babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606
  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, callback, progressCallBack, database, useArrayBuffer, onError, onRetry, retryStrategy) {
  6194. if (retryStrategy === void 0) { retryStrategy = null; }
  6195. url = Tools.CleanUrl(url);
  6196. url = Tools.PreprocessUrl(url);
  6197. var request = null;
  6198. var noIndexedDB = function (retryIndex) {
  6199. var oldRequest = request;
  6200. request = new XMLHttpRequest();
  6201. var loadUrl = Tools.BaseUrl + url;
  6202. request.open('GET', loadUrl, true);
  6203. if (useArrayBuffer) {
  6204. request.responseType = "arraybuffer";
  6205. }
  6206. if (progressCallBack) {
  6207. request.onprogress = progressCallBack;
  6208. }
  6209. request.onreadystatechange = function () {
  6210. var req = request;
  6211. // In case of undefined state in some browsers.
  6212. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6213. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6214. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6215. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6216. return;
  6217. }
  6218. retryStrategy = retryStrategy || Tools.DefaultRetryStrategy;
  6219. if (retryStrategy) {
  6220. var waitTime = retryStrategy(loadUrl, req, retryIndex || 0);
  6221. if (waitTime !== -1) {
  6222. setTimeout(function () { return noIndexedDB((retryIndex || 0) + 1); }, waitTime);
  6223. return;
  6224. }
  6225. }
  6226. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6227. if (onError) {
  6228. onError(req, e);
  6229. }
  6230. else {
  6231. throw e;
  6232. }
  6233. }
  6234. };
  6235. request.send();
  6236. if (oldRequest && onRetry) {
  6237. onRetry(oldRequest, request);
  6238. }
  6239. };
  6240. var loadFromIndexedDB = function () {
  6241. if (database) {
  6242. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6243. }
  6244. };
  6245. // If file and file input are set
  6246. if (url.indexOf("file:") !== -1) {
  6247. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6248. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6249. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6250. return request;
  6251. }
  6252. }
  6253. // Caching all files
  6254. if (database && database.enableSceneOffline) {
  6255. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6256. }
  6257. else {
  6258. noIndexedDB();
  6259. }
  6260. return request;
  6261. };
  6262. /**
  6263. * Load a script (identified by an url). When the url returns, the
  6264. * content of this file is added into a new script element, attached to the DOM (body element)
  6265. */
  6266. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6267. var head = document.getElementsByTagName('head')[0];
  6268. var script = document.createElement('script');
  6269. script.type = 'text/javascript';
  6270. script.src = scriptUrl;
  6271. script.onload = function () {
  6272. if (onSuccess) {
  6273. onSuccess();
  6274. }
  6275. };
  6276. script.onerror = function (e) {
  6277. if (onError) {
  6278. onError("Unable to load script", e);
  6279. }
  6280. };
  6281. head.appendChild(script);
  6282. };
  6283. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6284. var reader = new FileReader();
  6285. reader.onload = function (e) {
  6286. //target doesn't have result from ts 1.3
  6287. callback(e.target['result']);
  6288. };
  6289. reader.onprogress = progressCallback;
  6290. reader.readAsDataURL(fileToLoad);
  6291. };
  6292. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6293. var reader = new FileReader();
  6294. reader.onerror = function (e) {
  6295. Tools.Log("Error while reading file: " + fileToLoad.name);
  6296. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6297. };
  6298. reader.onload = function (e) {
  6299. //target doesn't have result from ts 1.3
  6300. callback(e.target['result']);
  6301. };
  6302. if (progressCallBack) {
  6303. reader.onprogress = progressCallBack;
  6304. }
  6305. if (!useArrayBuffer) {
  6306. // Asynchronous read
  6307. reader.readAsText(fileToLoad);
  6308. }
  6309. else {
  6310. reader.readAsArrayBuffer(fileToLoad);
  6311. }
  6312. };
  6313. //returns a downloadable url to a file content.
  6314. Tools.FileAsURL = function (content) {
  6315. var fileBlob = new Blob([content]);
  6316. var url = window.URL || window.webkitURL;
  6317. var link = url.createObjectURL(fileBlob);
  6318. return link;
  6319. };
  6320. // Misc.
  6321. Tools.Format = function (value, decimals) {
  6322. if (decimals === void 0) { decimals = 2; }
  6323. return value.toFixed(decimals);
  6324. };
  6325. Tools.CheckExtends = function (v, min, max) {
  6326. if (v.x < min.x)
  6327. min.x = v.x;
  6328. if (v.y < min.y)
  6329. min.y = v.y;
  6330. if (v.z < min.z)
  6331. min.z = v.z;
  6332. if (v.x > max.x)
  6333. max.x = v.x;
  6334. if (v.y > max.y)
  6335. max.y = v.y;
  6336. if (v.z > max.z)
  6337. max.z = v.z;
  6338. };
  6339. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6340. for (var prop in source) {
  6341. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6342. continue;
  6343. }
  6344. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6345. continue;
  6346. }
  6347. var sourceValue = source[prop];
  6348. var typeOfSourceValue = typeof sourceValue;
  6349. if (typeOfSourceValue === "function") {
  6350. continue;
  6351. }
  6352. if (typeOfSourceValue === "object") {
  6353. if (sourceValue instanceof Array) {
  6354. destination[prop] = [];
  6355. if (sourceValue.length > 0) {
  6356. if (typeof sourceValue[0] == "object") {
  6357. for (var index = 0; index < sourceValue.length; index++) {
  6358. var clonedValue = cloneValue(sourceValue[index], destination);
  6359. if (destination[prop].indexOf(clonedValue) === -1) {
  6360. destination[prop].push(clonedValue);
  6361. }
  6362. }
  6363. }
  6364. else {
  6365. destination[prop] = sourceValue.slice(0);
  6366. }
  6367. }
  6368. }
  6369. else {
  6370. destination[prop] = cloneValue(sourceValue, destination);
  6371. }
  6372. }
  6373. else {
  6374. destination[prop] = sourceValue;
  6375. }
  6376. }
  6377. };
  6378. Tools.IsEmpty = function (obj) {
  6379. for (var i in obj) {
  6380. if (obj.hasOwnProperty(i)) {
  6381. return false;
  6382. }
  6383. }
  6384. return true;
  6385. };
  6386. Tools.RegisterTopRootEvents = function (events) {
  6387. for (var index = 0; index < events.length; index++) {
  6388. var event = events[index];
  6389. window.addEventListener(event.name, event.handler, false);
  6390. try {
  6391. if (window.parent) {
  6392. window.parent.addEventListener(event.name, event.handler, false);
  6393. }
  6394. }
  6395. catch (e) {
  6396. // Silently fails...
  6397. }
  6398. }
  6399. };
  6400. Tools.UnregisterTopRootEvents = function (events) {
  6401. for (var index = 0; index < events.length; index++) {
  6402. var event = events[index];
  6403. window.removeEventListener(event.name, event.handler);
  6404. try {
  6405. if (window.parent) {
  6406. window.parent.removeEventListener(event.name, event.handler);
  6407. }
  6408. }
  6409. catch (e) {
  6410. // Silently fails...
  6411. }
  6412. }
  6413. };
  6414. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6415. if (mimeType === void 0) { mimeType = "image/png"; }
  6416. // Read the contents of the framebuffer
  6417. var numberOfChannelsByLine = width * 4;
  6418. var halfHeight = height / 2;
  6419. //Reading datas from WebGL
  6420. var data = engine.readPixels(0, 0, width, height);
  6421. //To flip image on Y axis.
  6422. for (var i = 0; i < halfHeight; i++) {
  6423. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6424. var currentCell = j + i * numberOfChannelsByLine;
  6425. var targetLine = height - i - 1;
  6426. var targetCell = j + targetLine * numberOfChannelsByLine;
  6427. var temp = data[currentCell];
  6428. data[currentCell] = data[targetCell];
  6429. data[targetCell] = temp;
  6430. }
  6431. }
  6432. // Create a 2D canvas to store the result
  6433. if (!screenshotCanvas) {
  6434. screenshotCanvas = document.createElement('canvas');
  6435. }
  6436. screenshotCanvas.width = width;
  6437. screenshotCanvas.height = height;
  6438. var context = screenshotCanvas.getContext('2d');
  6439. if (context) {
  6440. // Copy the pixels to a 2D canvas
  6441. var imageData = context.createImageData(width, height);
  6442. var castData = (imageData.data);
  6443. castData.set(data);
  6444. context.putImageData(imageData, 0, 0);
  6445. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6446. }
  6447. };
  6448. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6449. if (mimeType === void 0) { mimeType = "image/png"; }
  6450. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6451. if (successCallback) {
  6452. successCallback(base64Image);
  6453. }
  6454. else {
  6455. // We need HTMLCanvasElement.toBlob for HD screenshots
  6456. if (!screenshotCanvas.toBlob) {
  6457. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6458. screenshotCanvas.toBlob = function (callback, type, quality) {
  6459. var _this = this;
  6460. setTimeout(function () {
  6461. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6462. for (var i = 0; i < len; i++) {
  6463. arr[i] = binStr.charCodeAt(i);
  6464. }
  6465. callback(new Blob([arr], { type: type || 'image/png' }));
  6466. });
  6467. };
  6468. }
  6469. screenshotCanvas.toBlob(function (blob) {
  6470. var url = URL.createObjectURL(blob);
  6471. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6472. if (("download" in document.createElement("a"))) {
  6473. var a = window.document.createElement("a");
  6474. a.href = url;
  6475. if (fileName) {
  6476. a.setAttribute("download", fileName);
  6477. }
  6478. else {
  6479. var date = new Date();
  6480. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6481. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6482. }
  6483. window.document.body.appendChild(a);
  6484. a.addEventListener("click", function () {
  6485. if (a.parentElement) {
  6486. a.parentElement.removeChild(a);
  6487. }
  6488. });
  6489. a.click();
  6490. }
  6491. else {
  6492. var newWindow = window.open("");
  6493. if (!newWindow)
  6494. return;
  6495. var img = newWindow.document.createElement("img");
  6496. img.onload = function () {
  6497. // no longer need to read the blob so it's revoked
  6498. URL.revokeObjectURL(url);
  6499. };
  6500. img.src = url;
  6501. newWindow.document.body.appendChild(img);
  6502. }
  6503. });
  6504. }
  6505. };
  6506. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6507. if (mimeType === void 0) { mimeType = "image/png"; }
  6508. var width;
  6509. var height;
  6510. // If a precision value is specified
  6511. if (size.precision) {
  6512. width = Math.round(engine.getRenderWidth() * size.precision);
  6513. height = Math.round(width / engine.getAspectRatio(camera));
  6514. }
  6515. else if (size.width && size.height) {
  6516. width = size.width;
  6517. height = size.height;
  6518. }
  6519. else if (size.width && !size.height) {
  6520. width = size.width;
  6521. height = Math.round(width / engine.getAspectRatio(camera));
  6522. }
  6523. else if (size.height && !size.width) {
  6524. height = size.height;
  6525. width = Math.round(height * engine.getAspectRatio(camera));
  6526. }
  6527. else if (!isNaN(size)) {
  6528. height = size;
  6529. width = size;
  6530. }
  6531. else {
  6532. Tools.Error("Invalid 'size' parameter !");
  6533. return;
  6534. }
  6535. if (!screenshotCanvas) {
  6536. screenshotCanvas = document.createElement('canvas');
  6537. }
  6538. screenshotCanvas.width = width;
  6539. screenshotCanvas.height = height;
  6540. var renderContext = screenshotCanvas.getContext("2d");
  6541. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6542. var newWidth = width;
  6543. var newHeight = newWidth / ratio;
  6544. if (newHeight > height) {
  6545. newHeight = height;
  6546. newWidth = newHeight * ratio;
  6547. }
  6548. var offsetX = Math.max(0, width - newWidth) / 2;
  6549. var offsetY = Math.max(0, height - newHeight) / 2;
  6550. var renderingCanvas = engine.getRenderingCanvas();
  6551. if (renderContext && renderingCanvas) {
  6552. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6553. }
  6554. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6555. };
  6556. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6557. if (mimeType === void 0) { mimeType = "image/png"; }
  6558. if (samples === void 0) { samples = 1; }
  6559. if (antialiasing === void 0) { antialiasing = false; }
  6560. var width;
  6561. var height;
  6562. //If a precision value is specified
  6563. if (size.precision) {
  6564. width = Math.round(engine.getRenderWidth() * size.precision);
  6565. height = Math.round(width / engine.getAspectRatio(camera));
  6566. size = { width: width, height: height };
  6567. }
  6568. else if (size.width && size.height) {
  6569. width = size.width;
  6570. height = size.height;
  6571. }
  6572. else if (size.width && !size.height) {
  6573. width = size.width;
  6574. height = Math.round(width / engine.getAspectRatio(camera));
  6575. size = { width: width, height: height };
  6576. }
  6577. else if (size.height && !size.width) {
  6578. height = size.height;
  6579. width = Math.round(height * engine.getAspectRatio(camera));
  6580. size = { width: width, height: height };
  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. var scene = camera.getScene();
  6591. var previousCamera = null;
  6592. if (scene.activeCamera !== camera) {
  6593. previousCamera = scene.activeCamera;
  6594. scene.activeCamera = camera;
  6595. }
  6596. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6597. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6598. texture.renderList = null;
  6599. texture.samples = samples;
  6600. if (antialiasing) {
  6601. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6602. }
  6603. texture.onAfterRenderObservable.add(function () {
  6604. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6605. });
  6606. scene.incrementRenderId();
  6607. scene.resetCachedMaterial();
  6608. texture.render(true);
  6609. texture.dispose();
  6610. if (previousCamera) {
  6611. scene.activeCamera = previousCamera;
  6612. }
  6613. camera.getProjectionMatrix(true); // Force cache refresh;
  6614. };
  6615. // XHR response validator for local file scenario
  6616. Tools.ValidateXHRData = function (xhr, dataType) {
  6617. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6618. if (dataType === void 0) { dataType = 7; }
  6619. try {
  6620. if (dataType & 1) {
  6621. if (xhr.responseText && xhr.responseText.length > 0) {
  6622. return true;
  6623. }
  6624. else if (dataType === 1) {
  6625. return false;
  6626. }
  6627. }
  6628. if (dataType & 2) {
  6629. // Check header width and height since there is no "TGA" magic number
  6630. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6631. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6632. return true;
  6633. }
  6634. else if (dataType === 2) {
  6635. return false;
  6636. }
  6637. }
  6638. if (dataType & 4) {
  6639. // Check for the "DDS" magic number
  6640. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6641. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6642. return true;
  6643. }
  6644. else {
  6645. return false;
  6646. }
  6647. }
  6648. }
  6649. catch (e) {
  6650. // Global protection
  6651. }
  6652. return false;
  6653. };
  6654. /**
  6655. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6656. * Be aware Math.random() could cause collisions, but:
  6657. * "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"
  6658. */
  6659. Tools.RandomId = function () {
  6660. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6661. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6662. return v.toString(16);
  6663. });
  6664. };
  6665. Object.defineProperty(Tools, "NoneLogLevel", {
  6666. get: function () {
  6667. return Tools._NoneLogLevel;
  6668. },
  6669. enumerable: true,
  6670. configurable: true
  6671. });
  6672. Object.defineProperty(Tools, "MessageLogLevel", {
  6673. get: function () {
  6674. return Tools._MessageLogLevel;
  6675. },
  6676. enumerable: true,
  6677. configurable: true
  6678. });
  6679. Object.defineProperty(Tools, "WarningLogLevel", {
  6680. get: function () {
  6681. return Tools._WarningLogLevel;
  6682. },
  6683. enumerable: true,
  6684. configurable: true
  6685. });
  6686. Object.defineProperty(Tools, "ErrorLogLevel", {
  6687. get: function () {
  6688. return Tools._ErrorLogLevel;
  6689. },
  6690. enumerable: true,
  6691. configurable: true
  6692. });
  6693. Object.defineProperty(Tools, "AllLogLevel", {
  6694. get: function () {
  6695. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._AddLogEntry = function (entry) {
  6701. Tools._LogCache = entry + Tools._LogCache;
  6702. if (Tools.OnNewCacheEntry) {
  6703. Tools.OnNewCacheEntry(entry);
  6704. }
  6705. };
  6706. Tools._FormatMessage = function (message) {
  6707. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6708. var date = new Date();
  6709. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6710. };
  6711. Tools._LogDisabled = function (message) {
  6712. // nothing to do
  6713. };
  6714. Tools._LogEnabled = function (message) {
  6715. var formattedMessage = Tools._FormatMessage(message);
  6716. console.log("BJS - " + formattedMessage);
  6717. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6718. Tools._AddLogEntry(entry);
  6719. };
  6720. Tools._WarnDisabled = function (message) {
  6721. // nothing to do
  6722. };
  6723. Tools._WarnEnabled = function (message) {
  6724. var formattedMessage = Tools._FormatMessage(message);
  6725. console.warn("BJS - " + formattedMessage);
  6726. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6727. Tools._AddLogEntry(entry);
  6728. };
  6729. Tools._ErrorDisabled = function (message) {
  6730. // nothing to do
  6731. };
  6732. Tools._ErrorEnabled = function (message) {
  6733. Tools.errorsCount++;
  6734. var formattedMessage = Tools._FormatMessage(message);
  6735. console.error("BJS - " + formattedMessage);
  6736. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6737. Tools._AddLogEntry(entry);
  6738. };
  6739. Object.defineProperty(Tools, "LogCache", {
  6740. get: function () {
  6741. return Tools._LogCache;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Tools.ClearLogCache = function () {
  6747. Tools._LogCache = "";
  6748. Tools.errorsCount = 0;
  6749. };
  6750. Object.defineProperty(Tools, "LogLevels", {
  6751. set: function (level) {
  6752. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6753. Tools.Log = Tools._LogEnabled;
  6754. }
  6755. else {
  6756. Tools.Log = Tools._LogDisabled;
  6757. }
  6758. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6759. Tools.Warn = Tools._WarnEnabled;
  6760. }
  6761. else {
  6762. Tools.Warn = Tools._WarnDisabled;
  6763. }
  6764. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6765. Tools.Error = Tools._ErrorEnabled;
  6766. }
  6767. else {
  6768. Tools.Error = Tools._ErrorDisabled;
  6769. }
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Tools.IsWindowObjectExist = function () {
  6775. return (typeof window) !== "undefined";
  6776. };
  6777. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6778. get: function () {
  6779. return Tools._PerformanceNoneLogLevel;
  6780. },
  6781. enumerable: true,
  6782. configurable: true
  6783. });
  6784. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6785. get: function () {
  6786. return Tools._PerformanceUserMarkLogLevel;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6792. get: function () {
  6793. return Tools._PerformanceConsoleLogLevel;
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6799. set: function (level) {
  6800. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6801. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6802. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6803. return;
  6804. }
  6805. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6806. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6807. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6808. return;
  6809. }
  6810. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6811. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6817. };
  6818. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6819. };
  6820. Tools._StartUserMark = function (counterName, condition) {
  6821. if (condition === void 0) { condition = true; }
  6822. if (!Tools._performance) {
  6823. if (!Tools.IsWindowObjectExist()) {
  6824. return;
  6825. }
  6826. Tools._performance = window.performance;
  6827. }
  6828. if (!condition || !Tools._performance.mark) {
  6829. return;
  6830. }
  6831. Tools._performance.mark(counterName + "-Begin");
  6832. };
  6833. Tools._EndUserMark = function (counterName, condition) {
  6834. if (condition === void 0) { condition = true; }
  6835. if (!condition || !Tools._performance.mark) {
  6836. return;
  6837. }
  6838. Tools._performance.mark(counterName + "-End");
  6839. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6840. };
  6841. Tools._StartPerformanceConsole = function (counterName, condition) {
  6842. if (condition === void 0) { condition = true; }
  6843. if (!condition) {
  6844. return;
  6845. }
  6846. Tools._StartUserMark(counterName, condition);
  6847. if (console.time) {
  6848. console.time(counterName);
  6849. }
  6850. };
  6851. Tools._EndPerformanceConsole = function (counterName, condition) {
  6852. if (condition === void 0) { condition = true; }
  6853. if (!condition) {
  6854. return;
  6855. }
  6856. Tools._EndUserMark(counterName, condition);
  6857. if (console.time) {
  6858. console.timeEnd(counterName);
  6859. }
  6860. };
  6861. Object.defineProperty(Tools, "Now", {
  6862. get: function () {
  6863. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6864. return window.performance.now();
  6865. }
  6866. return new Date().getTime();
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. /**
  6872. * This method will return the name of the class used to create the instance of the given object.
  6873. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6874. * @param object the object to get the class name from
  6875. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6876. */
  6877. Tools.GetClassName = function (object, isType) {
  6878. if (isType === void 0) { isType = false; }
  6879. var name = null;
  6880. if (!isType && object.getClassName) {
  6881. name = object.getClassName();
  6882. }
  6883. else {
  6884. if (object instanceof Object) {
  6885. var classObj = isType ? object : Object.getPrototypeOf(object);
  6886. name = classObj.constructor["__bjsclassName__"];
  6887. }
  6888. if (!name) {
  6889. name = typeof object;
  6890. }
  6891. }
  6892. return name;
  6893. };
  6894. Tools.First = function (array, predicate) {
  6895. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6896. var el = array_1[_i];
  6897. if (predicate(el)) {
  6898. return el;
  6899. }
  6900. }
  6901. return null;
  6902. };
  6903. /**
  6904. * This method will return the name of the full name of the class, including its owning module (if any).
  6905. * 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).
  6906. * @param object the object to get the class name from
  6907. * @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.
  6908. */
  6909. Tools.getFullClassName = function (object, isType) {
  6910. if (isType === void 0) { isType = false; }
  6911. var className = null;
  6912. var moduleName = null;
  6913. if (!isType && object.getClassName) {
  6914. className = object.getClassName();
  6915. }
  6916. else {
  6917. if (object instanceof Object) {
  6918. var classObj = isType ? object : Object.getPrototypeOf(object);
  6919. className = classObj.constructor["__bjsclassName__"];
  6920. moduleName = classObj.constructor["__bjsmoduleName__"];
  6921. }
  6922. if (!className) {
  6923. className = typeof object;
  6924. }
  6925. }
  6926. if (!className) {
  6927. return null;
  6928. }
  6929. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6930. };
  6931. /**
  6932. * 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.
  6933. * @param array
  6934. */
  6935. Tools.arrayOrStringFeeder = function (array) {
  6936. return function (index) {
  6937. if (index >= array.length) {
  6938. return null;
  6939. }
  6940. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6941. if (val && val.getHashCode) {
  6942. val = val.getHashCode();
  6943. }
  6944. if (typeof val === "string") {
  6945. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6946. }
  6947. return val;
  6948. };
  6949. };
  6950. /**
  6951. * Compute the hashCode of a stream of number
  6952. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6953. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6954. * @return the hash code computed
  6955. */
  6956. Tools.hashCodeFromStream = function (feeder) {
  6957. // Based from here: http://stackoverflow.com/a/7616484/802124
  6958. var hash = 0;
  6959. var index = 0;
  6960. var chr = feeder(index++);
  6961. while (chr != null) {
  6962. hash = ((hash << 5) - hash) + chr;
  6963. hash |= 0; // Convert to 32bit integer
  6964. chr = feeder(index++);
  6965. }
  6966. return hash;
  6967. };
  6968. Tools.BaseUrl = "";
  6969. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  6970. /**
  6971. * Default behaviour for cors in the application.
  6972. * It can be a string if the expected behavior is identical in the entire app.
  6973. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  6974. */
  6975. Tools.CorsBehavior = "anonymous";
  6976. Tools.UseFallbackTexture = true;
  6977. /**
  6978. * Use this object to register external classes like custom textures or material
  6979. * to allow the laoders to instantiate them
  6980. */
  6981. Tools.RegisteredExternalClasses = {};
  6982. // Used in case of a texture loading problem
  6983. 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";
  6984. Tools.PreprocessUrl = function (url) {
  6985. return url;
  6986. };
  6987. // Logs
  6988. Tools._NoneLogLevel = 0;
  6989. Tools._MessageLogLevel = 1;
  6990. Tools._WarningLogLevel = 2;
  6991. Tools._ErrorLogLevel = 4;
  6992. Tools._LogCache = "";
  6993. Tools.errorsCount = 0;
  6994. Tools.Log = Tools._LogEnabled;
  6995. Tools.Warn = Tools._WarnEnabled;
  6996. Tools.Error = Tools._ErrorEnabled;
  6997. // Performances
  6998. Tools._PerformanceNoneLogLevel = 0;
  6999. Tools._PerformanceUserMarkLogLevel = 1;
  7000. Tools._PerformanceConsoleLogLevel = 2;
  7001. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7002. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7003. return Tools;
  7004. }());
  7005. BABYLON.Tools = Tools;
  7006. /**
  7007. * This class is used to track a performance counter which is number based.
  7008. * The user has access to many properties which give statistics of different nature
  7009. *
  7010. * The implementer can track two kinds of Performance Counter: time and count
  7011. * 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.
  7012. * 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.
  7013. */
  7014. var PerfCounter = /** @class */ (function () {
  7015. function PerfCounter() {
  7016. this._startMonitoringTime = 0;
  7017. this._min = 0;
  7018. this._max = 0;
  7019. this._average = 0;
  7020. this._lastSecAverage = 0;
  7021. this._current = 0;
  7022. this._totalValueCount = 0;
  7023. this._totalAccumulated = 0;
  7024. this._lastSecAccumulated = 0;
  7025. this._lastSecTime = 0;
  7026. this._lastSecValueCount = 0;
  7027. }
  7028. Object.defineProperty(PerfCounter.prototype, "min", {
  7029. /**
  7030. * Returns the smallest value ever
  7031. */
  7032. get: function () {
  7033. return this._min;
  7034. },
  7035. enumerable: true,
  7036. configurable: true
  7037. });
  7038. Object.defineProperty(PerfCounter.prototype, "max", {
  7039. /**
  7040. * Returns the biggest value ever
  7041. */
  7042. get: function () {
  7043. return this._max;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Object.defineProperty(PerfCounter.prototype, "average", {
  7049. /**
  7050. * Returns the average value since the performance counter is running
  7051. */
  7052. get: function () {
  7053. return this._average;
  7054. },
  7055. enumerable: true,
  7056. configurable: true
  7057. });
  7058. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7059. /**
  7060. * Returns the average value of the last second the counter was monitored
  7061. */
  7062. get: function () {
  7063. return this._lastSecAverage;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. Object.defineProperty(PerfCounter.prototype, "current", {
  7069. /**
  7070. * Returns the current value
  7071. */
  7072. get: function () {
  7073. return this._current;
  7074. },
  7075. enumerable: true,
  7076. configurable: true
  7077. });
  7078. Object.defineProperty(PerfCounter.prototype, "total", {
  7079. get: function () {
  7080. return this._totalAccumulated;
  7081. },
  7082. enumerable: true,
  7083. configurable: true
  7084. });
  7085. Object.defineProperty(PerfCounter.prototype, "count", {
  7086. get: function () {
  7087. return this._totalValueCount;
  7088. },
  7089. enumerable: true,
  7090. configurable: true
  7091. });
  7092. /**
  7093. * Call this method to start monitoring a new frame.
  7094. * 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.
  7095. */
  7096. PerfCounter.prototype.fetchNewFrame = function () {
  7097. this._totalValueCount++;
  7098. this._current = 0;
  7099. this._lastSecValueCount++;
  7100. };
  7101. /**
  7102. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7103. * @param newCount the count value to add to the monitored count
  7104. * @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.
  7105. */
  7106. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7107. if (!PerfCounter.Enabled) {
  7108. return;
  7109. }
  7110. this._current += newCount;
  7111. if (fetchResult) {
  7112. this._fetchResult();
  7113. }
  7114. };
  7115. /**
  7116. * Start monitoring this performance counter
  7117. */
  7118. PerfCounter.prototype.beginMonitoring = function () {
  7119. if (!PerfCounter.Enabled) {
  7120. return;
  7121. }
  7122. this._startMonitoringTime = Tools.Now;
  7123. };
  7124. /**
  7125. * Compute the time lapsed since the previous beginMonitoring() call.
  7126. * @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
  7127. */
  7128. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7129. if (newFrame === void 0) { newFrame = true; }
  7130. if (!PerfCounter.Enabled) {
  7131. return;
  7132. }
  7133. if (newFrame) {
  7134. this.fetchNewFrame();
  7135. }
  7136. var currentTime = Tools.Now;
  7137. this._current = currentTime - this._startMonitoringTime;
  7138. if (newFrame) {
  7139. this._fetchResult();
  7140. }
  7141. };
  7142. PerfCounter.prototype._fetchResult = function () {
  7143. this._totalAccumulated += this._current;
  7144. this._lastSecAccumulated += this._current;
  7145. // Min/Max update
  7146. this._min = Math.min(this._min, this._current);
  7147. this._max = Math.max(this._max, this._current);
  7148. this._average = this._totalAccumulated / this._totalValueCount;
  7149. // Reset last sec?
  7150. var now = Tools.Now;
  7151. if ((now - this._lastSecTime) > 1000) {
  7152. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7153. this._lastSecTime = now;
  7154. this._lastSecAccumulated = 0;
  7155. this._lastSecValueCount = 0;
  7156. }
  7157. };
  7158. PerfCounter.Enabled = true;
  7159. return PerfCounter;
  7160. }());
  7161. BABYLON.PerfCounter = PerfCounter;
  7162. /**
  7163. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7164. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7165. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7166. * @param name The name of the class, case should be preserved
  7167. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7168. */
  7169. function className(name, module) {
  7170. return function (target) {
  7171. target["__bjsclassName__"] = name;
  7172. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7173. };
  7174. }
  7175. BABYLON.className = className;
  7176. /**
  7177. * An implementation of a loop for asynchronous functions.
  7178. */
  7179. var AsyncLoop = /** @class */ (function () {
  7180. /**
  7181. * Constroctor.
  7182. * @param iterations the number of iterations.
  7183. * @param _fn the function to run each iteration
  7184. * @param _successCallback the callback that will be called upon succesful execution
  7185. * @param offset starting offset.
  7186. */
  7187. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7188. if (offset === void 0) { offset = 0; }
  7189. this.iterations = iterations;
  7190. this._fn = _fn;
  7191. this._successCallback = _successCallback;
  7192. this.index = offset - 1;
  7193. this._done = false;
  7194. }
  7195. /**
  7196. * Execute the next iteration. Must be called after the last iteration was finished.
  7197. */
  7198. AsyncLoop.prototype.executeNext = function () {
  7199. if (!this._done) {
  7200. if (this.index + 1 < this.iterations) {
  7201. ++this.index;
  7202. this._fn(this);
  7203. }
  7204. else {
  7205. this.breakLoop();
  7206. }
  7207. }
  7208. };
  7209. /**
  7210. * Break the loop and run the success callback.
  7211. */
  7212. AsyncLoop.prototype.breakLoop = function () {
  7213. this._done = true;
  7214. this._successCallback();
  7215. };
  7216. /**
  7217. * Helper function
  7218. */
  7219. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7220. if (offset === void 0) { offset = 0; }
  7221. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7222. loop.executeNext();
  7223. return loop;
  7224. };
  7225. /**
  7226. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7227. * @param iterations total number of iterations
  7228. * @param syncedIterations number of synchronous iterations in each async iteration.
  7229. * @param fn the function to call each iteration.
  7230. * @param callback a success call back that will be called when iterating stops.
  7231. * @param breakFunction a break condition (optional)
  7232. * @param timeout timeout settings for the setTimeout function. default - 0.
  7233. * @constructor
  7234. */
  7235. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7236. if (timeout === void 0) { timeout = 0; }
  7237. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7238. if (breakFunction && breakFunction())
  7239. loop.breakLoop();
  7240. else {
  7241. setTimeout(function () {
  7242. for (var i = 0; i < syncedIterations; ++i) {
  7243. var iteration = (loop.index * syncedIterations) + i;
  7244. if (iteration >= iterations)
  7245. break;
  7246. fn(iteration);
  7247. if (breakFunction && breakFunction()) {
  7248. loop.breakLoop();
  7249. break;
  7250. }
  7251. }
  7252. loop.executeNext();
  7253. }, timeout);
  7254. }
  7255. }, callback);
  7256. };
  7257. return AsyncLoop;
  7258. }());
  7259. BABYLON.AsyncLoop = AsyncLoop;
  7260. })(BABYLON || (BABYLON = {}));
  7261. //# sourceMappingURL=babylon.tools.js.map
  7262. var BABYLON;
  7263. (function (BABYLON) {
  7264. var Internals;
  7265. (function (Internals) {
  7266. var _AlphaState = /** @class */ (function () {
  7267. /**
  7268. * Initializes the state.
  7269. */
  7270. function _AlphaState() {
  7271. this._isAlphaBlendDirty = false;
  7272. this._isBlendFunctionParametersDirty = false;
  7273. this._isBlendEquationParametersDirty = false;
  7274. this._isBlendConstantsDirty = false;
  7275. this._alphaBlend = false;
  7276. this._blendFunctionParameters = new Array(4);
  7277. this._blendEquationParameters = new Array(2);
  7278. this._blendConstants = new Array(4);
  7279. this.reset();
  7280. }
  7281. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7282. get: function () {
  7283. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7289. get: function () {
  7290. return this._alphaBlend;
  7291. },
  7292. set: function (value) {
  7293. if (this._alphaBlend === value) {
  7294. return;
  7295. }
  7296. this._alphaBlend = value;
  7297. this._isAlphaBlendDirty = true;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7303. if (this._blendConstants[0] === r &&
  7304. this._blendConstants[1] === g &&
  7305. this._blendConstants[2] === b &&
  7306. this._blendConstants[3] === a) {
  7307. return;
  7308. }
  7309. this._blendConstants[0] = r;
  7310. this._blendConstants[1] = g;
  7311. this._blendConstants[2] = b;
  7312. this._blendConstants[3] = a;
  7313. this._isBlendConstantsDirty = true;
  7314. };
  7315. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7316. if (this._blendFunctionParameters[0] === value0 &&
  7317. this._blendFunctionParameters[1] === value1 &&
  7318. this._blendFunctionParameters[2] === value2 &&
  7319. this._blendFunctionParameters[3] === value3) {
  7320. return;
  7321. }
  7322. this._blendFunctionParameters[0] = value0;
  7323. this._blendFunctionParameters[1] = value1;
  7324. this._blendFunctionParameters[2] = value2;
  7325. this._blendFunctionParameters[3] = value3;
  7326. this._isBlendFunctionParametersDirty = true;
  7327. };
  7328. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7329. if (this._blendEquationParameters[0] === rgb &&
  7330. this._blendEquationParameters[1] === alpha) {
  7331. return;
  7332. }
  7333. this._blendEquationParameters[0] = rgb;
  7334. this._blendEquationParameters[1] = alpha;
  7335. this._isBlendEquationParametersDirty = true;
  7336. };
  7337. _AlphaState.prototype.reset = function () {
  7338. this._alphaBlend = false;
  7339. this._blendFunctionParameters[0] = null;
  7340. this._blendFunctionParameters[1] = null;
  7341. this._blendFunctionParameters[2] = null;
  7342. this._blendFunctionParameters[3] = null;
  7343. this._blendEquationParameters[0] = null;
  7344. this._blendEquationParameters[1] = null;
  7345. this._blendConstants[0] = null;
  7346. this._blendConstants[1] = null;
  7347. this._blendConstants[2] = null;
  7348. this._blendConstants[3] = null;
  7349. this._isAlphaBlendDirty = true;
  7350. this._isBlendFunctionParametersDirty = false;
  7351. this._isBlendEquationParametersDirty = false;
  7352. this._isBlendConstantsDirty = false;
  7353. };
  7354. _AlphaState.prototype.apply = function (gl) {
  7355. if (!this.isDirty) {
  7356. return;
  7357. }
  7358. // Alpha blend
  7359. if (this._isAlphaBlendDirty) {
  7360. if (this._alphaBlend) {
  7361. gl.enable(gl.BLEND);
  7362. }
  7363. else {
  7364. gl.disable(gl.BLEND);
  7365. }
  7366. this._isAlphaBlendDirty = false;
  7367. }
  7368. // Alpha function
  7369. if (this._isBlendFunctionParametersDirty) {
  7370. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7371. this._isBlendFunctionParametersDirty = false;
  7372. }
  7373. // Alpha equation
  7374. if (this._isBlendEquationParametersDirty) {
  7375. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7376. this._isBlendEquationParametersDirty = false;
  7377. }
  7378. // Constants
  7379. if (this._isBlendConstantsDirty) {
  7380. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7381. this._isBlendConstantsDirty = false;
  7382. }
  7383. };
  7384. return _AlphaState;
  7385. }());
  7386. Internals._AlphaState = _AlphaState;
  7387. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7388. })(BABYLON || (BABYLON = {}));
  7389. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7390. var BABYLON;
  7391. (function (BABYLON) {
  7392. var Internals;
  7393. (function (Internals) {
  7394. var _DepthCullingState = /** @class */ (function () {
  7395. /**
  7396. * Initializes the state.
  7397. */
  7398. function _DepthCullingState() {
  7399. this._isDepthTestDirty = false;
  7400. this._isDepthMaskDirty = false;
  7401. this._isDepthFuncDirty = false;
  7402. this._isCullFaceDirty = false;
  7403. this._isCullDirty = false;
  7404. this._isZOffsetDirty = false;
  7405. this.reset();
  7406. }
  7407. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7408. get: function () {
  7409. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7415. get: function () {
  7416. return this._zOffset;
  7417. },
  7418. set: function (value) {
  7419. if (this._zOffset === value) {
  7420. return;
  7421. }
  7422. this._zOffset = value;
  7423. this._isZOffsetDirty = true;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7429. get: function () {
  7430. return this._cullFace;
  7431. },
  7432. set: function (value) {
  7433. if (this._cullFace === value) {
  7434. return;
  7435. }
  7436. this._cullFace = value;
  7437. this._isCullFaceDirty = true;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7443. get: function () {
  7444. return this._cull;
  7445. },
  7446. set: function (value) {
  7447. if (this._cull === value) {
  7448. return;
  7449. }
  7450. this._cull = value;
  7451. this._isCullDirty = true;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7457. get: function () {
  7458. return this._depthFunc;
  7459. },
  7460. set: function (value) {
  7461. if (this._depthFunc === value) {
  7462. return;
  7463. }
  7464. this._depthFunc = value;
  7465. this._isDepthFuncDirty = true;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7471. get: function () {
  7472. return this._depthMask;
  7473. },
  7474. set: function (value) {
  7475. if (this._depthMask === value) {
  7476. return;
  7477. }
  7478. this._depthMask = value;
  7479. this._isDepthMaskDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7485. get: function () {
  7486. return this._depthTest;
  7487. },
  7488. set: function (value) {
  7489. if (this._depthTest === value) {
  7490. return;
  7491. }
  7492. this._depthTest = value;
  7493. this._isDepthTestDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. _DepthCullingState.prototype.reset = function () {
  7499. this._depthMask = true;
  7500. this._depthTest = true;
  7501. this._depthFunc = null;
  7502. this._cullFace = null;
  7503. this._cull = null;
  7504. this._zOffset = 0;
  7505. this._isDepthTestDirty = true;
  7506. this._isDepthMaskDirty = true;
  7507. this._isDepthFuncDirty = false;
  7508. this._isCullFaceDirty = false;
  7509. this._isCullDirty = false;
  7510. this._isZOffsetDirty = false;
  7511. };
  7512. _DepthCullingState.prototype.apply = function (gl) {
  7513. if (!this.isDirty) {
  7514. return;
  7515. }
  7516. // Cull
  7517. if (this._isCullDirty) {
  7518. if (this.cull) {
  7519. gl.enable(gl.CULL_FACE);
  7520. }
  7521. else {
  7522. gl.disable(gl.CULL_FACE);
  7523. }
  7524. this._isCullDirty = false;
  7525. }
  7526. // Cull face
  7527. if (this._isCullFaceDirty) {
  7528. gl.cullFace(this.cullFace);
  7529. this._isCullFaceDirty = false;
  7530. }
  7531. // Depth mask
  7532. if (this._isDepthMaskDirty) {
  7533. gl.depthMask(this.depthMask);
  7534. this._isDepthMaskDirty = false;
  7535. }
  7536. // Depth test
  7537. if (this._isDepthTestDirty) {
  7538. if (this.depthTest) {
  7539. gl.enable(gl.DEPTH_TEST);
  7540. }
  7541. else {
  7542. gl.disable(gl.DEPTH_TEST);
  7543. }
  7544. this._isDepthTestDirty = false;
  7545. }
  7546. // Depth func
  7547. if (this._isDepthFuncDirty) {
  7548. gl.depthFunc(this.depthFunc);
  7549. this._isDepthFuncDirty = false;
  7550. }
  7551. // zOffset
  7552. if (this._isZOffsetDirty) {
  7553. if (this.zOffset) {
  7554. gl.enable(gl.POLYGON_OFFSET_FILL);
  7555. gl.polygonOffset(this.zOffset, 0);
  7556. }
  7557. else {
  7558. gl.disable(gl.POLYGON_OFFSET_FILL);
  7559. }
  7560. this._isZOffsetDirty = false;
  7561. }
  7562. };
  7563. return _DepthCullingState;
  7564. }());
  7565. Internals._DepthCullingState = _DepthCullingState;
  7566. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7567. })(BABYLON || (BABYLON = {}));
  7568. //# sourceMappingURL=babylon.depthCullingState.js.map
  7569. var BABYLON;
  7570. (function (BABYLON) {
  7571. var Internals;
  7572. (function (Internals) {
  7573. var _StencilState = /** @class */ (function () {
  7574. function _StencilState() {
  7575. this._isStencilTestDirty = false;
  7576. this._isStencilMaskDirty = false;
  7577. this._isStencilFuncDirty = false;
  7578. this._isStencilOpDirty = false;
  7579. this.reset();
  7580. }
  7581. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7582. get: function () {
  7583. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7589. get: function () {
  7590. return this._stencilFunc;
  7591. },
  7592. set: function (value) {
  7593. if (this._stencilFunc === value) {
  7594. return;
  7595. }
  7596. this._stencilFunc = value;
  7597. this._isStencilFuncDirty = true;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7603. get: function () {
  7604. return this._stencilFuncRef;
  7605. },
  7606. set: function (value) {
  7607. if (this._stencilFuncRef === value) {
  7608. return;
  7609. }
  7610. this._stencilFuncRef = value;
  7611. this._isStencilFuncDirty = true;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7617. get: function () {
  7618. return this._stencilFuncMask;
  7619. },
  7620. set: function (value) {
  7621. if (this._stencilFuncMask === value) {
  7622. return;
  7623. }
  7624. this._stencilFuncMask = value;
  7625. this._isStencilFuncDirty = true;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7631. get: function () {
  7632. return this._stencilOpStencilFail;
  7633. },
  7634. set: function (value) {
  7635. if (this._stencilOpStencilFail === value) {
  7636. return;
  7637. }
  7638. this._stencilOpStencilFail = value;
  7639. this._isStencilOpDirty = true;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7645. get: function () {
  7646. return this._stencilOpDepthFail;
  7647. },
  7648. set: function (value) {
  7649. if (this._stencilOpDepthFail === value) {
  7650. return;
  7651. }
  7652. this._stencilOpDepthFail = value;
  7653. this._isStencilOpDirty = true;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7659. get: function () {
  7660. return this._stencilOpStencilDepthPass;
  7661. },
  7662. set: function (value) {
  7663. if (this._stencilOpStencilDepthPass === value) {
  7664. return;
  7665. }
  7666. this._stencilOpStencilDepthPass = value;
  7667. this._isStencilOpDirty = true;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7673. get: function () {
  7674. return this._stencilMask;
  7675. },
  7676. set: function (value) {
  7677. if (this._stencilMask === value) {
  7678. return;
  7679. }
  7680. this._stencilMask = value;
  7681. this._isStencilMaskDirty = true;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7687. get: function () {
  7688. return this._stencilTest;
  7689. },
  7690. set: function (value) {
  7691. if (this._stencilTest === value) {
  7692. return;
  7693. }
  7694. this._stencilTest = value;
  7695. this._isStencilTestDirty = true;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. _StencilState.prototype.reset = function () {
  7701. this._stencilTest = false;
  7702. this._stencilMask = 0xFF;
  7703. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7704. this._stencilFuncRef = 1;
  7705. this._stencilFuncMask = 0xFF;
  7706. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7707. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7708. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7709. this._isStencilTestDirty = true;
  7710. this._isStencilMaskDirty = true;
  7711. this._isStencilFuncDirty = true;
  7712. this._isStencilOpDirty = true;
  7713. };
  7714. _StencilState.prototype.apply = function (gl) {
  7715. if (!this.isDirty) {
  7716. return;
  7717. }
  7718. // Stencil test
  7719. if (this._isStencilTestDirty) {
  7720. if (this.stencilTest) {
  7721. gl.enable(gl.STENCIL_TEST);
  7722. }
  7723. else {
  7724. gl.disable(gl.STENCIL_TEST);
  7725. }
  7726. this._isStencilTestDirty = false;
  7727. }
  7728. // Stencil mask
  7729. if (this._isStencilMaskDirty) {
  7730. gl.stencilMask(this.stencilMask);
  7731. this._isStencilMaskDirty = false;
  7732. }
  7733. // Stencil func
  7734. if (this._isStencilFuncDirty) {
  7735. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7736. this._isStencilFuncDirty = false;
  7737. }
  7738. // Stencil op
  7739. if (this._isStencilOpDirty) {
  7740. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7741. this._isStencilOpDirty = false;
  7742. }
  7743. };
  7744. return _StencilState;
  7745. }());
  7746. Internals._StencilState = _StencilState;
  7747. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7748. })(BABYLON || (BABYLON = {}));
  7749. //# sourceMappingURL=babylon.stencilState.js.map
  7750. var BABYLON;
  7751. (function (BABYLON) {
  7752. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7753. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7754. };
  7755. var compileRawShader = function (gl, source, type) {
  7756. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7757. gl.shaderSource(shader, source);
  7758. gl.compileShader(shader);
  7759. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7760. var log = gl.getShaderInfoLog(shader);
  7761. if (log) {
  7762. throw new Error(log);
  7763. }
  7764. }
  7765. if (!shader) {
  7766. throw new Error("Something went wrong while compile the shader.");
  7767. }
  7768. return shader;
  7769. };
  7770. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7771. var magFilter = gl.NEAREST;
  7772. var minFilter = gl.NEAREST;
  7773. switch (samplingMode) {
  7774. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7775. magFilter = gl.LINEAR;
  7776. if (generateMipMaps) {
  7777. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7778. }
  7779. else {
  7780. minFilter = gl.LINEAR;
  7781. }
  7782. break;
  7783. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7784. magFilter = gl.LINEAR;
  7785. if (generateMipMaps) {
  7786. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7787. }
  7788. else {
  7789. minFilter = gl.LINEAR;
  7790. }
  7791. break;
  7792. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7793. magFilter = gl.NEAREST;
  7794. if (generateMipMaps) {
  7795. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7796. }
  7797. else {
  7798. minFilter = gl.NEAREST;
  7799. }
  7800. break;
  7801. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7802. magFilter = gl.NEAREST;
  7803. if (generateMipMaps) {
  7804. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7805. }
  7806. else {
  7807. minFilter = gl.NEAREST;
  7808. }
  7809. break;
  7810. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7811. magFilter = gl.NEAREST;
  7812. if (generateMipMaps) {
  7813. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7814. }
  7815. else {
  7816. minFilter = gl.LINEAR;
  7817. }
  7818. break;
  7819. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7820. magFilter = gl.NEAREST;
  7821. if (generateMipMaps) {
  7822. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7823. }
  7824. else {
  7825. minFilter = gl.LINEAR;
  7826. }
  7827. break;
  7828. case BABYLON.Texture.NEAREST_LINEAR:
  7829. magFilter = gl.NEAREST;
  7830. minFilter = gl.LINEAR;
  7831. break;
  7832. case BABYLON.Texture.NEAREST_NEAREST:
  7833. magFilter = gl.NEAREST;
  7834. minFilter = gl.NEAREST;
  7835. break;
  7836. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7837. magFilter = gl.LINEAR;
  7838. if (generateMipMaps) {
  7839. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7840. }
  7841. else {
  7842. minFilter = gl.NEAREST;
  7843. }
  7844. break;
  7845. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7846. magFilter = gl.LINEAR;
  7847. if (generateMipMaps) {
  7848. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7849. }
  7850. else {
  7851. minFilter = gl.NEAREST;
  7852. }
  7853. break;
  7854. case BABYLON.Texture.LINEAR_LINEAR:
  7855. magFilter = gl.LINEAR;
  7856. minFilter = gl.LINEAR;
  7857. break;
  7858. case BABYLON.Texture.LINEAR_NEAREST:
  7859. magFilter = gl.LINEAR;
  7860. minFilter = gl.NEAREST;
  7861. break;
  7862. }
  7863. return {
  7864. min: minFilter,
  7865. mag: magFilter
  7866. };
  7867. };
  7868. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7869. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7870. var img;
  7871. var onload = function () {
  7872. loadedImages[index] = img;
  7873. loadedImages._internalCount++;
  7874. if (scene) {
  7875. scene._removePendingData(img);
  7876. }
  7877. if (loadedImages._internalCount === 6) {
  7878. onfinish(loadedImages);
  7879. }
  7880. };
  7881. var onerror = function (message, exception) {
  7882. if (scene) {
  7883. scene._removePendingData(img);
  7884. }
  7885. if (onErrorCallBack) {
  7886. onErrorCallBack(message, exception);
  7887. }
  7888. };
  7889. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7890. if (scene) {
  7891. scene._addPendingData(img);
  7892. }
  7893. };
  7894. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7895. if (onError === void 0) { onError = null; }
  7896. var loadedImages = [];
  7897. loadedImages._internalCount = 0;
  7898. for (var index = 0; index < 6; index++) {
  7899. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7900. }
  7901. };
  7902. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7903. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7904. var onload = function (data) {
  7905. loadedFiles[index] = data;
  7906. loadedFiles._internalCount++;
  7907. if (loadedFiles._internalCount === 6) {
  7908. onfinish(loadedFiles);
  7909. }
  7910. };
  7911. var onerror = function (request, exception) {
  7912. if (onErrorCallBack && request) {
  7913. onErrorCallBack(request.status + " " + request.statusText, exception);
  7914. }
  7915. };
  7916. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7917. };
  7918. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7919. if (onError === void 0) { onError = null; }
  7920. var loadedFiles = [];
  7921. loadedFiles._internalCount = 0;
  7922. for (var index = 0; index < 6; index++) {
  7923. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7924. }
  7925. };
  7926. var BufferPointer = /** @class */ (function () {
  7927. function BufferPointer() {
  7928. }
  7929. return BufferPointer;
  7930. }());
  7931. var InstancingAttributeInfo = /** @class */ (function () {
  7932. function InstancingAttributeInfo() {
  7933. }
  7934. return InstancingAttributeInfo;
  7935. }());
  7936. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7937. /**
  7938. * Define options used to create a render target texture
  7939. */
  7940. var RenderTargetCreationOptions = /** @class */ (function () {
  7941. function RenderTargetCreationOptions() {
  7942. }
  7943. return RenderTargetCreationOptions;
  7944. }());
  7945. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7946. /**
  7947. * Regroup several parameters relative to the browser in use
  7948. */
  7949. var EngineCapabilities = /** @class */ (function () {
  7950. function EngineCapabilities() {
  7951. }
  7952. return EngineCapabilities;
  7953. }());
  7954. BABYLON.EngineCapabilities = EngineCapabilities;
  7955. /**
  7956. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7957. */
  7958. var Engine = /** @class */ (function () {
  7959. /**
  7960. * @constructor
  7961. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7962. * @param {boolean} [antialias] - enable antialias
  7963. * @param options - further options to be sent to the getContext function
  7964. */
  7965. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7966. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7967. var _this = this;
  7968. // Public members
  7969. this.forcePOTTextures = false;
  7970. this.isFullscreen = false;
  7971. this.isPointerLock = false;
  7972. this.cullBackFaces = true;
  7973. this.renderEvenInBackground = true;
  7974. this.preventCacheWipeBetweenFrames = false;
  7975. // To enable/disable IDB support and avoid XHR on .manifest
  7976. this.enableOfflineSupport = false;
  7977. this.scenes = new Array();
  7978. this.postProcesses = new Array();
  7979. // Observables
  7980. /**
  7981. * Observable event triggered each time the rendering canvas is resized
  7982. */
  7983. this.onResizeObservable = new BABYLON.Observable();
  7984. /**
  7985. * Observable event triggered each time the canvas loses focus
  7986. */
  7987. this.onCanvasBlurObservable = new BABYLON.Observable();
  7988. /**
  7989. * Observable event triggered each time the canvas gains focus
  7990. */
  7991. this.onCanvasFocusObservable = new BABYLON.Observable();
  7992. /**
  7993. * Observable event triggered each time the canvas receives pointerout event
  7994. */
  7995. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7996. /**
  7997. * Observable event triggered before each texture is initialized
  7998. */
  7999. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8000. //WebVR
  8001. this._vrDisplay = undefined;
  8002. this._vrSupported = false;
  8003. this._vrExclusivePointerMode = false;
  8004. // Uniform buffers list
  8005. this.disableUniformBuffers = false;
  8006. this._uniformBuffers = new Array();
  8007. // Observables
  8008. /**
  8009. * Observable raised when the engine begins a new frame
  8010. */
  8011. this.onBeginFrameObservable = new BABYLON.Observable();
  8012. /**
  8013. * Observable raised when the engine ends the current frame
  8014. */
  8015. this.onEndFrameObservable = new BABYLON.Observable();
  8016. /**
  8017. * Observable raised when the engine is about to compile a shader
  8018. */
  8019. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8020. /**
  8021. * Observable raised when the engine has jsut compiled a shader
  8022. */
  8023. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8024. this._windowIsBackground = false;
  8025. this._webGLVersion = 1.0;
  8026. this._badOS = false;
  8027. this._badDesktopOS = false;
  8028. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8029. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8030. this.onVRRequestPresentStart = new BABYLON.Observable();
  8031. this._colorWrite = true;
  8032. this._drawCalls = new BABYLON.PerfCounter();
  8033. this._renderingQueueLaunched = false;
  8034. this._activeRenderLoops = new Array();
  8035. // Deterministic lockstepMaxSteps
  8036. this._deterministicLockstep = false;
  8037. this._lockstepMaxSteps = 4;
  8038. // Lost context
  8039. this.onContextLostObservable = new BABYLON.Observable();
  8040. this.onContextRestoredObservable = new BABYLON.Observable();
  8041. this._contextWasLost = false;
  8042. this._doNotHandleContextLost = false;
  8043. // FPS
  8044. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8045. this._fps = 60;
  8046. this._deltaTime = 0;
  8047. /**
  8048. * Turn this value on if you want to pause FPS computation when in background
  8049. */
  8050. this.disablePerformanceMonitorInBackground = false;
  8051. // States
  8052. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8053. this._stencilState = new BABYLON.Internals._StencilState();
  8054. this._alphaState = new BABYLON.Internals._AlphaState();
  8055. this._alphaMode = Engine.ALPHA_DISABLE;
  8056. // Cache
  8057. this._internalTexturesCache = new Array();
  8058. this._boundTexturesCache = {};
  8059. this._boundTexturesOrder = new Array();
  8060. this._compiledEffects = {};
  8061. this._vertexAttribArraysEnabled = [];
  8062. this._uintIndicesCurrentlySet = false;
  8063. this._currentBoundBuffer = new Array();
  8064. this._currentBufferPointers = new Array();
  8065. this._currentInstanceLocations = new Array();
  8066. this._currentInstanceBuffers = new Array();
  8067. this._vaoRecordInProgress = false;
  8068. this._mustWipeVertexAttributes = false;
  8069. this._nextFreeTextureSlot = 0;
  8070. // Hardware supported Compressed Textures
  8071. this._texturesSupported = new Array();
  8072. this._onVRFullScreenTriggered = function () {
  8073. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8074. //get the old size before we change
  8075. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8076. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8077. //get the width and height, change the render size
  8078. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8079. _this.setHardwareScalingLevel(1);
  8080. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8081. }
  8082. else {
  8083. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8084. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8085. }
  8086. };
  8087. this._boundUniforms = {};
  8088. var canvas = null;
  8089. Engine.Instances.push(this);
  8090. if (!canvasOrContext) {
  8091. return;
  8092. }
  8093. options = options || {};
  8094. if (canvasOrContext.getContext) {
  8095. canvas = canvasOrContext;
  8096. this._renderingCanvas = canvas;
  8097. if (antialias != null) {
  8098. options.antialias = antialias;
  8099. }
  8100. if (options.deterministicLockstep === undefined) {
  8101. options.deterministicLockstep = false;
  8102. }
  8103. if (options.lockstepMaxSteps === undefined) {
  8104. options.lockstepMaxSteps = 4;
  8105. }
  8106. if (options.preserveDrawingBuffer === undefined) {
  8107. options.preserveDrawingBuffer = false;
  8108. }
  8109. if (options.audioEngine === undefined) {
  8110. options.audioEngine = true;
  8111. }
  8112. if (options.stencil === undefined) {
  8113. options.stencil = true;
  8114. }
  8115. this._deterministicLockstep = options.deterministicLockstep;
  8116. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8117. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8118. // Exceptions
  8119. if (!options.disableWebGL2Support) {
  8120. if (navigator && navigator.userAgent) {
  8121. var ua = navigator.userAgent;
  8122. for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
  8123. var exception = _a[_i];
  8124. if (ua.indexOf(exception) > -1) {
  8125. this.disableUniformBuffers = true;
  8126. break;
  8127. }
  8128. }
  8129. }
  8130. }
  8131. // GL
  8132. if (!options.disableWebGL2Support) {
  8133. try {
  8134. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8135. if (this._gl) {
  8136. this._webGLVersion = 2.0;
  8137. }
  8138. }
  8139. catch (e) {
  8140. // Do nothing
  8141. }
  8142. }
  8143. if (!this._gl) {
  8144. if (!canvas) {
  8145. throw new Error("The provided canvas is null or undefined.");
  8146. }
  8147. try {
  8148. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8149. }
  8150. catch (e) {
  8151. throw new Error("WebGL not supported");
  8152. }
  8153. }
  8154. if (!this._gl) {
  8155. throw new Error("WebGL not supported");
  8156. }
  8157. this._onCanvasFocus = function () {
  8158. _this.onCanvasFocusObservable.notifyObservers(_this);
  8159. };
  8160. this._onCanvasBlur = function () {
  8161. _this.onCanvasBlurObservable.notifyObservers(_this);
  8162. };
  8163. canvas.addEventListener("focus", this._onCanvasFocus);
  8164. canvas.addEventListener("blur", this._onCanvasBlur);
  8165. this._onBlur = function () {
  8166. if (_this.disablePerformanceMonitorInBackground) {
  8167. _this._performanceMonitor.disable();
  8168. }
  8169. _this._windowIsBackground = true;
  8170. };
  8171. this._onFocus = function () {
  8172. if (_this.disablePerformanceMonitorInBackground) {
  8173. _this._performanceMonitor.enable();
  8174. }
  8175. _this._windowIsBackground = false;
  8176. };
  8177. this._onCanvasPointerOut = function () {
  8178. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8179. };
  8180. window.addEventListener("blur", this._onBlur);
  8181. window.addEventListener("focus", this._onFocus);
  8182. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8183. // Context lost
  8184. if (!this._doNotHandleContextLost) {
  8185. this._onContextLost = function (evt) {
  8186. evt.preventDefault();
  8187. _this._contextWasLost = true;
  8188. BABYLON.Tools.Warn("WebGL context lost.");
  8189. _this.onContextLostObservable.notifyObservers(_this);
  8190. };
  8191. this._onContextRestored = function (evt) {
  8192. // Adding a timeout to avoid race condition at browser level
  8193. setTimeout(function () {
  8194. // Rebuild gl context
  8195. _this._initGLContext();
  8196. // Rebuild effects
  8197. _this._rebuildEffects();
  8198. // Rebuild textures
  8199. _this._rebuildInternalTextures();
  8200. // Rebuild buffers
  8201. _this._rebuildBuffers();
  8202. // Cache
  8203. _this.wipeCaches(true);
  8204. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8205. _this.onContextRestoredObservable.notifyObservers(_this);
  8206. _this._contextWasLost = false;
  8207. }, 0);
  8208. };
  8209. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8210. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8211. }
  8212. }
  8213. else {
  8214. this._gl = canvasOrContext;
  8215. this._renderingCanvas = this._gl.canvas;
  8216. if (this._gl.renderbufferStorageMultisample) {
  8217. this._webGLVersion = 2.0;
  8218. }
  8219. options.stencil = this._gl.getContextAttributes().stencil;
  8220. }
  8221. // Viewport
  8222. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8223. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8224. this.resize();
  8225. this._isStencilEnable = options.stencil ? true : false;
  8226. this._initGLContext();
  8227. if (canvas) {
  8228. // Fullscreen
  8229. this._onFullscreenChange = function () {
  8230. if (document.fullscreen !== undefined) {
  8231. _this.isFullscreen = document.fullscreen;
  8232. }
  8233. else if (document.mozFullScreen !== undefined) {
  8234. _this.isFullscreen = document.mozFullScreen;
  8235. }
  8236. else if (document.webkitIsFullScreen !== undefined) {
  8237. _this.isFullscreen = document.webkitIsFullScreen;
  8238. }
  8239. else if (document.msIsFullScreen !== undefined) {
  8240. _this.isFullscreen = document.msIsFullScreen;
  8241. }
  8242. // Pointer lock
  8243. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8244. canvas.requestPointerLock = canvas.requestPointerLock ||
  8245. canvas.msRequestPointerLock ||
  8246. canvas.mozRequestPointerLock ||
  8247. canvas.webkitRequestPointerLock;
  8248. if (canvas.requestPointerLock) {
  8249. canvas.requestPointerLock();
  8250. }
  8251. }
  8252. };
  8253. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8254. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8255. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8256. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8257. // Pointer lock
  8258. this._onPointerLockChange = function () {
  8259. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8260. document.webkitPointerLockElement === canvas ||
  8261. document.msPointerLockElement === canvas ||
  8262. document.pointerLockElement === canvas);
  8263. };
  8264. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8265. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8266. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8267. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8268. this._onVRDisplayPointerRestricted = function () {
  8269. if (canvas) {
  8270. canvas.requestPointerLock();
  8271. }
  8272. };
  8273. this._onVRDisplayPointerUnrestricted = function () {
  8274. document.exitPointerLock();
  8275. };
  8276. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8277. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8278. }
  8279. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8280. Engine.audioEngine = new BABYLON.AudioEngine();
  8281. }
  8282. // Prepare buffer pointers
  8283. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8284. this._currentBufferPointers[i] = new BufferPointer();
  8285. }
  8286. // Load WebVR Devices
  8287. if (options.autoEnableWebVR) {
  8288. this.initWebVR();
  8289. }
  8290. // Detect if we are running on a faulty buggy OS.
  8291. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8292. // Detect if we are running on a faulty buggy desktop OS.
  8293. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8294. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8295. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8296. }
  8297. Object.defineProperty(Engine, "LastCreatedEngine", {
  8298. get: function () {
  8299. if (Engine.Instances.length === 0) {
  8300. return null;
  8301. }
  8302. return Engine.Instances[Engine.Instances.length - 1];
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. Object.defineProperty(Engine, "LastCreatedScene", {
  8308. get: function () {
  8309. var lastCreatedEngine = Engine.LastCreatedEngine;
  8310. if (!lastCreatedEngine) {
  8311. return null;
  8312. }
  8313. if (lastCreatedEngine.scenes.length === 0) {
  8314. return null;
  8315. }
  8316. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. /**
  8322. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8323. */
  8324. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8325. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8326. var engine = Engine.Instances[engineIndex];
  8327. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8328. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8329. }
  8330. }
  8331. };
  8332. Object.defineProperty(Engine, "NEVER", {
  8333. get: function () {
  8334. return Engine._NEVER;
  8335. },
  8336. enumerable: true,
  8337. configurable: true
  8338. });
  8339. Object.defineProperty(Engine, "ALWAYS", {
  8340. get: function () {
  8341. return Engine._ALWAYS;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(Engine, "LESS", {
  8347. get: function () {
  8348. return Engine._LESS;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine, "EQUAL", {
  8354. get: function () {
  8355. return Engine._EQUAL;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Engine, "LEQUAL", {
  8361. get: function () {
  8362. return Engine._LEQUAL;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Object.defineProperty(Engine, "GREATER", {
  8368. get: function () {
  8369. return Engine._GREATER;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(Engine, "GEQUAL", {
  8375. get: function () {
  8376. return Engine._GEQUAL;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(Engine, "NOTEQUAL", {
  8382. get: function () {
  8383. return Engine._NOTEQUAL;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(Engine, "KEEP", {
  8389. get: function () {
  8390. return Engine._KEEP;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(Engine, "REPLACE", {
  8396. get: function () {
  8397. return Engine._REPLACE;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(Engine, "INCR", {
  8403. get: function () {
  8404. return Engine._INCR;
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. Object.defineProperty(Engine, "DECR", {
  8410. get: function () {
  8411. return Engine._DECR;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(Engine, "INVERT", {
  8417. get: function () {
  8418. return Engine._INVERT;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. Object.defineProperty(Engine, "INCR_WRAP", {
  8424. get: function () {
  8425. return Engine._INCR_WRAP;
  8426. },
  8427. enumerable: true,
  8428. configurable: true
  8429. });
  8430. Object.defineProperty(Engine, "DECR_WRAP", {
  8431. get: function () {
  8432. return Engine._DECR_WRAP;
  8433. },
  8434. enumerable: true,
  8435. configurable: true
  8436. });
  8437. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8438. get: function () {
  8439. return Engine._ALPHA_DISABLE;
  8440. },
  8441. enumerable: true,
  8442. configurable: true
  8443. });
  8444. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8445. get: function () {
  8446. return Engine._ALPHA_ONEONE;
  8447. },
  8448. enumerable: true,
  8449. configurable: true
  8450. });
  8451. Object.defineProperty(Engine, "ALPHA_ADD", {
  8452. get: function () {
  8453. return Engine._ALPHA_ADD;
  8454. },
  8455. enumerable: true,
  8456. configurable: true
  8457. });
  8458. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8459. get: function () {
  8460. return Engine._ALPHA_COMBINE;
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8466. get: function () {
  8467. return Engine._ALPHA_SUBTRACT;
  8468. },
  8469. enumerable: true,
  8470. configurable: true
  8471. });
  8472. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8473. get: function () {
  8474. return Engine._ALPHA_MULTIPLY;
  8475. },
  8476. enumerable: true,
  8477. configurable: true
  8478. });
  8479. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8480. get: function () {
  8481. return Engine._ALPHA_MAXIMIZED;
  8482. },
  8483. enumerable: true,
  8484. configurable: true
  8485. });
  8486. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8487. get: function () {
  8488. return Engine._ALPHA_PREMULTIPLIED;
  8489. },
  8490. enumerable: true,
  8491. configurable: true
  8492. });
  8493. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8494. get: function () {
  8495. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8496. },
  8497. enumerable: true,
  8498. configurable: true
  8499. });
  8500. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8501. get: function () {
  8502. return Engine._ALPHA_INTERPOLATE;
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8508. get: function () {
  8509. return Engine._ALPHA_SCREENMODE;
  8510. },
  8511. enumerable: true,
  8512. configurable: true
  8513. });
  8514. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8515. get: function () {
  8516. return Engine._DELAYLOADSTATE_NONE;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8522. get: function () {
  8523. return Engine._DELAYLOADSTATE_LOADED;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8529. get: function () {
  8530. return Engine._DELAYLOADSTATE_LOADING;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8536. get: function () {
  8537. return Engine._DELAYLOADSTATE_NOTLOADED;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8543. get: function () {
  8544. return Engine._TEXTUREFORMAT_ALPHA;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8550. get: function () {
  8551. return Engine._TEXTUREFORMAT_LUMINANCE;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8557. get: function () {
  8558. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8564. get: function () {
  8565. return Engine._TEXTUREFORMAT_RGB;
  8566. },
  8567. enumerable: true,
  8568. configurable: true
  8569. });
  8570. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8571. get: function () {
  8572. return Engine._TEXTUREFORMAT_RGBA;
  8573. },
  8574. enumerable: true,
  8575. configurable: true
  8576. });
  8577. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8578. get: function () {
  8579. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8580. },
  8581. enumerable: true,
  8582. configurable: true
  8583. });
  8584. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8585. get: function () {
  8586. return Engine._TEXTURETYPE_FLOAT;
  8587. },
  8588. enumerable: true,
  8589. configurable: true
  8590. });
  8591. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8592. get: function () {
  8593. return Engine._TEXTURETYPE_HALF_FLOAT;
  8594. },
  8595. enumerable: true,
  8596. configurable: true
  8597. });
  8598. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8599. get: function () {
  8600. return Engine._SCALEMODE_FLOOR;
  8601. },
  8602. enumerable: true,
  8603. configurable: true
  8604. });
  8605. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8606. get: function () {
  8607. return Engine._SCALEMODE_NEAREST;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8613. get: function () {
  8614. return Engine._SCALEMODE_CEILING;
  8615. },
  8616. enumerable: true,
  8617. configurable: true
  8618. });
  8619. Object.defineProperty(Engine, "Version", {
  8620. get: function () {
  8621. return "3.2.0-alpha0";
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8627. get: function () {
  8628. return this._vrExclusivePointerMode;
  8629. },
  8630. enumerable: true,
  8631. configurable: true
  8632. });
  8633. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8634. get: function () {
  8635. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8636. },
  8637. enumerable: true,
  8638. configurable: true
  8639. });
  8640. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8641. get: function () {
  8642. return this._webGLVersion < 2 || this.forcePOTTextures;
  8643. },
  8644. enumerable: true,
  8645. configurable: true
  8646. });
  8647. Object.defineProperty(Engine.prototype, "badOS", {
  8648. get: function () {
  8649. return this._badOS;
  8650. },
  8651. enumerable: true,
  8652. configurable: true
  8653. });
  8654. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8655. get: function () {
  8656. return this._badDesktopOS;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8662. get: function () {
  8663. return this._performanceMonitor;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8669. get: function () {
  8670. return this._texturesSupported;
  8671. },
  8672. enumerable: true,
  8673. configurable: true
  8674. });
  8675. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8676. get: function () {
  8677. return this._textureFormatInUse;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(Engine.prototype, "currentViewport", {
  8683. get: function () {
  8684. return this._cachedViewport;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8690. // Empty texture
  8691. get: function () {
  8692. if (!this._emptyTexture) {
  8693. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8694. }
  8695. return this._emptyTexture;
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8701. get: function () {
  8702. if (!this._emptyTexture3D) {
  8703. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8704. }
  8705. return this._emptyTexture3D;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8711. get: function () {
  8712. if (!this._emptyCubeTexture) {
  8713. var faceData = new Uint8Array(4);
  8714. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8715. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8716. }
  8717. return this._emptyCubeTexture;
  8718. },
  8719. enumerable: true,
  8720. configurable: true
  8721. });
  8722. Engine.prototype._rebuildInternalTextures = function () {
  8723. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8724. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8725. var internalTexture = currentState_1[_i];
  8726. internalTexture._rebuild();
  8727. }
  8728. };
  8729. Engine.prototype._rebuildEffects = function () {
  8730. for (var key in this._compiledEffects) {
  8731. var effect = this._compiledEffects[key];
  8732. effect._prepareEffect();
  8733. }
  8734. BABYLON.Effect.ResetCache();
  8735. };
  8736. Engine.prototype._rebuildBuffers = function () {
  8737. // Index / Vertex
  8738. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8739. var scene = _a[_i];
  8740. scene.resetCachedMaterial();
  8741. scene._rebuildGeometries();
  8742. scene._rebuildTextures();
  8743. }
  8744. // Uniforms
  8745. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8746. var uniformBuffer = _c[_b];
  8747. uniformBuffer._rebuild();
  8748. }
  8749. };
  8750. Engine.prototype._initGLContext = function () {
  8751. // Caps
  8752. this._caps = new EngineCapabilities();
  8753. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8754. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8755. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8756. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8757. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8758. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8759. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8760. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8761. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8762. // Infos
  8763. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8764. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8765. if (rendererInfo != null) {
  8766. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8767. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8768. }
  8769. if (!this._glVendor) {
  8770. this._glVendor = "Unknown vendor";
  8771. }
  8772. if (!this._glRenderer) {
  8773. this._glRenderer = "Unknown renderer";
  8774. }
  8775. // Constants
  8776. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8777. if (this._gl.RGBA16F !== 0x881A) {
  8778. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8779. }
  8780. if (this._gl.RGBA32F !== 0x8814) {
  8781. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8782. }
  8783. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8784. this._gl.DEPTH24_STENCIL8 = 35056;
  8785. }
  8786. // Extensions
  8787. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8788. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8789. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8790. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8791. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8792. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8793. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8794. 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');
  8795. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8796. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8797. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8798. this._caps.highPrecisionShaderSupported = true;
  8799. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8800. if (this._caps.timerQuery) {
  8801. if (this._webGLVersion === 1) {
  8802. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8803. }
  8804. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8805. }
  8806. // Checks if some of the format renders first to allow the use of webgl inspector.
  8807. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8808. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8809. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8810. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8811. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8812. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8813. if (this._webGLVersion > 1) {
  8814. this._gl.HALF_FLOAT_OES = 0x140B;
  8815. }
  8816. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8817. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8818. // Draw buffers
  8819. if (this._webGLVersion > 1) {
  8820. this._caps.drawBuffersExtension = true;
  8821. }
  8822. else {
  8823. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8824. if (drawBuffersExtension !== null) {
  8825. this._caps.drawBuffersExtension = true;
  8826. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8827. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8828. for (var i = 0; i < 16; i++) {
  8829. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8830. }
  8831. }
  8832. else {
  8833. this._caps.drawBuffersExtension = false;
  8834. }
  8835. }
  8836. // Depth Texture
  8837. if (this._webGLVersion > 1) {
  8838. this._caps.depthTextureExtension = true;
  8839. }
  8840. else {
  8841. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8842. if (depthTextureExtension != null) {
  8843. this._caps.depthTextureExtension = true;
  8844. }
  8845. }
  8846. // Vertex array object
  8847. if (this._webGLVersion > 1) {
  8848. this._caps.vertexArrayObject = true;
  8849. }
  8850. else {
  8851. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8852. if (vertexArrayObjectExtension != null) {
  8853. this._caps.vertexArrayObject = true;
  8854. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8855. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8856. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8857. }
  8858. else {
  8859. this._caps.vertexArrayObject = false;
  8860. }
  8861. }
  8862. // Instances count
  8863. if (this._webGLVersion > 1) {
  8864. this._caps.instancedArrays = true;
  8865. }
  8866. else {
  8867. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8868. if (instanceExtension != null) {
  8869. this._caps.instancedArrays = true;
  8870. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8871. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8872. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8873. }
  8874. else {
  8875. this._caps.instancedArrays = false;
  8876. }
  8877. }
  8878. // Intelligently add supported compressed formats in order to check for.
  8879. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8880. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8881. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8882. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8883. if (this._caps.astc)
  8884. this.texturesSupported.push('-astc.ktx');
  8885. if (this._caps.s3tc)
  8886. this.texturesSupported.push('-dxt.ktx');
  8887. if (this._caps.pvrtc)
  8888. this.texturesSupported.push('-pvrtc.ktx');
  8889. if (this._caps.etc2)
  8890. this.texturesSupported.push('-etc2.ktx');
  8891. if (this._caps.etc1)
  8892. this.texturesSupported.push('-etc1.ktx');
  8893. if (this._gl.getShaderPrecisionFormat) {
  8894. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8895. if (highp) {
  8896. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8897. }
  8898. }
  8899. // Depth buffer
  8900. this.setDepthBuffer(true);
  8901. this.setDepthFunctionToLessOrEqual();
  8902. this.setDepthWrite(true);
  8903. };
  8904. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8905. get: function () {
  8906. return this._webGLVersion;
  8907. },
  8908. enumerable: true,
  8909. configurable: true
  8910. });
  8911. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8912. /**
  8913. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8914. */
  8915. get: function () {
  8916. return this._isStencilEnable;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Engine.prototype._prepareWorkingCanvas = function () {
  8922. if (this._workingCanvas) {
  8923. return;
  8924. }
  8925. this._workingCanvas = document.createElement("canvas");
  8926. var context = this._workingCanvas.getContext("2d");
  8927. if (context) {
  8928. this._workingContext = context;
  8929. }
  8930. };
  8931. Engine.prototype.resetTextureCache = function () {
  8932. for (var key in this._boundTexturesCache) {
  8933. var boundTexture = this._boundTexturesCache[key];
  8934. if (boundTexture) {
  8935. this._removeDesignatedSlot(boundTexture);
  8936. }
  8937. this._boundTexturesCache[key] = null;
  8938. }
  8939. this._nextFreeTextureSlot = 0;
  8940. this._activeChannel = -1;
  8941. };
  8942. Engine.prototype.isDeterministicLockStep = function () {
  8943. return this._deterministicLockstep;
  8944. };
  8945. Engine.prototype.getLockstepMaxSteps = function () {
  8946. return this._lockstepMaxSteps;
  8947. };
  8948. Engine.prototype.getGlInfo = function () {
  8949. return {
  8950. vendor: this._glVendor,
  8951. renderer: this._glRenderer,
  8952. version: this._glVersion
  8953. };
  8954. };
  8955. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8956. if (useScreen === void 0) { useScreen = false; }
  8957. var viewport = camera.viewport;
  8958. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8959. };
  8960. Engine.prototype.getRenderWidth = function (useScreen) {
  8961. if (useScreen === void 0) { useScreen = false; }
  8962. if (!useScreen && this._currentRenderTarget) {
  8963. return this._currentRenderTarget.width;
  8964. }
  8965. return this._gl.drawingBufferWidth;
  8966. };
  8967. Engine.prototype.getRenderHeight = function (useScreen) {
  8968. if (useScreen === void 0) { useScreen = false; }
  8969. if (!useScreen && this._currentRenderTarget) {
  8970. return this._currentRenderTarget.height;
  8971. }
  8972. return this._gl.drawingBufferHeight;
  8973. };
  8974. Engine.prototype.getRenderingCanvas = function () {
  8975. return this._renderingCanvas;
  8976. };
  8977. Engine.prototype.getRenderingCanvasClientRect = function () {
  8978. if (!this._renderingCanvas) {
  8979. return null;
  8980. }
  8981. return this._renderingCanvas.getBoundingClientRect();
  8982. };
  8983. Engine.prototype.setHardwareScalingLevel = function (level) {
  8984. this._hardwareScalingLevel = level;
  8985. this.resize();
  8986. };
  8987. Engine.prototype.getHardwareScalingLevel = function () {
  8988. return this._hardwareScalingLevel;
  8989. };
  8990. Engine.prototype.getLoadedTexturesCache = function () {
  8991. return this._internalTexturesCache;
  8992. };
  8993. Engine.prototype.getCaps = function () {
  8994. return this._caps;
  8995. };
  8996. Object.defineProperty(Engine.prototype, "drawCalls", {
  8997. /** The number of draw calls submitted last frame */
  8998. get: function () {
  8999. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9000. return 0;
  9001. },
  9002. enumerable: true,
  9003. configurable: true
  9004. });
  9005. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9006. get: function () {
  9007. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9008. return null;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Engine.prototype.getDepthFunction = function () {
  9014. return this._depthCullingState.depthFunc;
  9015. };
  9016. Engine.prototype.setDepthFunction = function (depthFunc) {
  9017. this._depthCullingState.depthFunc = depthFunc;
  9018. };
  9019. Engine.prototype.setDepthFunctionToGreater = function () {
  9020. this._depthCullingState.depthFunc = this._gl.GREATER;
  9021. };
  9022. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9023. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9024. };
  9025. Engine.prototype.setDepthFunctionToLess = function () {
  9026. this._depthCullingState.depthFunc = this._gl.LESS;
  9027. };
  9028. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9029. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9030. };
  9031. Engine.prototype.getStencilBuffer = function () {
  9032. return this._stencilState.stencilTest;
  9033. };
  9034. Engine.prototype.setStencilBuffer = function (enable) {
  9035. this._stencilState.stencilTest = enable;
  9036. };
  9037. Engine.prototype.getStencilMask = function () {
  9038. return this._stencilState.stencilMask;
  9039. };
  9040. Engine.prototype.setStencilMask = function (mask) {
  9041. this._stencilState.stencilMask = mask;
  9042. };
  9043. Engine.prototype.getStencilFunction = function () {
  9044. return this._stencilState.stencilFunc;
  9045. };
  9046. Engine.prototype.getStencilFunctionReference = function () {
  9047. return this._stencilState.stencilFuncRef;
  9048. };
  9049. Engine.prototype.getStencilFunctionMask = function () {
  9050. return this._stencilState.stencilFuncMask;
  9051. };
  9052. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9053. this._stencilState.stencilFunc = stencilFunc;
  9054. };
  9055. Engine.prototype.setStencilFunctionReference = function (reference) {
  9056. this._stencilState.stencilFuncRef = reference;
  9057. };
  9058. Engine.prototype.setStencilFunctionMask = function (mask) {
  9059. this._stencilState.stencilFuncMask = mask;
  9060. };
  9061. Engine.prototype.getStencilOperationFail = function () {
  9062. return this._stencilState.stencilOpStencilFail;
  9063. };
  9064. Engine.prototype.getStencilOperationDepthFail = function () {
  9065. return this._stencilState.stencilOpDepthFail;
  9066. };
  9067. Engine.prototype.getStencilOperationPass = function () {
  9068. return this._stencilState.stencilOpStencilDepthPass;
  9069. };
  9070. Engine.prototype.setStencilOperationFail = function (operation) {
  9071. this._stencilState.stencilOpStencilFail = operation;
  9072. };
  9073. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9074. this._stencilState.stencilOpDepthFail = operation;
  9075. };
  9076. Engine.prototype.setStencilOperationPass = function (operation) {
  9077. this._stencilState.stencilOpStencilDepthPass = operation;
  9078. };
  9079. Engine.prototype.setDitheringState = function (value) {
  9080. if (value) {
  9081. this._gl.enable(this._gl.DITHER);
  9082. }
  9083. else {
  9084. this._gl.disable(this._gl.DITHER);
  9085. }
  9086. };
  9087. Engine.prototype.setRasterizerState = function (value) {
  9088. if (value) {
  9089. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9090. }
  9091. else {
  9092. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9093. }
  9094. };
  9095. /**
  9096. * stop executing a render loop function and remove it from the execution array
  9097. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9098. */
  9099. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9100. if (!renderFunction) {
  9101. this._activeRenderLoops = [];
  9102. return;
  9103. }
  9104. var index = this._activeRenderLoops.indexOf(renderFunction);
  9105. if (index >= 0) {
  9106. this._activeRenderLoops.splice(index, 1);
  9107. }
  9108. };
  9109. Engine.prototype._renderLoop = function () {
  9110. if (!this._contextWasLost) {
  9111. var shouldRender = true;
  9112. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9113. shouldRender = false;
  9114. }
  9115. if (shouldRender) {
  9116. // Start new frame
  9117. this.beginFrame();
  9118. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9119. var renderFunction = this._activeRenderLoops[index];
  9120. renderFunction();
  9121. }
  9122. // Present
  9123. this.endFrame();
  9124. }
  9125. }
  9126. if (this._activeRenderLoops.length > 0) {
  9127. // Register new frame
  9128. var requester = null;
  9129. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9130. requester = this._vrDisplay;
  9131. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9132. }
  9133. else {
  9134. this._renderingQueueLaunched = false;
  9135. }
  9136. };
  9137. /**
  9138. * Register and execute a render loop. The engine can have more than one render function.
  9139. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9140. * @example
  9141. * engine.runRenderLoop(function () {
  9142. * scene.render()
  9143. * })
  9144. */
  9145. Engine.prototype.runRenderLoop = function (renderFunction) {
  9146. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9147. return;
  9148. }
  9149. this._activeRenderLoops.push(renderFunction);
  9150. if (!this._renderingQueueLaunched) {
  9151. this._renderingQueueLaunched = true;
  9152. this._bindedRenderFunction = this._renderLoop.bind(this);
  9153. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9154. }
  9155. };
  9156. /**
  9157. * Toggle full screen mode.
  9158. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9159. * @param {any} options - an options object to be sent to the requestFullscreen function
  9160. */
  9161. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9162. if (this.isFullscreen) {
  9163. BABYLON.Tools.ExitFullscreen();
  9164. }
  9165. else {
  9166. this._pointerLockRequested = requestPointerLock;
  9167. if (this._renderingCanvas) {
  9168. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9169. }
  9170. }
  9171. };
  9172. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9173. if (stencil === void 0) { stencil = false; }
  9174. this.applyStates();
  9175. var mode = 0;
  9176. if (backBuffer && color) {
  9177. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9178. mode |= this._gl.COLOR_BUFFER_BIT;
  9179. }
  9180. if (depth) {
  9181. this._gl.clearDepth(1.0);
  9182. mode |= this._gl.DEPTH_BUFFER_BIT;
  9183. }
  9184. if (stencil) {
  9185. this._gl.clearStencil(0);
  9186. mode |= this._gl.STENCIL_BUFFER_BIT;
  9187. }
  9188. this._gl.clear(mode);
  9189. };
  9190. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9191. var gl = this._gl;
  9192. // Save state
  9193. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9194. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9195. // Change state
  9196. gl.enable(gl.SCISSOR_TEST);
  9197. gl.scissor(x, y, width, height);
  9198. // Clear
  9199. this.clear(clearColor, true, true, true);
  9200. // Restore state
  9201. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9202. if (curScissor === true) {
  9203. gl.enable(gl.SCISSOR_TEST);
  9204. }
  9205. else {
  9206. gl.disable(gl.SCISSOR_TEST);
  9207. }
  9208. };
  9209. /**
  9210. * Set the WebGL's viewport
  9211. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9212. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9213. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9214. */
  9215. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9216. var width = requiredWidth || this.getRenderWidth();
  9217. var height = requiredHeight || this.getRenderHeight();
  9218. var x = viewport.x || 0;
  9219. var y = viewport.y || 0;
  9220. this._cachedViewport = viewport;
  9221. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9222. };
  9223. /**
  9224. * Directly set the WebGL Viewport
  9225. * The x, y, width & height are directly passed to the WebGL call
  9226. * @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.
  9227. */
  9228. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9229. var currentViewport = this._cachedViewport;
  9230. this._cachedViewport = null;
  9231. this._gl.viewport(x, y, width, height);
  9232. return currentViewport;
  9233. };
  9234. Engine.prototype.beginFrame = function () {
  9235. this.onBeginFrameObservable.notifyObservers(this);
  9236. this._measureFps();
  9237. };
  9238. Engine.prototype.endFrame = function () {
  9239. //force a flush in case we are using a bad OS.
  9240. if (this._badOS) {
  9241. this.flushFramebuffer();
  9242. }
  9243. //submit frame to the vr device, if enabled
  9244. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9245. // TODO: We should only submit the frame if we read frameData successfully.
  9246. this._vrDisplay.submitFrame();
  9247. }
  9248. this.onEndFrameObservable.notifyObservers(this);
  9249. };
  9250. /**
  9251. * resize the view according to the canvas' size.
  9252. * @example
  9253. * window.addEventListener("resize", function () {
  9254. * engine.resize();
  9255. * });
  9256. */
  9257. Engine.prototype.resize = function () {
  9258. // We're not resizing the size of the canvas while in VR mode & presenting
  9259. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9260. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9261. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9262. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9263. }
  9264. };
  9265. /**
  9266. * force a specific size of the canvas
  9267. * @param {number} width - the new canvas' width
  9268. * @param {number} height - the new canvas' height
  9269. */
  9270. Engine.prototype.setSize = function (width, height) {
  9271. if (!this._renderingCanvas) {
  9272. return;
  9273. }
  9274. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9275. return;
  9276. }
  9277. this._renderingCanvas.width = width;
  9278. this._renderingCanvas.height = height;
  9279. for (var index = 0; index < this.scenes.length; index++) {
  9280. var scene = this.scenes[index];
  9281. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9282. var cam = scene.cameras[camIndex];
  9283. cam._currentRenderId = 0;
  9284. }
  9285. }
  9286. if (this.onResizeObservable.hasObservers) {
  9287. this.onResizeObservable.notifyObservers(this);
  9288. }
  9289. };
  9290. // WebVR functions
  9291. Engine.prototype.isVRDevicePresent = function () {
  9292. return !!this._vrDisplay;
  9293. };
  9294. Engine.prototype.getVRDevice = function () {
  9295. return this._vrDisplay;
  9296. };
  9297. Engine.prototype.initWebVR = function () {
  9298. var _this = this;
  9299. var notifyObservers = function () {
  9300. var eventArgs = {
  9301. vrDisplay: _this._vrDisplay,
  9302. vrSupported: _this._vrSupported
  9303. };
  9304. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9305. };
  9306. if (!this._onVrDisplayConnect) {
  9307. this._onVrDisplayConnect = function (event) {
  9308. _this._vrDisplay = event.display;
  9309. notifyObservers();
  9310. };
  9311. this._onVrDisplayDisconnect = function () {
  9312. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9313. _this._vrDisplay = undefined;
  9314. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9315. notifyObservers();
  9316. };
  9317. this._onVrDisplayPresentChange = function () {
  9318. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9319. };
  9320. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9321. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9322. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9323. }
  9324. this._getVRDisplays(notifyObservers);
  9325. return this.onVRDisplayChangedObservable;
  9326. };
  9327. Engine.prototype.enableVR = function () {
  9328. var _this = this;
  9329. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9330. var onResolved = function () {
  9331. _this.onVRRequestPresentComplete.notifyObservers(true);
  9332. _this._onVRFullScreenTriggered();
  9333. };
  9334. var onRejected = function () {
  9335. _this.onVRRequestPresentComplete.notifyObservers(false);
  9336. };
  9337. this.onVRRequestPresentStart.notifyObservers(this);
  9338. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9339. }
  9340. };
  9341. Engine.prototype.disableVR = function () {
  9342. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9343. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9344. }
  9345. };
  9346. Engine.prototype._getVRDisplays = function (callback) {
  9347. var _this = this;
  9348. var getWebVRDevices = function (devices) {
  9349. _this._vrSupported = true;
  9350. // note that devices may actually be an empty array. This is fine;
  9351. // we expect this._vrDisplay to be undefined in this case.
  9352. return _this._vrDisplay = devices[0];
  9353. };
  9354. if (navigator.getVRDisplays) {
  9355. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9356. // TODO: System CANNOT support WebVR, despite API presence.
  9357. _this._vrSupported = false;
  9358. callback();
  9359. });
  9360. }
  9361. else {
  9362. // TODO: Browser does not support WebVR
  9363. this._vrDisplay = undefined;
  9364. this._vrSupported = false;
  9365. callback();
  9366. }
  9367. };
  9368. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9369. if (this._currentRenderTarget) {
  9370. this.unBindFramebuffer(this._currentRenderTarget);
  9371. }
  9372. this._currentRenderTarget = texture;
  9373. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9374. var gl = this._gl;
  9375. if (texture.isCube) {
  9376. if (faceIndex === undefined) {
  9377. faceIndex = 0;
  9378. }
  9379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9380. }
  9381. if (this._cachedViewport && !forceFullscreenViewport) {
  9382. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9383. }
  9384. else {
  9385. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9386. }
  9387. this.wipeCaches();
  9388. };
  9389. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9390. if (this._currentFramebuffer !== framebuffer) {
  9391. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9392. this._currentFramebuffer = framebuffer;
  9393. }
  9394. };
  9395. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9396. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9397. this._currentRenderTarget = null;
  9398. // If MSAA, we need to bitblt back to main texture
  9399. var gl = this._gl;
  9400. if (texture._MSAAFramebuffer) {
  9401. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9402. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9403. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9404. }
  9405. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9406. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9407. gl.generateMipmap(gl.TEXTURE_2D);
  9408. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9409. }
  9410. if (onBeforeUnbind) {
  9411. if (texture._MSAAFramebuffer) {
  9412. // Bind the correct framebuffer
  9413. this.bindUnboundFramebuffer(texture._framebuffer);
  9414. }
  9415. onBeforeUnbind();
  9416. }
  9417. this.bindUnboundFramebuffer(null);
  9418. };
  9419. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9420. if (texture.generateMipMaps) {
  9421. var gl = this._gl;
  9422. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9423. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9424. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9425. }
  9426. };
  9427. Engine.prototype.flushFramebuffer = function () {
  9428. this._gl.flush();
  9429. };
  9430. Engine.prototype.restoreDefaultFramebuffer = function () {
  9431. if (this._currentRenderTarget) {
  9432. this.unBindFramebuffer(this._currentRenderTarget);
  9433. }
  9434. else {
  9435. this.bindUnboundFramebuffer(null);
  9436. }
  9437. if (this._cachedViewport) {
  9438. this.setViewport(this._cachedViewport);
  9439. }
  9440. this.wipeCaches();
  9441. };
  9442. // UBOs
  9443. Engine.prototype.createUniformBuffer = function (elements) {
  9444. var ubo = this._gl.createBuffer();
  9445. if (!ubo) {
  9446. throw new Error("Unable to create uniform buffer");
  9447. }
  9448. this.bindUniformBuffer(ubo);
  9449. if (elements instanceof Float32Array) {
  9450. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9451. }
  9452. else {
  9453. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9454. }
  9455. this.bindUniformBuffer(null);
  9456. ubo.references = 1;
  9457. return ubo;
  9458. };
  9459. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9460. var ubo = this._gl.createBuffer();
  9461. if (!ubo) {
  9462. throw new Error("Unable to create dynamic uniform buffer");
  9463. }
  9464. this.bindUniformBuffer(ubo);
  9465. if (elements instanceof Float32Array) {
  9466. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9467. }
  9468. else {
  9469. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9470. }
  9471. this.bindUniformBuffer(null);
  9472. ubo.references = 1;
  9473. return ubo;
  9474. };
  9475. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9476. this.bindUniformBuffer(uniformBuffer);
  9477. if (offset === undefined) {
  9478. offset = 0;
  9479. }
  9480. if (count === undefined) {
  9481. if (elements instanceof Float32Array) {
  9482. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9483. }
  9484. else {
  9485. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9486. }
  9487. }
  9488. else {
  9489. if (elements instanceof Float32Array) {
  9490. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9491. }
  9492. else {
  9493. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9494. }
  9495. }
  9496. this.bindUniformBuffer(null);
  9497. };
  9498. // VBOs
  9499. Engine.prototype._resetVertexBufferBinding = function () {
  9500. this.bindArrayBuffer(null);
  9501. this._cachedVertexBuffers = null;
  9502. };
  9503. Engine.prototype.createVertexBuffer = function (vertices) {
  9504. var vbo = this._gl.createBuffer();
  9505. if (!vbo) {
  9506. throw new Error("Unable to create vertex buffer");
  9507. }
  9508. this.bindArrayBuffer(vbo);
  9509. if (vertices instanceof Float32Array) {
  9510. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9511. }
  9512. else {
  9513. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9514. }
  9515. this._resetVertexBufferBinding();
  9516. vbo.references = 1;
  9517. return vbo;
  9518. };
  9519. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9520. var vbo = this._gl.createBuffer();
  9521. if (!vbo) {
  9522. throw new Error("Unable to create dynamic vertex buffer");
  9523. }
  9524. this.bindArrayBuffer(vbo);
  9525. if (vertices instanceof Float32Array) {
  9526. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9527. }
  9528. else {
  9529. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9530. }
  9531. this._resetVertexBufferBinding();
  9532. vbo.references = 1;
  9533. return vbo;
  9534. };
  9535. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9536. if (offset === void 0) { offset = 0; }
  9537. // Force cache update
  9538. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9539. this.bindIndexBuffer(indexBuffer);
  9540. var arrayBuffer;
  9541. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9542. arrayBuffer = indices;
  9543. }
  9544. else {
  9545. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9546. }
  9547. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9548. this._resetIndexBufferBinding();
  9549. };
  9550. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9551. this.bindArrayBuffer(vertexBuffer);
  9552. if (offset === undefined) {
  9553. offset = 0;
  9554. }
  9555. if (count === undefined) {
  9556. if (vertices instanceof Float32Array) {
  9557. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9558. }
  9559. else {
  9560. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9561. }
  9562. }
  9563. else {
  9564. if (vertices instanceof Float32Array) {
  9565. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9566. }
  9567. else {
  9568. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9569. }
  9570. }
  9571. this._resetVertexBufferBinding();
  9572. };
  9573. Engine.prototype._resetIndexBufferBinding = function () {
  9574. this.bindIndexBuffer(null);
  9575. this._cachedIndexBuffer = null;
  9576. };
  9577. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9578. var vbo = this._gl.createBuffer();
  9579. if (!vbo) {
  9580. throw new Error("Unable to create index buffer");
  9581. }
  9582. this.bindIndexBuffer(vbo);
  9583. // Check for 32 bits indices
  9584. var arrayBuffer;
  9585. var need32Bits = false;
  9586. if (indices instanceof Uint16Array) {
  9587. arrayBuffer = indices;
  9588. }
  9589. else {
  9590. //check 32 bit support
  9591. if (this._caps.uintIndices) {
  9592. if (indices instanceof Uint32Array) {
  9593. arrayBuffer = indices;
  9594. need32Bits = true;
  9595. }
  9596. else {
  9597. //number[] or Int32Array, check if 32 bit is necessary
  9598. for (var index = 0; index < indices.length; index++) {
  9599. if (indices[index] > 65535) {
  9600. need32Bits = true;
  9601. break;
  9602. }
  9603. }
  9604. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9605. }
  9606. }
  9607. else {
  9608. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9609. arrayBuffer = new Uint16Array(indices);
  9610. }
  9611. }
  9612. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9613. this._resetIndexBufferBinding();
  9614. vbo.references = 1;
  9615. vbo.is32Bits = need32Bits;
  9616. return vbo;
  9617. };
  9618. Engine.prototype.bindArrayBuffer = function (buffer) {
  9619. if (!this._vaoRecordInProgress) {
  9620. this._unbindVertexArrayObject();
  9621. }
  9622. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9623. };
  9624. Engine.prototype.bindUniformBuffer = function (buffer) {
  9625. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9626. };
  9627. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9628. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9629. };
  9630. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9631. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9632. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9633. };
  9634. ;
  9635. Engine.prototype.bindIndexBuffer = function (buffer) {
  9636. if (!this._vaoRecordInProgress) {
  9637. this._unbindVertexArrayObject();
  9638. }
  9639. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9640. };
  9641. Engine.prototype.bindBuffer = function (buffer, target) {
  9642. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9643. this._gl.bindBuffer(target, buffer);
  9644. this._currentBoundBuffer[target] = buffer;
  9645. }
  9646. };
  9647. Engine.prototype.updateArrayBuffer = function (data) {
  9648. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9649. };
  9650. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9651. var pointer = this._currentBufferPointers[indx];
  9652. var changed = false;
  9653. if (!pointer.active) {
  9654. changed = true;
  9655. pointer.active = true;
  9656. pointer.index = indx;
  9657. pointer.size = size;
  9658. pointer.type = type;
  9659. pointer.normalized = normalized;
  9660. pointer.stride = stride;
  9661. pointer.offset = offset;
  9662. pointer.buffer = buffer;
  9663. }
  9664. else {
  9665. if (pointer.buffer !== buffer) {
  9666. pointer.buffer = buffer;
  9667. changed = true;
  9668. }
  9669. if (pointer.size !== size) {
  9670. pointer.size = size;
  9671. changed = true;
  9672. }
  9673. if (pointer.type !== type) {
  9674. pointer.type = type;
  9675. changed = true;
  9676. }
  9677. if (pointer.normalized !== normalized) {
  9678. pointer.normalized = normalized;
  9679. changed = true;
  9680. }
  9681. if (pointer.stride !== stride) {
  9682. pointer.stride = stride;
  9683. changed = true;
  9684. }
  9685. if (pointer.offset !== offset) {
  9686. pointer.offset = offset;
  9687. changed = true;
  9688. }
  9689. }
  9690. if (changed || this._vaoRecordInProgress) {
  9691. this.bindArrayBuffer(buffer);
  9692. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9693. }
  9694. };
  9695. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9696. if (indexBuffer == null) {
  9697. return;
  9698. }
  9699. if (this._cachedIndexBuffer !== indexBuffer) {
  9700. this._cachedIndexBuffer = indexBuffer;
  9701. this.bindIndexBuffer(indexBuffer);
  9702. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9703. }
  9704. };
  9705. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9706. var attributes = effect.getAttributesNames();
  9707. if (!this._vaoRecordInProgress) {
  9708. this._unbindVertexArrayObject();
  9709. }
  9710. this.unbindAllAttributes();
  9711. for (var index = 0; index < attributes.length; index++) {
  9712. var order = effect.getAttributeLocation(index);
  9713. if (order >= 0) {
  9714. var vertexBuffer = vertexBuffers[attributes[index]];
  9715. if (!vertexBuffer) {
  9716. continue;
  9717. }
  9718. this._gl.enableVertexAttribArray(order);
  9719. if (!this._vaoRecordInProgress) {
  9720. this._vertexAttribArraysEnabled[order] = true;
  9721. }
  9722. var buffer = vertexBuffer.getBuffer();
  9723. if (buffer) {
  9724. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9725. if (vertexBuffer.getIsInstanced()) {
  9726. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9727. if (!this._vaoRecordInProgress) {
  9728. this._currentInstanceLocations.push(order);
  9729. this._currentInstanceBuffers.push(buffer);
  9730. }
  9731. }
  9732. }
  9733. }
  9734. }
  9735. };
  9736. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9737. var vao = this._gl.createVertexArray();
  9738. this._vaoRecordInProgress = true;
  9739. this._gl.bindVertexArray(vao);
  9740. this._mustWipeVertexAttributes = true;
  9741. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9742. this.bindIndexBuffer(indexBuffer);
  9743. this._vaoRecordInProgress = false;
  9744. this._gl.bindVertexArray(null);
  9745. return vao;
  9746. };
  9747. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9748. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9749. this._cachedVertexArrayObject = vertexArrayObject;
  9750. this._gl.bindVertexArray(vertexArrayObject);
  9751. this._cachedVertexBuffers = null;
  9752. this._cachedIndexBuffer = null;
  9753. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9754. this._mustWipeVertexAttributes = true;
  9755. }
  9756. };
  9757. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9758. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9759. this._cachedVertexBuffers = vertexBuffer;
  9760. this._cachedEffectForVertexBuffers = effect;
  9761. var attributesCount = effect.getAttributesCount();
  9762. this._unbindVertexArrayObject();
  9763. this.unbindAllAttributes();
  9764. var offset = 0;
  9765. for (var index = 0; index < attributesCount; index++) {
  9766. if (index < vertexDeclaration.length) {
  9767. var order = effect.getAttributeLocation(index);
  9768. if (order >= 0) {
  9769. this._gl.enableVertexAttribArray(order);
  9770. this._vertexAttribArraysEnabled[order] = true;
  9771. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9772. }
  9773. offset += vertexDeclaration[index] * 4;
  9774. }
  9775. }
  9776. }
  9777. this._bindIndexBufferWithCache(indexBuffer);
  9778. };
  9779. Engine.prototype._unbindVertexArrayObject = function () {
  9780. if (!this._cachedVertexArrayObject) {
  9781. return;
  9782. }
  9783. this._cachedVertexArrayObject = null;
  9784. this._gl.bindVertexArray(null);
  9785. };
  9786. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9787. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9788. this._cachedVertexBuffers = vertexBuffers;
  9789. this._cachedEffectForVertexBuffers = effect;
  9790. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9791. }
  9792. this._bindIndexBufferWithCache(indexBuffer);
  9793. };
  9794. Engine.prototype.unbindInstanceAttributes = function () {
  9795. var boundBuffer;
  9796. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9797. var instancesBuffer = this._currentInstanceBuffers[i];
  9798. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9799. boundBuffer = instancesBuffer;
  9800. this.bindArrayBuffer(instancesBuffer);
  9801. }
  9802. var offsetLocation = this._currentInstanceLocations[i];
  9803. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9804. }
  9805. this._currentInstanceBuffers.length = 0;
  9806. this._currentInstanceLocations.length = 0;
  9807. };
  9808. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9809. this._gl.deleteVertexArray(vao);
  9810. };
  9811. Engine.prototype._releaseBuffer = function (buffer) {
  9812. buffer.references--;
  9813. if (buffer.references === 0) {
  9814. this._gl.deleteBuffer(buffer);
  9815. return true;
  9816. }
  9817. return false;
  9818. };
  9819. Engine.prototype.createInstancesBuffer = function (capacity) {
  9820. var buffer = this._gl.createBuffer();
  9821. if (!buffer) {
  9822. throw new Error("Unable to create instance buffer");
  9823. }
  9824. buffer.capacity = capacity;
  9825. this.bindArrayBuffer(buffer);
  9826. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9827. return buffer;
  9828. };
  9829. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9830. this._gl.deleteBuffer(buffer);
  9831. };
  9832. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9833. this.bindArrayBuffer(instancesBuffer);
  9834. if (data) {
  9835. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9836. }
  9837. if (offsetLocations[0].index !== undefined) {
  9838. var stride = 0;
  9839. for (var i = 0; i < offsetLocations.length; i++) {
  9840. var ai = offsetLocations[i];
  9841. stride += ai.attributeSize * 4;
  9842. }
  9843. for (var i = 0; i < offsetLocations.length; i++) {
  9844. var ai = offsetLocations[i];
  9845. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9846. this._gl.enableVertexAttribArray(ai.index);
  9847. this._vertexAttribArraysEnabled[ai.index] = true;
  9848. }
  9849. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9850. this._gl.vertexAttribDivisor(ai.index, 1);
  9851. this._currentInstanceLocations.push(ai.index);
  9852. this._currentInstanceBuffers.push(instancesBuffer);
  9853. }
  9854. }
  9855. else {
  9856. for (var index = 0; index < 4; index++) {
  9857. var offsetLocation = offsetLocations[index];
  9858. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9859. this._gl.enableVertexAttribArray(offsetLocation);
  9860. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9861. }
  9862. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9863. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9864. this._currentInstanceLocations.push(offsetLocation);
  9865. this._currentInstanceBuffers.push(instancesBuffer);
  9866. }
  9867. }
  9868. };
  9869. Engine.prototype.applyStates = function () {
  9870. this._depthCullingState.apply(this._gl);
  9871. this._stencilState.apply(this._gl);
  9872. this._alphaState.apply(this._gl);
  9873. };
  9874. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9875. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  9876. };
  9877. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9878. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  9879. };
  9880. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9881. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  9882. };
  9883. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  9884. // Apply states
  9885. this.applyStates();
  9886. this._drawCalls.addCount(1, false);
  9887. // Render
  9888. var drawMode = this.DrawMode(fillMode);
  9889. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9890. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9891. if (instancesCount) {
  9892. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  9893. }
  9894. else {
  9895. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  9896. }
  9897. };
  9898. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  9899. // Apply states
  9900. this.applyStates();
  9901. this._drawCalls.addCount(1, false);
  9902. var drawMode = this.DrawMode(fillMode);
  9903. if (instancesCount) {
  9904. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  9905. }
  9906. else {
  9907. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  9908. }
  9909. };
  9910. Engine.prototype.DrawMode = function (fillMode) {
  9911. switch (fillMode) {
  9912. // Triangle views
  9913. case BABYLON.Material.TriangleFillMode:
  9914. return this._gl.TRIANGLES;
  9915. case BABYLON.Material.PointFillMode:
  9916. return this._gl.POINTS;
  9917. case BABYLON.Material.WireFrameFillMode:
  9918. return this._gl.LINES;
  9919. // Draw modes
  9920. case BABYLON.Material.PointListDrawMode:
  9921. return this._gl.POINTS;
  9922. case BABYLON.Material.LineListDrawMode:
  9923. return this._gl.LINES;
  9924. case BABYLON.Material.LineLoopDrawMode:
  9925. return this._gl.LINE_LOOP;
  9926. case BABYLON.Material.LineStripDrawMode:
  9927. return this._gl.LINE_STRIP;
  9928. case BABYLON.Material.TriangleStripDrawMode:
  9929. return this._gl.TRIANGLE_STRIP;
  9930. case BABYLON.Material.TriangleFanDrawMode:
  9931. return this._gl.TRIANGLE_FAN;
  9932. default:
  9933. return this._gl.TRIANGLES;
  9934. }
  9935. };
  9936. // Shaders
  9937. Engine.prototype._releaseEffect = function (effect) {
  9938. if (this._compiledEffects[effect._key]) {
  9939. delete this._compiledEffects[effect._key];
  9940. this._deleteProgram(effect.getProgram());
  9941. }
  9942. };
  9943. Engine.prototype._deleteProgram = function (program) {
  9944. if (program) {
  9945. program.__SPECTOR_rebuildProgram = null;
  9946. if (program.transformFeedback) {
  9947. this.deleteTransformFeedback(program.transformFeedback);
  9948. program.transformFeedback = null;
  9949. }
  9950. this._gl.deleteProgram(program);
  9951. }
  9952. };
  9953. /**
  9954. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9955. * @param samplers An array of string used to represent textures
  9956. */
  9957. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9958. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9959. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9960. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9961. if (this._compiledEffects[name]) {
  9962. var compiledEffect = this._compiledEffects[name];
  9963. if (onCompiled && compiledEffect.isReady()) {
  9964. onCompiled(compiledEffect);
  9965. }
  9966. return compiledEffect;
  9967. }
  9968. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9969. effect._key = name;
  9970. this._compiledEffects[name] = effect;
  9971. return effect;
  9972. };
  9973. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9974. if (uniformsNames === void 0) { uniformsNames = []; }
  9975. if (samplers === void 0) { samplers = []; }
  9976. if (defines === void 0) { defines = ""; }
  9977. return this.createEffect({
  9978. vertex: "particles",
  9979. fragmentElement: fragmentName
  9980. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9981. };
  9982. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9983. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9984. context = context || this._gl;
  9985. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9986. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9987. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9988. };
  9989. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9990. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9991. context = context || this._gl;
  9992. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9993. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9994. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9995. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9996. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9997. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9998. return program;
  9999. };
  10000. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10001. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10002. var shaderProgram = context.createProgram();
  10003. if (!shaderProgram) {
  10004. throw new Error("Unable to create program");
  10005. }
  10006. context.attachShader(shaderProgram, vertexShader);
  10007. context.attachShader(shaderProgram, fragmentShader);
  10008. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10009. var transformFeedback = this.createTransformFeedback();
  10010. this.bindTransformFeedback(transformFeedback);
  10011. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10012. shaderProgram.transformFeedback = transformFeedback;
  10013. }
  10014. context.linkProgram(shaderProgram);
  10015. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10016. this.bindTransformFeedback(null);
  10017. }
  10018. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10019. if (!linked) {
  10020. context.validateProgram(shaderProgram);
  10021. var error = context.getProgramInfoLog(shaderProgram);
  10022. if (error) {
  10023. throw new Error(error);
  10024. }
  10025. }
  10026. context.deleteShader(vertexShader);
  10027. context.deleteShader(fragmentShader);
  10028. return shaderProgram;
  10029. };
  10030. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10031. var results = new Array();
  10032. for (var index = 0; index < uniformsNames.length; index++) {
  10033. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10034. }
  10035. return results;
  10036. };
  10037. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10038. var results = [];
  10039. for (var index = 0; index < attributesNames.length; index++) {
  10040. try {
  10041. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10042. }
  10043. catch (e) {
  10044. results.push(-1);
  10045. }
  10046. }
  10047. return results;
  10048. };
  10049. Engine.prototype.enableEffect = function (effect) {
  10050. if (!effect) {
  10051. return;
  10052. }
  10053. // Use program
  10054. this.bindSamplers(effect);
  10055. this._currentEffect = effect;
  10056. if (effect.onBind) {
  10057. effect.onBind(effect);
  10058. }
  10059. effect.onBindObservable.notifyObservers(effect);
  10060. };
  10061. Engine.prototype.setIntArray = function (uniform, array) {
  10062. if (!uniform)
  10063. return;
  10064. this._gl.uniform1iv(uniform, array);
  10065. };
  10066. Engine.prototype.setIntArray2 = function (uniform, array) {
  10067. if (!uniform || array.length % 2 !== 0)
  10068. return;
  10069. this._gl.uniform2iv(uniform, array);
  10070. };
  10071. Engine.prototype.setIntArray3 = function (uniform, array) {
  10072. if (!uniform || array.length % 3 !== 0)
  10073. return;
  10074. this._gl.uniform3iv(uniform, array);
  10075. };
  10076. Engine.prototype.setIntArray4 = function (uniform, array) {
  10077. if (!uniform || array.length % 4 !== 0)
  10078. return;
  10079. this._gl.uniform4iv(uniform, array);
  10080. };
  10081. Engine.prototype.setFloatArray = function (uniform, array) {
  10082. if (!uniform)
  10083. return;
  10084. this._gl.uniform1fv(uniform, array);
  10085. };
  10086. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10087. if (!uniform || array.length % 2 !== 0)
  10088. return;
  10089. this._gl.uniform2fv(uniform, array);
  10090. };
  10091. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10092. if (!uniform || array.length % 3 !== 0)
  10093. return;
  10094. this._gl.uniform3fv(uniform, array);
  10095. };
  10096. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10097. if (!uniform || array.length % 4 !== 0)
  10098. return;
  10099. this._gl.uniform4fv(uniform, array);
  10100. };
  10101. Engine.prototype.setArray = function (uniform, array) {
  10102. if (!uniform)
  10103. return;
  10104. this._gl.uniform1fv(uniform, array);
  10105. };
  10106. Engine.prototype.setArray2 = function (uniform, array) {
  10107. if (!uniform || array.length % 2 !== 0)
  10108. return;
  10109. this._gl.uniform2fv(uniform, array);
  10110. };
  10111. Engine.prototype.setArray3 = function (uniform, array) {
  10112. if (!uniform || array.length % 3 !== 0)
  10113. return;
  10114. this._gl.uniform3fv(uniform, array);
  10115. };
  10116. Engine.prototype.setArray4 = function (uniform, array) {
  10117. if (!uniform || array.length % 4 !== 0)
  10118. return;
  10119. this._gl.uniform4fv(uniform, array);
  10120. };
  10121. Engine.prototype.setMatrices = function (uniform, matrices) {
  10122. if (!uniform)
  10123. return;
  10124. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10125. };
  10126. Engine.prototype.setMatrix = function (uniform, matrix) {
  10127. if (!uniform)
  10128. return;
  10129. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10130. };
  10131. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10132. if (!uniform)
  10133. return;
  10134. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10135. };
  10136. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10137. if (!uniform)
  10138. return;
  10139. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10140. };
  10141. Engine.prototype.setFloat = function (uniform, value) {
  10142. if (!uniform)
  10143. return;
  10144. this._gl.uniform1f(uniform, value);
  10145. };
  10146. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10147. if (!uniform)
  10148. return;
  10149. this._gl.uniform2f(uniform, x, y);
  10150. };
  10151. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10152. if (!uniform)
  10153. return;
  10154. this._gl.uniform3f(uniform, x, y, z);
  10155. };
  10156. Engine.prototype.setBool = function (uniform, bool) {
  10157. if (!uniform)
  10158. return;
  10159. this._gl.uniform1i(uniform, bool);
  10160. };
  10161. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10162. if (!uniform)
  10163. return;
  10164. this._gl.uniform4f(uniform, x, y, z, w);
  10165. };
  10166. Engine.prototype.setColor3 = function (uniform, color3) {
  10167. if (!uniform)
  10168. return;
  10169. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10170. };
  10171. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10172. if (!uniform)
  10173. return;
  10174. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10175. };
  10176. // States
  10177. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10178. if (zOffset === void 0) { zOffset = 0; }
  10179. if (reverseSide === void 0) { reverseSide = false; }
  10180. // Culling
  10181. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10182. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10183. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10184. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10185. if (culling) {
  10186. this._depthCullingState.cullFace = cullFace;
  10187. this._depthCullingState.cull = true;
  10188. }
  10189. else {
  10190. this._depthCullingState.cull = false;
  10191. }
  10192. }
  10193. // Z offset
  10194. this.setZOffset(zOffset);
  10195. };
  10196. Engine.prototype.setZOffset = function (value) {
  10197. this._depthCullingState.zOffset = value;
  10198. };
  10199. Engine.prototype.getZOffset = function () {
  10200. return this._depthCullingState.zOffset;
  10201. };
  10202. Engine.prototype.setDepthBuffer = function (enable) {
  10203. this._depthCullingState.depthTest = enable;
  10204. };
  10205. Engine.prototype.getDepthWrite = function () {
  10206. return this._depthCullingState.depthMask;
  10207. };
  10208. Engine.prototype.setDepthWrite = function (enable) {
  10209. this._depthCullingState.depthMask = enable;
  10210. };
  10211. Engine.prototype.setColorWrite = function (enable) {
  10212. this._gl.colorMask(enable, enable, enable, enable);
  10213. this._colorWrite = enable;
  10214. };
  10215. Engine.prototype.getColorWrite = function () {
  10216. return this._colorWrite;
  10217. };
  10218. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10219. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10220. };
  10221. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10222. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10223. if (this._alphaMode === mode) {
  10224. return;
  10225. }
  10226. switch (mode) {
  10227. case Engine.ALPHA_DISABLE:
  10228. this._alphaState.alphaBlend = false;
  10229. break;
  10230. case Engine.ALPHA_PREMULTIPLIED:
  10231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10232. this._alphaState.alphaBlend = true;
  10233. break;
  10234. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10235. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10236. this._alphaState.alphaBlend = true;
  10237. break;
  10238. case Engine.ALPHA_COMBINE:
  10239. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10240. this._alphaState.alphaBlend = true;
  10241. break;
  10242. case Engine.ALPHA_ONEONE:
  10243. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10244. this._alphaState.alphaBlend = true;
  10245. break;
  10246. case Engine.ALPHA_ADD:
  10247. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10248. this._alphaState.alphaBlend = true;
  10249. break;
  10250. case Engine.ALPHA_SUBTRACT:
  10251. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10252. this._alphaState.alphaBlend = true;
  10253. break;
  10254. case Engine.ALPHA_MULTIPLY:
  10255. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10256. this._alphaState.alphaBlend = true;
  10257. break;
  10258. case Engine.ALPHA_MAXIMIZED:
  10259. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10260. this._alphaState.alphaBlend = true;
  10261. break;
  10262. case Engine.ALPHA_INTERPOLATE:
  10263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10264. this._alphaState.alphaBlend = true;
  10265. break;
  10266. case Engine.ALPHA_SCREENMODE:
  10267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10268. this._alphaState.alphaBlend = true;
  10269. break;
  10270. }
  10271. if (!noDepthWriteChange) {
  10272. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10273. }
  10274. this._alphaMode = mode;
  10275. };
  10276. Engine.prototype.getAlphaMode = function () {
  10277. return this._alphaMode;
  10278. };
  10279. Engine.prototype.setAlphaTesting = function (enable) {
  10280. this._alphaTest = enable;
  10281. };
  10282. Engine.prototype.getAlphaTesting = function () {
  10283. return !!this._alphaTest;
  10284. };
  10285. // Textures
  10286. Engine.prototype.wipeCaches = function (bruteForce) {
  10287. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10288. return;
  10289. }
  10290. this.resetTextureCache();
  10291. this._currentEffect = null;
  10292. // 6/8/2017: deltakosh: Should not be required anymore.
  10293. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10294. if (bruteForce) {
  10295. this._currentProgram = null;
  10296. this._stencilState.reset();
  10297. this._depthCullingState.reset();
  10298. this.setDepthFunctionToLessOrEqual();
  10299. this._alphaState.reset();
  10300. }
  10301. this._cachedVertexBuffers = null;
  10302. this._cachedIndexBuffer = null;
  10303. this._cachedEffectForVertexBuffers = null;
  10304. this._unbindVertexArrayObject();
  10305. this.bindIndexBuffer(null);
  10306. this.bindArrayBuffer(null);
  10307. };
  10308. /**
  10309. * Set the compressed texture format to use, based on the formats you have, and the formats
  10310. * supported by the hardware / browser.
  10311. *
  10312. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10313. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10314. * to API arguments needed to compressed textures. This puts the burden on the container
  10315. * generator to house the arcane code for determining these for current & future formats.
  10316. *
  10317. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10318. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10319. *
  10320. * Note: The result of this call is not taken into account when a texture is base64.
  10321. *
  10322. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10323. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10324. *
  10325. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10326. * @returns The extension selected.
  10327. */
  10328. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10329. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10330. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10331. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10332. return this._textureFormatInUse = this._texturesSupported[i];
  10333. }
  10334. }
  10335. }
  10336. // actively set format to nothing, to allow this to be called more than once
  10337. // and possibly fail the 2nd time
  10338. this._textureFormatInUse = null;
  10339. return null;
  10340. };
  10341. Engine.prototype._createTexture = function () {
  10342. var texture = this._gl.createTexture();
  10343. if (!texture) {
  10344. throw new Error("Unable to create texture");
  10345. }
  10346. return texture;
  10347. };
  10348. /**
  10349. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10350. * @param {string} urlArg- This contains one of the following:
  10351. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10352. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10353. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10354. *
  10355. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10356. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10357. * @param {Scene} scene- Needed for loading to the correct scene.
  10358. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10359. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10360. * @param {callback} onError- Optional callback to be called upon failure.
  10361. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10362. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10363. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10364. *
  10365. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10366. */
  10367. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10368. var _this = this;
  10369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10370. if (onLoad === void 0) { onLoad = null; }
  10371. if (onError === void 0) { onError = null; }
  10372. if (buffer === void 0) { buffer = null; }
  10373. if (fallBack === void 0) { fallBack = null; }
  10374. if (format === void 0) { format = null; }
  10375. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10376. var fromData = url.substr(0, 5) === "data:";
  10377. var fromBlob = url.substr(0, 5) === "blob:";
  10378. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10379. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10380. // establish the file extension, if possible
  10381. var lastDot = url.lastIndexOf('.');
  10382. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10383. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10384. var isTGA = (extension === ".tga");
  10385. // determine if a ktx file should be substituted
  10386. var isKTX = false;
  10387. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10388. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10389. isKTX = true;
  10390. }
  10391. if (scene) {
  10392. scene._addPendingData(texture);
  10393. }
  10394. texture.url = url;
  10395. texture.generateMipMaps = !noMipmap;
  10396. texture.samplingMode = samplingMode;
  10397. texture.invertY = invertY;
  10398. if (!this._doNotHandleContextLost) {
  10399. // Keep a link to the buffer only if we plan to handle context lost
  10400. texture._buffer = buffer;
  10401. }
  10402. var onLoadObserver = null;
  10403. if (onLoad && !fallBack) {
  10404. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10405. }
  10406. if (!fallBack)
  10407. this._internalTexturesCache.push(texture);
  10408. var onerror = function (message, exception) {
  10409. if (scene) {
  10410. scene._removePendingData(texture);
  10411. }
  10412. if (onLoadObserver) {
  10413. texture.onLoadedObservable.remove(onLoadObserver);
  10414. }
  10415. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10416. if (isKTX) {
  10417. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10418. }
  10419. else if (BABYLON.Tools.UseFallbackTexture) {
  10420. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10421. }
  10422. if (onError) {
  10423. onError(message || "Unknown error", exception);
  10424. }
  10425. };
  10426. var callback = null;
  10427. // processing for non-image formats
  10428. if (isKTX || isTGA || isDDS) {
  10429. if (isKTX) {
  10430. callback = function (data) {
  10431. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10432. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10433. ktx.uploadLevels(_this._gl, !noMipmap);
  10434. return false;
  10435. }, samplingMode);
  10436. };
  10437. }
  10438. else if (isTGA) {
  10439. callback = function (arrayBuffer) {
  10440. var data = new Uint8Array(arrayBuffer);
  10441. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10442. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10443. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10444. return false;
  10445. }, samplingMode);
  10446. };
  10447. }
  10448. else if (isDDS) {
  10449. callback = function (data) {
  10450. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10451. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10452. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10453. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10454. return false;
  10455. }, samplingMode);
  10456. };
  10457. }
  10458. if (!buffer) {
  10459. BABYLON.Tools.LoadFile(url, function (data) {
  10460. if (callback) {
  10461. callback(data);
  10462. }
  10463. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10464. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10465. });
  10466. }
  10467. else {
  10468. if (callback) {
  10469. callback(buffer);
  10470. }
  10471. }
  10472. // image format processing
  10473. }
  10474. else {
  10475. var onload = function (img) {
  10476. if (fromBlob && !_this._doNotHandleContextLost) {
  10477. // We need to store the image if we need to rebuild the texture
  10478. // in case of a webgl context lost
  10479. texture._buffer = img;
  10480. }
  10481. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10482. var gl = _this._gl;
  10483. var isPot = (img.width === potWidth && img.height === potHeight);
  10484. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10485. if (isPot) {
  10486. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10487. return false;
  10488. }
  10489. // Using shaders to rescale because canvas.drawImage is lossy
  10490. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10491. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10492. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10496. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10497. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10498. _this._releaseTexture(source);
  10499. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10500. continuationCallback();
  10501. });
  10502. return true;
  10503. }, samplingMode);
  10504. };
  10505. if (!fromData || isBase64)
  10506. if (buffer instanceof HTMLImageElement) {
  10507. onload(buffer);
  10508. }
  10509. else {
  10510. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10511. }
  10512. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10513. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10514. else
  10515. onload(buffer);
  10516. }
  10517. return texture;
  10518. };
  10519. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10520. var _this = this;
  10521. var rtt = this.createRenderTargetTexture({
  10522. width: destination.width,
  10523. height: destination.height,
  10524. }, {
  10525. generateMipMaps: false,
  10526. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10527. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10528. generateDepthBuffer: false,
  10529. generateStencilBuffer: false
  10530. });
  10531. if (!this._rescalePostProcess) {
  10532. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10533. }
  10534. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10535. _this._rescalePostProcess.onApply = function (effect) {
  10536. effect._bindTexture("textureSampler", source);
  10537. };
  10538. var hostingScene = scene;
  10539. if (!hostingScene) {
  10540. hostingScene = _this.scenes[_this.scenes.length - 1];
  10541. }
  10542. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10543. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10544. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10545. _this.unBindFramebuffer(rtt);
  10546. _this._releaseTexture(rtt);
  10547. if (onComplete) {
  10548. onComplete();
  10549. }
  10550. });
  10551. };
  10552. Engine.prototype._getInternalFormat = function (format) {
  10553. var internalFormat = this._gl.RGBA;
  10554. switch (format) {
  10555. case Engine.TEXTUREFORMAT_ALPHA:
  10556. internalFormat = this._gl.ALPHA;
  10557. break;
  10558. case Engine.TEXTUREFORMAT_LUMINANCE:
  10559. internalFormat = this._gl.LUMINANCE;
  10560. break;
  10561. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10562. internalFormat = this._gl.LUMINANCE_ALPHA;
  10563. break;
  10564. case Engine.TEXTUREFORMAT_RGB:
  10565. internalFormat = this._gl.RGB;
  10566. break;
  10567. case Engine.TEXTUREFORMAT_RGBA:
  10568. internalFormat = this._gl.RGBA;
  10569. break;
  10570. }
  10571. return internalFormat;
  10572. };
  10573. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10574. if (compression === void 0) { compression = null; }
  10575. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10576. if (!texture) {
  10577. return;
  10578. }
  10579. var internalFormat = this._getInternalFormat(format);
  10580. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10581. var textureType = this._getWebGLTextureType(type);
  10582. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10583. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10584. if (!this._doNotHandleContextLost) {
  10585. texture._bufferView = data;
  10586. texture.format = format;
  10587. texture.type = type;
  10588. texture.invertY = invertY;
  10589. texture._compression = compression;
  10590. }
  10591. if (texture.width % 4 !== 0) {
  10592. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10593. }
  10594. if (compression && data) {
  10595. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10596. }
  10597. else {
  10598. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10599. }
  10600. if (texture.generateMipMaps) {
  10601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10602. }
  10603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10604. this.resetTextureCache();
  10605. texture.isReady = true;
  10606. };
  10607. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10608. if (compression === void 0) { compression = null; }
  10609. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10611. texture.baseWidth = width;
  10612. texture.baseHeight = height;
  10613. texture.width = width;
  10614. texture.height = height;
  10615. texture.format = format;
  10616. texture.generateMipMaps = generateMipMaps;
  10617. texture.samplingMode = samplingMode;
  10618. texture.invertY = invertY;
  10619. texture._compression = compression;
  10620. texture.type = type;
  10621. if (!this._doNotHandleContextLost) {
  10622. texture._bufferView = data;
  10623. }
  10624. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10625. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10626. // Filters
  10627. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10630. if (generateMipMaps) {
  10631. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10632. }
  10633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10634. this._internalTexturesCache.push(texture);
  10635. return texture;
  10636. };
  10637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10639. texture.baseWidth = width;
  10640. texture.baseHeight = height;
  10641. if (generateMipMaps) {
  10642. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10643. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10644. }
  10645. this.resetTextureCache();
  10646. texture.width = width;
  10647. texture.height = height;
  10648. texture.isReady = false;
  10649. texture.generateMipMaps = generateMipMaps;
  10650. texture.samplingMode = samplingMode;
  10651. this.updateTextureSamplingMode(samplingMode, texture);
  10652. this._internalTexturesCache.push(texture);
  10653. return texture;
  10654. };
  10655. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10656. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10657. if (texture.isCube) {
  10658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10659. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10662. }
  10663. else if (texture.is3D) {
  10664. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10665. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10666. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10667. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10668. }
  10669. else {
  10670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10674. }
  10675. texture.samplingMode = samplingMode;
  10676. };
  10677. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10678. if (premulAlpha === void 0) { premulAlpha = false; }
  10679. if (!texture) {
  10680. return;
  10681. }
  10682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10683. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10684. if (premulAlpha) {
  10685. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10686. }
  10687. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10689. if (texture.generateMipMaps) {
  10690. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10691. }
  10692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10693. if (premulAlpha) {
  10694. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10695. }
  10696. this.resetTextureCache();
  10697. texture.isReady = true;
  10698. };
  10699. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10700. if (!texture || texture._isDisabled) {
  10701. return;
  10702. }
  10703. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10704. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10705. try {
  10706. // Testing video texture support
  10707. if (this._videoTextureSupported === undefined) {
  10708. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10709. if (this._gl.getError() !== 0) {
  10710. this._videoTextureSupported = false;
  10711. }
  10712. else {
  10713. this._videoTextureSupported = true;
  10714. }
  10715. }
  10716. // Copy video through the current working canvas if video texture is not supported
  10717. if (!this._videoTextureSupported) {
  10718. if (!texture._workingCanvas) {
  10719. texture._workingCanvas = document.createElement("canvas");
  10720. var context = texture._workingCanvas.getContext("2d");
  10721. if (!context) {
  10722. throw new Error("Unable to get 2d context");
  10723. }
  10724. texture._workingContext = context;
  10725. texture._workingCanvas.width = texture.width;
  10726. texture._workingCanvas.height = texture.height;
  10727. }
  10728. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10729. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10730. }
  10731. else {
  10732. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10733. }
  10734. if (texture.generateMipMaps) {
  10735. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10736. }
  10737. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10738. this.resetTextureCache();
  10739. texture.isReady = true;
  10740. }
  10741. catch (ex) {
  10742. // Something unexpected
  10743. // Let's disable the texture
  10744. texture._isDisabled = true;
  10745. }
  10746. };
  10747. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10748. var fullOptions = new RenderTargetCreationOptions();
  10749. if (options !== undefined && typeof options === "object") {
  10750. fullOptions.generateMipMaps = options.generateMipMaps;
  10751. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10752. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10753. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10754. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10755. }
  10756. else {
  10757. fullOptions.generateMipMaps = options;
  10758. fullOptions.generateDepthBuffer = true;
  10759. fullOptions.generateStencilBuffer = false;
  10760. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10761. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10762. }
  10763. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10764. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10765. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10766. }
  10767. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10768. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10769. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10770. }
  10771. var gl = this._gl;
  10772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10773. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10774. var width = size.width || size;
  10775. var height = size.height || size;
  10776. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10777. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10778. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10779. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10780. }
  10781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10785. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10786. // Create the framebuffer
  10787. var framebuffer = gl.createFramebuffer();
  10788. this.bindUnboundFramebuffer(framebuffer);
  10789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10790. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10791. if (fullOptions.generateMipMaps) {
  10792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10793. }
  10794. // Unbind
  10795. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10796. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10797. this.bindUnboundFramebuffer(null);
  10798. texture._framebuffer = framebuffer;
  10799. texture.baseWidth = width;
  10800. texture.baseHeight = height;
  10801. texture.width = width;
  10802. texture.height = height;
  10803. texture.isReady = true;
  10804. texture.samples = 1;
  10805. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10806. texture.samplingMode = fullOptions.samplingMode;
  10807. texture.type = fullOptions.type;
  10808. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10809. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10810. this.resetTextureCache();
  10811. this._internalTexturesCache.push(texture);
  10812. return texture;
  10813. };
  10814. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10815. var generateMipMaps = false;
  10816. var generateDepthBuffer = true;
  10817. var generateStencilBuffer = false;
  10818. var generateDepthTexture = false;
  10819. var textureCount = 1;
  10820. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10821. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10822. var types = [], samplingModes = [];
  10823. if (options !== undefined) {
  10824. generateMipMaps = options.generateMipMaps;
  10825. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10826. generateStencilBuffer = options.generateStencilBuffer;
  10827. generateDepthTexture = options.generateDepthTexture;
  10828. textureCount = options.textureCount || 1;
  10829. if (options.types) {
  10830. types = options.types;
  10831. }
  10832. if (options.samplingModes) {
  10833. samplingModes = options.samplingModes;
  10834. }
  10835. }
  10836. var gl = this._gl;
  10837. // Create the framebuffer
  10838. var framebuffer = gl.createFramebuffer();
  10839. this.bindUnboundFramebuffer(framebuffer);
  10840. var width = size.width || size;
  10841. var height = size.height || size;
  10842. var textures = [];
  10843. var attachments = [];
  10844. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10845. for (var i = 0; i < textureCount; i++) {
  10846. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10847. var type = types[i] || defaultType;
  10848. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10849. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10850. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10851. }
  10852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10853. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10854. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10855. }
  10856. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10857. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10858. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10859. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10860. }
  10861. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10862. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10863. textures.push(texture);
  10864. attachments.push(attachment);
  10865. gl.activeTexture(gl["TEXTURE" + i]);
  10866. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10871. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10872. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10873. if (generateMipMaps) {
  10874. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10875. }
  10876. // Unbind
  10877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10878. texture._framebuffer = framebuffer;
  10879. texture._depthStencilBuffer = depthStencilBuffer;
  10880. texture.baseWidth = width;
  10881. texture.baseHeight = height;
  10882. texture.width = width;
  10883. texture.height = height;
  10884. texture.isReady = true;
  10885. texture.samples = 1;
  10886. texture.generateMipMaps = generateMipMaps;
  10887. texture.samplingMode = samplingMode;
  10888. texture.type = type;
  10889. texture._generateDepthBuffer = generateDepthBuffer;
  10890. texture._generateStencilBuffer = generateStencilBuffer;
  10891. this._internalTexturesCache.push(texture);
  10892. }
  10893. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10894. // Depth texture
  10895. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10896. gl.activeTexture(gl.TEXTURE0);
  10897. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10902. 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);
  10903. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10904. depthTexture._framebuffer = framebuffer;
  10905. depthTexture.baseWidth = width;
  10906. depthTexture.baseHeight = height;
  10907. depthTexture.width = width;
  10908. depthTexture.height = height;
  10909. depthTexture.isReady = true;
  10910. depthTexture.samples = 1;
  10911. depthTexture.generateMipMaps = generateMipMaps;
  10912. depthTexture.samplingMode = gl.NEAREST;
  10913. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10914. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10915. textures.push(depthTexture);
  10916. this._internalTexturesCache.push(depthTexture);
  10917. }
  10918. gl.drawBuffers(attachments);
  10919. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10920. this.bindUnboundFramebuffer(null);
  10921. this.resetTextureCache();
  10922. return textures;
  10923. };
  10924. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10925. if (samples === void 0) { samples = 1; }
  10926. var depthStencilBuffer = null;
  10927. var gl = this._gl;
  10928. // Create the depth/stencil buffer
  10929. if (generateStencilBuffer) {
  10930. depthStencilBuffer = gl.createRenderbuffer();
  10931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10932. if (samples > 1) {
  10933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10934. }
  10935. else {
  10936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10937. }
  10938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10939. }
  10940. else if (generateDepthBuffer) {
  10941. depthStencilBuffer = gl.createRenderbuffer();
  10942. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10943. if (samples > 1) {
  10944. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10945. }
  10946. else {
  10947. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10948. }
  10949. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10950. }
  10951. return depthStencilBuffer;
  10952. };
  10953. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10954. if (this.webGLVersion < 2 || !texture) {
  10955. return 1;
  10956. }
  10957. if (texture.samples === samples) {
  10958. return samples;
  10959. }
  10960. var gl = this._gl;
  10961. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10962. // Dispose previous render buffers
  10963. if (texture._depthStencilBuffer) {
  10964. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10965. }
  10966. if (texture._MSAAFramebuffer) {
  10967. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10968. }
  10969. if (texture._MSAARenderBuffer) {
  10970. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10971. }
  10972. if (samples > 1) {
  10973. var framebuffer = gl.createFramebuffer();
  10974. if (!framebuffer) {
  10975. throw new Error("Unable to create multi sampled framebuffer");
  10976. }
  10977. texture._MSAAFramebuffer = framebuffer;
  10978. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10979. var colorRenderbuffer = gl.createRenderbuffer();
  10980. if (!colorRenderbuffer) {
  10981. throw new Error("Unable to create multi sampled framebuffer");
  10982. }
  10983. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10984. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10985. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10986. texture._MSAARenderBuffer = colorRenderbuffer;
  10987. }
  10988. else {
  10989. this.bindUnboundFramebuffer(texture._framebuffer);
  10990. }
  10991. texture.samples = samples;
  10992. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10993. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10994. this.bindUnboundFramebuffer(null);
  10995. return samples;
  10996. };
  10997. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10998. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10999. };
  11000. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11001. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11002. };
  11003. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11004. var gl = this._gl;
  11005. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11006. var generateMipMaps = true;
  11007. var generateDepthBuffer = true;
  11008. var generateStencilBuffer = false;
  11009. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11010. if (options !== undefined) {
  11011. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11012. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11013. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11014. if (options.samplingMode !== undefined) {
  11015. samplingMode = options.samplingMode;
  11016. }
  11017. }
  11018. texture.isCube = true;
  11019. texture.generateMipMaps = generateMipMaps;
  11020. texture.samples = 1;
  11021. texture.samplingMode = samplingMode;
  11022. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11023. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11024. for (var face = 0; face < 6; face++) {
  11025. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11026. }
  11027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11031. // Create the framebuffer
  11032. var framebuffer = gl.createFramebuffer();
  11033. this.bindUnboundFramebuffer(framebuffer);
  11034. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11035. // Mipmaps
  11036. if (texture.generateMipMaps) {
  11037. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11038. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11039. }
  11040. // Unbind
  11041. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11042. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11043. this.bindUnboundFramebuffer(null);
  11044. texture._framebuffer = framebuffer;
  11045. texture.width = size;
  11046. texture.height = size;
  11047. texture.isReady = true;
  11048. this.resetTextureCache();
  11049. this._internalTexturesCache.push(texture);
  11050. return texture;
  11051. };
  11052. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11053. var _this = this;
  11054. if (onLoad === void 0) { onLoad = null; }
  11055. if (onError === void 0) { onError = null; }
  11056. if (forcedExtension === void 0) { forcedExtension = null; }
  11057. var callback = function (loadData) {
  11058. if (!loadData) {
  11059. if (onLoad) {
  11060. onLoad(null);
  11061. }
  11062. return;
  11063. }
  11064. var texture = loadData.texture;
  11065. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11066. texture._lodGenerationScale = scale;
  11067. texture._lodGenerationOffset = offset;
  11068. if (_this._caps.textureLOD) {
  11069. // Do not add extra process if texture lod is supported.
  11070. if (onLoad) {
  11071. onLoad(texture);
  11072. }
  11073. return;
  11074. }
  11075. var mipSlices = 3;
  11076. var gl = _this._gl;
  11077. var width = loadData.width;
  11078. if (!width) {
  11079. return;
  11080. }
  11081. var textures = [];
  11082. for (var i = 0; i < mipSlices; i++) {
  11083. //compute LOD from even spacing in smoothness (matching shader calculation)
  11084. var smoothness = i / (mipSlices - 1);
  11085. var roughness = 1 - smoothness;
  11086. var minLODIndex = offset; // roughness = 0
  11087. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11088. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11089. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11090. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11091. glTextureFromLod.isCube = true;
  11092. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  11093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11097. if (loadData.isDDS) {
  11098. var info = loadData.info;
  11099. var data = loadData.data;
  11100. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11101. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11102. }
  11103. else {
  11104. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11105. }
  11106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11107. // Wrap in a base texture for easy binding.
  11108. var lodTexture = new BABYLON.BaseTexture(scene);
  11109. lodTexture.isCube = true;
  11110. lodTexture._texture = glTextureFromLod;
  11111. glTextureFromLod.isReady = true;
  11112. textures.push(lodTexture);
  11113. }
  11114. texture._lodTextureHigh = textures[2];
  11115. texture._lodTextureMid = textures[1];
  11116. texture._lodTextureLow = textures[0];
  11117. if (onLoad) {
  11118. onLoad(texture);
  11119. }
  11120. };
  11121. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11122. };
  11123. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11124. var _this = this;
  11125. if (onLoad === void 0) { onLoad = null; }
  11126. if (onError === void 0) { onError = null; }
  11127. if (forcedExtension === void 0) { forcedExtension = null; }
  11128. var gl = this._gl;
  11129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11130. texture.isCube = true;
  11131. texture.url = rootUrl;
  11132. texture.generateMipMaps = !noMipmap;
  11133. if (!this._doNotHandleContextLost) {
  11134. texture._extension = forcedExtension;
  11135. texture._files = files;
  11136. }
  11137. var isKTX = false;
  11138. var isDDS = false;
  11139. var lastDot = rootUrl.lastIndexOf('.');
  11140. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11141. if (this._textureFormatInUse) {
  11142. extension = this._textureFormatInUse;
  11143. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11144. isKTX = true;
  11145. }
  11146. else {
  11147. isDDS = (extension === ".dds");
  11148. }
  11149. var onerror = function (request, exception) {
  11150. if (onError && request) {
  11151. onError(request.status + " " + request.statusText, exception);
  11152. }
  11153. };
  11154. if (isKTX) {
  11155. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11156. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11157. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11158. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11159. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11160. ktx.uploadLevels(_this._gl, !noMipmap);
  11161. _this.setCubeMapTextureParams(gl, loadMipmap);
  11162. texture.width = ktx.pixelWidth;
  11163. texture.height = ktx.pixelHeight;
  11164. texture.isReady = true;
  11165. }, undefined, undefined, true, onerror);
  11166. }
  11167. else if (isDDS) {
  11168. if (files && files.length === 6) {
  11169. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11170. var info;
  11171. var loadMipmap = false;
  11172. var width = 0;
  11173. for (var index = 0; index < imgs.length; index++) {
  11174. var data = imgs[index];
  11175. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11176. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11177. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11178. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11179. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11180. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11181. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11182. }
  11183. texture.width = info.width;
  11184. texture.height = info.height;
  11185. texture.type = info.textureType;
  11186. width = info.width;
  11187. }
  11188. _this.setCubeMapTextureParams(gl, loadMipmap);
  11189. texture.isReady = true;
  11190. if (onLoad) {
  11191. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11192. }
  11193. }, files, onError);
  11194. }
  11195. else {
  11196. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11197. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11198. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11199. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11200. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11201. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11202. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11203. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11204. }
  11205. _this.setCubeMapTextureParams(gl, loadMipmap);
  11206. texture.width = info.width;
  11207. texture.height = info.height;
  11208. texture.isReady = true;
  11209. texture.type = info.textureType;
  11210. if (onLoad) {
  11211. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11212. }
  11213. }, undefined, undefined, true, onerror);
  11214. }
  11215. }
  11216. else {
  11217. if (!files) {
  11218. throw new Error("Cannot load cubemap because files were not defined");
  11219. }
  11220. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11221. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11222. var height = width;
  11223. _this._prepareWorkingCanvas();
  11224. if (!_this._workingCanvas || !_this._workingContext) {
  11225. return;
  11226. }
  11227. _this._workingCanvas.width = width;
  11228. _this._workingCanvas.height = height;
  11229. var faces = [
  11230. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11231. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11232. ];
  11233. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11234. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11235. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11236. for (var index = 0; index < faces.length; index++) {
  11237. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11238. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11239. }
  11240. if (!noMipmap) {
  11241. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11242. }
  11243. _this.setCubeMapTextureParams(gl, !noMipmap);
  11244. texture.width = width;
  11245. texture.height = height;
  11246. texture.isReady = true;
  11247. if (format) {
  11248. texture.format = format;
  11249. }
  11250. texture.onLoadedObservable.notifyObservers(texture);
  11251. texture.onLoadedObservable.clear();
  11252. if (onLoad) {
  11253. onLoad();
  11254. }
  11255. }, files, onError);
  11256. }
  11257. this._internalTexturesCache.push(texture);
  11258. return texture;
  11259. };
  11260. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11265. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11266. this.resetTextureCache();
  11267. };
  11268. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11269. if (compression === void 0) { compression = null; }
  11270. if (level === void 0) { level = 0; }
  11271. texture._bufferViewArray = data;
  11272. texture.format = format;
  11273. texture.type = type;
  11274. texture.invertY = invertY;
  11275. texture._compression = compression;
  11276. var gl = this._gl;
  11277. var textureType = this._getWebGLTextureType(type);
  11278. var internalFormat = this._getInternalFormat(format);
  11279. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11280. var needConversion = false;
  11281. if (internalFormat === gl.RGB) {
  11282. internalFormat = gl.RGBA;
  11283. needConversion = true;
  11284. }
  11285. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11286. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11287. if (texture.width % 4 !== 0) {
  11288. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11289. }
  11290. // Data are known to be in +X +Y +Z -X -Y -Z
  11291. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11292. var faceData = data[faceIndex];
  11293. if (compression) {
  11294. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11295. }
  11296. else {
  11297. if (needConversion) {
  11298. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11299. }
  11300. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11301. }
  11302. }
  11303. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11304. if (isPot && texture.generateMipMaps && level === 0) {
  11305. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11306. }
  11307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11308. this.resetTextureCache();
  11309. texture.isReady = true;
  11310. };
  11311. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11312. if (compression === void 0) { compression = null; }
  11313. var gl = this._gl;
  11314. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11315. texture.isCube = true;
  11316. texture.generateMipMaps = generateMipMaps;
  11317. texture.format = format;
  11318. texture.type = type;
  11319. if (!this._doNotHandleContextLost) {
  11320. texture._bufferViewArray = data;
  11321. }
  11322. var textureType = this._getWebGLTextureType(type);
  11323. var internalFormat = this._getInternalFormat(format);
  11324. if (internalFormat === gl.RGB) {
  11325. internalFormat = gl.RGBA;
  11326. }
  11327. var width = size;
  11328. var height = width;
  11329. texture.width = width;
  11330. texture.height = height;
  11331. // Double check on POT to generate Mips.
  11332. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11333. if (!isPot) {
  11334. generateMipMaps = false;
  11335. }
  11336. // Upload data if needed. The texture won't be ready until then.
  11337. if (data) {
  11338. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11339. }
  11340. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11341. // Filters
  11342. if (data && generateMipMaps) {
  11343. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11344. }
  11345. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11348. }
  11349. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11350. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11351. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11352. }
  11353. else {
  11354. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11357. }
  11358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11360. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11361. return texture;
  11362. };
  11363. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11364. var _this = this;
  11365. if (onLoad === void 0) { onLoad = null; }
  11366. if (onError === void 0) { onError = null; }
  11367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11368. if (invertY === void 0) { invertY = false; }
  11369. var gl = this._gl;
  11370. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11371. scene._addPendingData(texture);
  11372. texture.url = url;
  11373. this._internalTexturesCache.push(texture);
  11374. var onerror = function (request, exception) {
  11375. scene._removePendingData(texture);
  11376. if (onError && request) {
  11377. onError(request.status + " " + request.statusText, exception);
  11378. }
  11379. };
  11380. var internalCallback = function (data) {
  11381. var width = texture.width;
  11382. var faceDataArrays = callback(data);
  11383. if (!faceDataArrays) {
  11384. return;
  11385. }
  11386. if (mipmmapGenerator) {
  11387. var textureType = _this._getWebGLTextureType(type);
  11388. var internalFormat = _this._getInternalFormat(format);
  11389. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11390. var needConversion = false;
  11391. if (internalFormat === gl.RGB) {
  11392. internalFormat = gl.RGBA;
  11393. needConversion = true;
  11394. }
  11395. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11396. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11397. var mipData = mipmmapGenerator(faceDataArrays);
  11398. for (var level = 0; level < mipData.length; level++) {
  11399. var mipSize = width >> level;
  11400. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11401. var mipFaceData = mipData[level][faceIndex];
  11402. if (needConversion) {
  11403. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11404. }
  11405. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11406. }
  11407. }
  11408. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11409. }
  11410. else {
  11411. texture.generateMipMaps = !noMipmap;
  11412. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11413. }
  11414. texture.isReady = true;
  11415. _this.resetTextureCache();
  11416. scene._removePendingData(texture);
  11417. if (onLoad) {
  11418. onLoad();
  11419. }
  11420. };
  11421. BABYLON.Tools.LoadFile(url, function (data) {
  11422. internalCallback(data);
  11423. }, undefined, scene.database, true, onerror);
  11424. return texture;
  11425. };
  11426. ;
  11427. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11428. if (compression === void 0) { compression = null; }
  11429. var internalFormat = this._getInternalFormat(format);
  11430. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11431. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11432. if (!this._doNotHandleContextLost) {
  11433. texture._bufferView = data;
  11434. texture.format = format;
  11435. texture.invertY = invertY;
  11436. texture._compression = compression;
  11437. }
  11438. if (texture.width % 4 !== 0) {
  11439. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11440. }
  11441. if (compression && data) {
  11442. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11443. }
  11444. else {
  11445. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11446. }
  11447. if (texture.generateMipMaps) {
  11448. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11449. }
  11450. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11451. this.resetTextureCache();
  11452. texture.isReady = true;
  11453. };
  11454. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11455. if (compression === void 0) { compression = null; }
  11456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11457. texture.baseWidth = width;
  11458. texture.baseHeight = height;
  11459. texture.baseDepth = depth;
  11460. texture.width = width;
  11461. texture.height = height;
  11462. texture.depth = depth;
  11463. texture.format = format;
  11464. texture.generateMipMaps = generateMipMaps;
  11465. texture.samplingMode = samplingMode;
  11466. texture.is3D = true;
  11467. if (!this._doNotHandleContextLost) {
  11468. texture._bufferView = data;
  11469. }
  11470. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11471. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11472. // Filters
  11473. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11474. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11476. if (generateMipMaps) {
  11477. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11478. }
  11479. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11480. this._internalTexturesCache.push(texture);
  11481. return texture;
  11482. };
  11483. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11484. var gl = this._gl;
  11485. if (!gl) {
  11486. return;
  11487. }
  11488. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11491. if (!noMipmap && !isCompressed) {
  11492. gl.generateMipmap(gl.TEXTURE_2D);
  11493. }
  11494. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11495. this.resetTextureCache();
  11496. if (scene) {
  11497. scene._removePendingData(texture);
  11498. }
  11499. texture.onLoadedObservable.notifyObservers(texture);
  11500. texture.onLoadedObservable.clear();
  11501. };
  11502. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11503. var _this = this;
  11504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11505. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11506. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11507. var gl = this._gl;
  11508. if (!gl) {
  11509. return;
  11510. }
  11511. if (!texture._webGLTexture) {
  11512. this.resetTextureCache();
  11513. if (scene) {
  11514. scene._removePendingData(texture);
  11515. }
  11516. return;
  11517. }
  11518. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11519. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11520. texture.baseWidth = width;
  11521. texture.baseHeight = height;
  11522. texture.width = potWidth;
  11523. texture.height = potHeight;
  11524. texture.isReady = true;
  11525. if (processFunction(potWidth, potHeight, function () {
  11526. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11527. })) {
  11528. // Returning as texture needs extra async steps
  11529. return;
  11530. }
  11531. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11532. };
  11533. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11534. // Create new RGBA data container.
  11535. var rgbaData;
  11536. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11537. rgbaData = new Float32Array(width * height * 4);
  11538. }
  11539. else {
  11540. rgbaData = new Uint32Array(width * height * 4);
  11541. }
  11542. // Convert each pixel.
  11543. for (var x = 0; x < width; x++) {
  11544. for (var y = 0; y < height; y++) {
  11545. var index = (y * width + x) * 3;
  11546. var newIndex = (y * width + x) * 4;
  11547. // Map Old Value to new value.
  11548. rgbaData[newIndex + 0] = rgbData[index + 0];
  11549. rgbaData[newIndex + 1] = rgbData[index + 1];
  11550. rgbaData[newIndex + 2] = rgbData[index + 2];
  11551. // Add fully opaque alpha channel.
  11552. rgbaData[newIndex + 3] = 1;
  11553. }
  11554. }
  11555. return rgbaData;
  11556. };
  11557. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11558. var gl = this._gl;
  11559. if (texture._framebuffer) {
  11560. gl.deleteFramebuffer(texture._framebuffer);
  11561. texture._framebuffer = null;
  11562. }
  11563. if (texture._depthStencilBuffer) {
  11564. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11565. texture._depthStencilBuffer = null;
  11566. }
  11567. if (texture._MSAAFramebuffer) {
  11568. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11569. texture._MSAAFramebuffer = null;
  11570. }
  11571. if (texture._MSAARenderBuffer) {
  11572. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11573. texture._MSAARenderBuffer = null;
  11574. }
  11575. };
  11576. Engine.prototype._releaseTexture = function (texture) {
  11577. var gl = this._gl;
  11578. this._releaseFramebufferObjects(texture);
  11579. gl.deleteTexture(texture._webGLTexture);
  11580. // Unbind channels
  11581. this.unbindAllTextures();
  11582. var index = this._internalTexturesCache.indexOf(texture);
  11583. if (index !== -1) {
  11584. this._internalTexturesCache.splice(index, 1);
  11585. }
  11586. // Integrated fixed lod samplers.
  11587. if (texture._lodTextureHigh) {
  11588. texture._lodTextureHigh.dispose();
  11589. }
  11590. if (texture._lodTextureMid) {
  11591. texture._lodTextureMid.dispose();
  11592. }
  11593. if (texture._lodTextureLow) {
  11594. texture._lodTextureLow.dispose();
  11595. }
  11596. };
  11597. Engine.prototype.setProgram = function (program) {
  11598. if (this._currentProgram !== program) {
  11599. this._gl.useProgram(program);
  11600. this._currentProgram = program;
  11601. }
  11602. };
  11603. Engine.prototype.bindSamplers = function (effect) {
  11604. this.setProgram(effect.getProgram());
  11605. var samplers = effect.getSamplers();
  11606. for (var index = 0; index < samplers.length; index++) {
  11607. var uniform = effect.getUniform(samplers[index]);
  11608. if (uniform) {
  11609. this._boundUniforms[index] = uniform;
  11610. }
  11611. }
  11612. this._currentEffect = null;
  11613. };
  11614. Engine.prototype._activateTextureChannel = function (channel) {
  11615. if (this._activeChannel !== channel) {
  11616. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11617. this._activeChannel = channel;
  11618. }
  11619. };
  11620. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11621. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11622. if (index > -1 && index !== this._boundTexturesOrder.length - 1) {
  11623. this._boundTexturesOrder.splice(index, 1);
  11624. this._boundTexturesOrder.push(internalTexture);
  11625. }
  11626. };
  11627. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11628. var currentSlot = internalTexture._designatedSlot;
  11629. internalTexture._designatedSlot = -1;
  11630. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11631. if (index > -1) {
  11632. this._boundTexturesOrder.splice(index, 1);
  11633. }
  11634. return currentSlot;
  11635. };
  11636. Engine.prototype._bindTextureDirectly = function (target, texture, isPartOfTextureArray) {
  11637. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11638. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11639. var isTextureForRendering = texture && texture._initialSlot > -1;
  11640. if (currentTextureBound !== texture) {
  11641. if (currentTextureBound) {
  11642. this._removeDesignatedSlot(currentTextureBound);
  11643. }
  11644. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11645. if (this._activeChannel >= 0) {
  11646. this._boundTexturesCache[this._activeChannel] = texture;
  11647. if (isTextureForRendering) {
  11648. this._boundTexturesOrder.push(texture);
  11649. }
  11650. }
  11651. }
  11652. if (isTextureForRendering) {
  11653. texture._designatedSlot = this._activeChannel;
  11654. if (!isPartOfTextureArray) {
  11655. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11656. }
  11657. }
  11658. };
  11659. Engine.prototype._bindTexture = function (channel, texture) {
  11660. if (channel < 0) {
  11661. return;
  11662. }
  11663. if (texture) {
  11664. channel = this._getCorrectTextureChannel(channel, texture);
  11665. }
  11666. this._activateTextureChannel(channel);
  11667. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11668. };
  11669. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11670. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11671. };
  11672. Engine.prototype.unbindAllTextures = function () {
  11673. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11674. this._activateTextureChannel(channel);
  11675. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11676. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11677. if (this.webGLVersion > 1) {
  11678. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11679. }
  11680. }
  11681. };
  11682. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11683. if (channel < 0) {
  11684. return;
  11685. }
  11686. if (uniform) {
  11687. this._boundUniforms[channel] = uniform;
  11688. }
  11689. this._setTexture(channel, texture);
  11690. };
  11691. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11692. if (!internalTexture) {
  11693. return -1;
  11694. }
  11695. internalTexture._initialSlot = channel;
  11696. if (channel !== internalTexture._designatedSlot) {
  11697. if (internalTexture._designatedSlot > -1) {
  11698. channel = internalTexture._designatedSlot;
  11699. }
  11700. else {
  11701. if (this._nextFreeTextureSlot > -1) {
  11702. channel = this._nextFreeTextureSlot;
  11703. this._nextFreeTextureSlot++;
  11704. if (this._nextFreeTextureSlot >= this._caps.maxTexturesImageUnits) {
  11705. this._nextFreeTextureSlot = -1; // No more free slots, we will recycle
  11706. }
  11707. }
  11708. else {
  11709. channel = this._removeDesignatedSlot(this._boundTexturesOrder[0]);
  11710. }
  11711. }
  11712. }
  11713. return channel;
  11714. };
  11715. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11716. var uniform = this._boundUniforms[sourceSlot];
  11717. this._gl.uniform1i(uniform, destination);
  11718. };
  11719. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11720. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11721. // Not ready?
  11722. if (!texture) {
  11723. if (this._boundTexturesCache[channel] != null) {
  11724. this._activateTextureChannel(channel);
  11725. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11726. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11727. if (this.webGLVersion > 1) {
  11728. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11729. }
  11730. }
  11731. return false;
  11732. }
  11733. // Video
  11734. var alreadyActivated = false;
  11735. if (texture.video) {
  11736. this._activateTextureChannel(channel);
  11737. alreadyActivated = true;
  11738. texture.update();
  11739. }
  11740. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11741. texture.delayLoad();
  11742. return false;
  11743. }
  11744. var internalTexture;
  11745. if (texture.isReady()) {
  11746. internalTexture = texture.getInternalTexture();
  11747. }
  11748. else if (texture.isCube) {
  11749. internalTexture = this.emptyCubeTexture;
  11750. }
  11751. else if (texture.is3D) {
  11752. internalTexture = this.emptyTexture3D;
  11753. }
  11754. else {
  11755. internalTexture = this.emptyTexture;
  11756. }
  11757. if (!isPartOfTextureArray) {
  11758. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11759. }
  11760. if (this._boundTexturesCache[channel] === internalTexture) {
  11761. this._moveBoundTextureOnTop(internalTexture);
  11762. if (!isPartOfTextureArray) {
  11763. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11764. }
  11765. return false;
  11766. }
  11767. if (!alreadyActivated) {
  11768. this._activateTextureChannel(channel);
  11769. }
  11770. if (internalTexture && internalTexture.is3D) {
  11771. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11772. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11773. internalTexture._cachedWrapU = texture.wrapU;
  11774. switch (texture.wrapU) {
  11775. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11776. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11777. break;
  11778. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11779. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11780. break;
  11781. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11782. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11783. break;
  11784. }
  11785. }
  11786. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11787. internalTexture._cachedWrapV = texture.wrapV;
  11788. switch (texture.wrapV) {
  11789. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11790. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11791. break;
  11792. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11794. break;
  11795. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11797. break;
  11798. }
  11799. }
  11800. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11801. internalTexture._cachedWrapR = texture.wrapR;
  11802. switch (texture.wrapV) {
  11803. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11804. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11805. break;
  11806. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11808. break;
  11809. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11811. break;
  11812. }
  11813. }
  11814. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11815. }
  11816. else if (internalTexture && internalTexture.isCube) {
  11817. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  11818. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11819. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11820. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11821. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11822. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11823. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11824. }
  11825. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11826. }
  11827. else {
  11828. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  11829. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11830. internalTexture._cachedWrapU = texture.wrapU;
  11831. switch (texture.wrapU) {
  11832. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11833. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11834. break;
  11835. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11837. break;
  11838. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11840. break;
  11841. }
  11842. }
  11843. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11844. internalTexture._cachedWrapV = texture.wrapV;
  11845. switch (texture.wrapV) {
  11846. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11848. break;
  11849. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11851. break;
  11852. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11854. break;
  11855. }
  11856. }
  11857. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11858. }
  11859. return true;
  11860. };
  11861. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11862. if (channel < 0 || !uniform) {
  11863. return;
  11864. }
  11865. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11866. this._textureUnits = new Int32Array(textures.length);
  11867. }
  11868. for (var i = 0; i < textures.length; i++) {
  11869. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  11870. }
  11871. this._gl.uniform1iv(uniform, this._textureUnits);
  11872. for (var index = 0; index < textures.length; index++) {
  11873. this._setTexture(this._textureUnits[index], textures[index], true);
  11874. }
  11875. };
  11876. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11877. var internalTexture = texture.getInternalTexture();
  11878. if (!internalTexture) {
  11879. return;
  11880. }
  11881. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11882. var value = texture.anisotropicFilteringLevel;
  11883. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11884. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11885. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11886. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11887. }
  11888. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11889. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11890. internalTexture._cachedAnisotropicFilteringLevel = value;
  11891. }
  11892. };
  11893. Engine.prototype.readPixels = function (x, y, width, height) {
  11894. var data = new Uint8Array(height * width * 4);
  11895. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11896. return data;
  11897. };
  11898. /**
  11899. * Add an externaly attached data from its key.
  11900. * This method call will fail and return false, if such key already exists.
  11901. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11902. * @param key the unique key that identifies the data
  11903. * @param data the data object to associate to the key for this Engine instance
  11904. * @return true if no such key were already present and the data was added successfully, false otherwise
  11905. */
  11906. Engine.prototype.addExternalData = function (key, data) {
  11907. if (!this._externalData) {
  11908. this._externalData = new BABYLON.StringDictionary();
  11909. }
  11910. return this._externalData.add(key, data);
  11911. };
  11912. /**
  11913. * Get an externaly attached data from its key
  11914. * @param key the unique key that identifies the data
  11915. * @return the associated data, if present (can be null), or undefined if not present
  11916. */
  11917. Engine.prototype.getExternalData = function (key) {
  11918. if (!this._externalData) {
  11919. this._externalData = new BABYLON.StringDictionary();
  11920. }
  11921. return this._externalData.get(key);
  11922. };
  11923. /**
  11924. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11925. * @param key the unique key that identifies the data
  11926. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11927. * @return the associated data, can be null if the factory returned null.
  11928. */
  11929. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11930. if (!this._externalData) {
  11931. this._externalData = new BABYLON.StringDictionary();
  11932. }
  11933. return this._externalData.getOrAddWithFactory(key, factory);
  11934. };
  11935. /**
  11936. * Remove an externaly attached data from the Engine instance
  11937. * @param key the unique key that identifies the data
  11938. * @return true if the data was successfully removed, false if it doesn't exist
  11939. */
  11940. Engine.prototype.removeExternalData = function (key) {
  11941. if (!this._externalData) {
  11942. this._externalData = new BABYLON.StringDictionary();
  11943. }
  11944. return this._externalData.remove(key);
  11945. };
  11946. Engine.prototype.unbindAllAttributes = function () {
  11947. if (this._mustWipeVertexAttributes) {
  11948. this._mustWipeVertexAttributes = false;
  11949. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11950. this._gl.disableVertexAttribArray(i);
  11951. this._vertexAttribArraysEnabled[i] = false;
  11952. this._currentBufferPointers[i].active = false;
  11953. }
  11954. return;
  11955. }
  11956. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11957. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11958. continue;
  11959. }
  11960. this._gl.disableVertexAttribArray(i);
  11961. this._vertexAttribArraysEnabled[i] = false;
  11962. this._currentBufferPointers[i].active = false;
  11963. }
  11964. };
  11965. Engine.prototype.releaseEffects = function () {
  11966. for (var name in this._compiledEffects) {
  11967. this._deleteProgram(this._compiledEffects[name]._program);
  11968. }
  11969. this._compiledEffects = {};
  11970. };
  11971. // Dispose
  11972. Engine.prototype.dispose = function () {
  11973. this.hideLoadingUI();
  11974. this.stopRenderLoop();
  11975. // Release postProcesses
  11976. while (this.postProcesses.length) {
  11977. this.postProcesses[0].dispose();
  11978. }
  11979. // Empty texture
  11980. if (this._emptyTexture) {
  11981. this._releaseTexture(this._emptyTexture);
  11982. this._emptyTexture = null;
  11983. }
  11984. if (this._emptyCubeTexture) {
  11985. this._releaseTexture(this._emptyCubeTexture);
  11986. this._emptyCubeTexture = null;
  11987. }
  11988. // Rescale PP
  11989. if (this._rescalePostProcess) {
  11990. this._rescalePostProcess.dispose();
  11991. }
  11992. // Release scenes
  11993. while (this.scenes.length) {
  11994. this.scenes[0].dispose();
  11995. }
  11996. // Release audio engine
  11997. if (Engine.audioEngine) {
  11998. Engine.audioEngine.dispose();
  11999. }
  12000. // Release effects
  12001. this.releaseEffects();
  12002. // Unbind
  12003. this.unbindAllAttributes();
  12004. if (this._dummyFramebuffer) {
  12005. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12006. }
  12007. //WebVR
  12008. this.disableVR();
  12009. // Events
  12010. if (BABYLON.Tools.IsWindowObjectExist()) {
  12011. window.removeEventListener("blur", this._onBlur);
  12012. window.removeEventListener("focus", this._onFocus);
  12013. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12014. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12015. if (this._renderingCanvas) {
  12016. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12017. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12018. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12019. if (!this._doNotHandleContextLost) {
  12020. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12021. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12022. }
  12023. }
  12024. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12025. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12026. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12027. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12028. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12029. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12030. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12031. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12032. if (this._onVrDisplayConnect) {
  12033. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12034. if (this._onVrDisplayDisconnect) {
  12035. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12036. }
  12037. if (this._onVrDisplayPresentChange) {
  12038. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12039. }
  12040. this._onVrDisplayConnect = null;
  12041. this._onVrDisplayDisconnect = null;
  12042. }
  12043. }
  12044. // Remove from Instances
  12045. var index = Engine.Instances.indexOf(this);
  12046. if (index >= 0) {
  12047. Engine.Instances.splice(index, 1);
  12048. }
  12049. this._workingCanvas = null;
  12050. this._workingContext = null;
  12051. this._currentBufferPointers = [];
  12052. this._renderingCanvas = null;
  12053. this._currentProgram = null;
  12054. this.onResizeObservable.clear();
  12055. this.onCanvasBlurObservable.clear();
  12056. this.onCanvasFocusObservable.clear();
  12057. this.onCanvasPointerOutObservable.clear();
  12058. this.onBeginFrameObservable.clear();
  12059. this.onEndFrameObservable.clear();
  12060. BABYLON.Effect.ResetCache();
  12061. };
  12062. // Loading screen
  12063. Engine.prototype.displayLoadingUI = function () {
  12064. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12065. return;
  12066. }
  12067. var loadingScreen = this.loadingScreen;
  12068. if (loadingScreen) {
  12069. loadingScreen.displayLoadingUI();
  12070. }
  12071. };
  12072. Engine.prototype.hideLoadingUI = function () {
  12073. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12074. return;
  12075. }
  12076. var loadingScreen = this.loadingScreen;
  12077. if (loadingScreen) {
  12078. loadingScreen.hideLoadingUI();
  12079. }
  12080. };
  12081. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12082. get: function () {
  12083. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12084. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12085. return this._loadingScreen;
  12086. },
  12087. set: function (loadingScreen) {
  12088. this._loadingScreen = loadingScreen;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12094. set: function (text) {
  12095. this.loadingScreen.loadingUIText = text;
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12101. set: function (color) {
  12102. this.loadingScreen.loadingUIBackgroundColor = color;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Engine.prototype.attachContextLostEvent = function (callback) {
  12108. if (this._renderingCanvas) {
  12109. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12110. }
  12111. };
  12112. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12113. if (this._renderingCanvas) {
  12114. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12115. }
  12116. };
  12117. Engine.prototype.getVertexShaderSource = function (program) {
  12118. var shaders = this._gl.getAttachedShaders(program);
  12119. if (!shaders) {
  12120. return null;
  12121. }
  12122. return this._gl.getShaderSource(shaders[0]);
  12123. };
  12124. Engine.prototype.getFragmentShaderSource = function (program) {
  12125. var shaders = this._gl.getAttachedShaders(program);
  12126. if (!shaders) {
  12127. return null;
  12128. }
  12129. return this._gl.getShaderSource(shaders[1]);
  12130. };
  12131. Engine.prototype.getError = function () {
  12132. return this._gl.getError();
  12133. };
  12134. // FPS
  12135. Engine.prototype.getFps = function () {
  12136. return this._fps;
  12137. };
  12138. Engine.prototype.getDeltaTime = function () {
  12139. return this._deltaTime;
  12140. };
  12141. Engine.prototype._measureFps = function () {
  12142. this._performanceMonitor.sampleFrame();
  12143. this._fps = this._performanceMonitor.averageFPS;
  12144. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12145. };
  12146. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12147. if (faceIndex === void 0) { faceIndex = -1; }
  12148. var gl = this._gl;
  12149. if (!this._dummyFramebuffer) {
  12150. var dummy = gl.createFramebuffer();
  12151. if (!dummy) {
  12152. throw new Error("Unable to create dummy framebuffer");
  12153. }
  12154. this._dummyFramebuffer = dummy;
  12155. }
  12156. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12157. if (faceIndex > -1) {
  12158. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12159. }
  12160. else {
  12161. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12162. }
  12163. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12164. var buffer;
  12165. switch (readType) {
  12166. case gl.UNSIGNED_BYTE:
  12167. buffer = new Uint8Array(4 * width * height);
  12168. readType = gl.UNSIGNED_BYTE;
  12169. break;
  12170. default:
  12171. buffer = new Float32Array(4 * width * height);
  12172. readType = gl.FLOAT;
  12173. break;
  12174. }
  12175. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12176. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12177. return buffer;
  12178. };
  12179. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12180. if (this._webGLVersion > 1) {
  12181. return this._caps.colorBufferFloat;
  12182. }
  12183. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  12184. };
  12185. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12186. if (this._webGLVersion > 1) {
  12187. return this._caps.colorBufferFloat;
  12188. }
  12189. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  12190. };
  12191. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12192. Engine.prototype._canRenderToFramebuffer = function (type) {
  12193. var gl = this._gl;
  12194. //clear existing errors
  12195. while (gl.getError() !== gl.NO_ERROR) { }
  12196. var successful = true;
  12197. var texture = gl.createTexture();
  12198. gl.bindTexture(gl.TEXTURE_2D, texture);
  12199. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12202. var fb = gl.createFramebuffer();
  12203. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12205. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12206. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12207. successful = successful && (gl.getError() === gl.NO_ERROR);
  12208. //try render by clearing frame buffer's color buffer
  12209. if (successful) {
  12210. gl.clear(gl.COLOR_BUFFER_BIT);
  12211. successful = successful && (gl.getError() === gl.NO_ERROR);
  12212. }
  12213. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12214. if (successful) {
  12215. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12216. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12217. var readFormat = gl.RGBA;
  12218. var readType = gl.UNSIGNED_BYTE;
  12219. var buffer = new Uint8Array(4);
  12220. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12221. successful = successful && (gl.getError() === gl.NO_ERROR);
  12222. }
  12223. //clean up
  12224. gl.deleteTexture(texture);
  12225. gl.deleteFramebuffer(fb);
  12226. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12227. //clear accumulated errors
  12228. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12229. return successful;
  12230. };
  12231. Engine.prototype._getWebGLTextureType = function (type) {
  12232. if (type === Engine.TEXTURETYPE_FLOAT) {
  12233. return this._gl.FLOAT;
  12234. }
  12235. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12236. // Add Half Float Constant.
  12237. return this._gl.HALF_FLOAT_OES;
  12238. }
  12239. return this._gl.UNSIGNED_BYTE;
  12240. };
  12241. ;
  12242. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12243. if (this._webGLVersion === 1) {
  12244. return this._gl.RGBA;
  12245. }
  12246. if (type === Engine.TEXTURETYPE_FLOAT) {
  12247. return this._gl.RGBA32F;
  12248. }
  12249. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12250. return this._gl.RGBA16F;
  12251. }
  12252. return this._gl.RGBA;
  12253. };
  12254. ;
  12255. Engine.prototype.createQuery = function () {
  12256. return this._gl.createQuery();
  12257. };
  12258. Engine.prototype.deleteQuery = function (query) {
  12259. this._gl.deleteQuery(query);
  12260. return this;
  12261. };
  12262. Engine.prototype.isQueryResultAvailable = function (query) {
  12263. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12264. };
  12265. Engine.prototype.getQueryResult = function (query) {
  12266. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12267. };
  12268. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12269. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12270. this._gl.beginQuery(glAlgorithm, query);
  12271. return this;
  12272. };
  12273. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12274. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12275. this._gl.endQuery(glAlgorithm);
  12276. return this;
  12277. };
  12278. /* Time queries */
  12279. Engine.prototype._createTimeQuery = function () {
  12280. var timerQuery = this._caps.timerQuery;
  12281. if (timerQuery.createQueryEXT) {
  12282. return timerQuery.createQueryEXT();
  12283. }
  12284. return this.createQuery();
  12285. };
  12286. Engine.prototype._deleteTimeQuery = function (query) {
  12287. var timerQuery = this._caps.timerQuery;
  12288. if (timerQuery.deleteQueryEXT) {
  12289. timerQuery.deleteQueryEXT(query);
  12290. return;
  12291. }
  12292. this.deleteQuery(query);
  12293. };
  12294. Engine.prototype._getTimeQueryResult = function (query) {
  12295. var timerQuery = this._caps.timerQuery;
  12296. if (timerQuery.getQueryObjectEXT) {
  12297. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12298. }
  12299. return this.getQueryResult(query);
  12300. };
  12301. Engine.prototype._getTimeQueryAvailability = function (query) {
  12302. var timerQuery = this._caps.timerQuery;
  12303. if (timerQuery.getQueryObjectEXT) {
  12304. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12305. }
  12306. return this.isQueryResultAvailable(query);
  12307. };
  12308. Engine.prototype.startTimeQuery = function () {
  12309. var timerQuery = this._caps.timerQuery;
  12310. if (!timerQuery) {
  12311. return null;
  12312. }
  12313. var token = new BABYLON._TimeToken();
  12314. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12315. if (this._caps.canUseTimestampForTimerQuery) {
  12316. token._startTimeQuery = this._createTimeQuery();
  12317. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12318. }
  12319. else {
  12320. if (this._currentNonTimestampToken) {
  12321. return this._currentNonTimestampToken;
  12322. }
  12323. token._timeElapsedQuery = this._createTimeQuery();
  12324. if (timerQuery.beginQueryEXT) {
  12325. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12326. }
  12327. else {
  12328. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12329. }
  12330. this._currentNonTimestampToken = token;
  12331. }
  12332. return token;
  12333. };
  12334. Engine.prototype.endTimeQuery = function (token) {
  12335. var timerQuery = this._caps.timerQuery;
  12336. if (!timerQuery || !token) {
  12337. return -1;
  12338. }
  12339. if (this._caps.canUseTimestampForTimerQuery) {
  12340. if (!token._startTimeQuery) {
  12341. return -1;
  12342. }
  12343. if (!token._endTimeQuery) {
  12344. token._endTimeQuery = this._createTimeQuery();
  12345. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12346. }
  12347. }
  12348. else if (!token._timeElapsedQueryEnded) {
  12349. if (!token._timeElapsedQuery) {
  12350. return -1;
  12351. }
  12352. if (timerQuery.endQueryEXT) {
  12353. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12354. }
  12355. else {
  12356. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12357. }
  12358. token._timeElapsedQueryEnded = true;
  12359. }
  12360. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12361. var available = false;
  12362. if (token._endTimeQuery) {
  12363. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12364. }
  12365. else if (token._timeElapsedQuery) {
  12366. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12367. }
  12368. if (available && !disjoint) {
  12369. var result = 0;
  12370. if (this._caps.canUseTimestampForTimerQuery) {
  12371. if (!token._startTimeQuery || !token._endTimeQuery) {
  12372. return -1;
  12373. }
  12374. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12375. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12376. result = timeEnd - timeStart;
  12377. this._deleteTimeQuery(token._startTimeQuery);
  12378. this._deleteTimeQuery(token._endTimeQuery);
  12379. token._startTimeQuery = null;
  12380. token._endTimeQuery = null;
  12381. }
  12382. else {
  12383. if (!token._timeElapsedQuery) {
  12384. return -1;
  12385. }
  12386. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12387. this._deleteTimeQuery(token._timeElapsedQuery);
  12388. token._timeElapsedQuery = null;
  12389. token._timeElapsedQueryEnded = false;
  12390. this._currentNonTimestampToken = null;
  12391. }
  12392. return result;
  12393. }
  12394. return -1;
  12395. };
  12396. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12397. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12398. };
  12399. // Transform feedback
  12400. Engine.prototype.createTransformFeedback = function () {
  12401. return this._gl.createTransformFeedback();
  12402. };
  12403. Engine.prototype.deleteTransformFeedback = function (value) {
  12404. this._gl.deleteTransformFeedback(value);
  12405. };
  12406. Engine.prototype.bindTransformFeedback = function (value) {
  12407. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12408. };
  12409. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12410. if (usePoints === void 0) { usePoints = true; }
  12411. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12412. };
  12413. Engine.prototype.endTransformFeedback = function () {
  12414. this._gl.endTransformFeedback();
  12415. };
  12416. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12417. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12418. };
  12419. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12420. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12421. };
  12422. // Statics
  12423. Engine.isSupported = function () {
  12424. try {
  12425. var tempcanvas = document.createElement("canvas");
  12426. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12427. return gl != null && !!window.WebGLRenderingContext;
  12428. }
  12429. catch (e) {
  12430. return false;
  12431. }
  12432. };
  12433. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12434. Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63"];
  12435. Engine.Instances = new Array();
  12436. // Const statics
  12437. Engine._ALPHA_DISABLE = 0;
  12438. Engine._ALPHA_ADD = 1;
  12439. Engine._ALPHA_COMBINE = 2;
  12440. Engine._ALPHA_SUBTRACT = 3;
  12441. Engine._ALPHA_MULTIPLY = 4;
  12442. Engine._ALPHA_MAXIMIZED = 5;
  12443. Engine._ALPHA_ONEONE = 6;
  12444. Engine._ALPHA_PREMULTIPLIED = 7;
  12445. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12446. Engine._ALPHA_INTERPOLATE = 9;
  12447. Engine._ALPHA_SCREENMODE = 10;
  12448. Engine._DELAYLOADSTATE_NONE = 0;
  12449. Engine._DELAYLOADSTATE_LOADED = 1;
  12450. Engine._DELAYLOADSTATE_LOADING = 2;
  12451. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12452. Engine._TEXTUREFORMAT_ALPHA = 0;
  12453. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12454. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12455. Engine._TEXTUREFORMAT_RGB = 4;
  12456. Engine._TEXTUREFORMAT_RGBA = 5;
  12457. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12458. Engine._TEXTURETYPE_FLOAT = 1;
  12459. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12460. // Depht or Stencil test Constants.
  12461. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12462. 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.
  12463. 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.
  12464. 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.
  12465. 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.
  12466. 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.
  12467. 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.
  12468. 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.
  12469. // Stencil Actions Constants.
  12470. Engine._KEEP = 0x1E00;
  12471. Engine._REPLACE = 0x1E01;
  12472. Engine._INCR = 0x1E02;
  12473. Engine._DECR = 0x1E03;
  12474. Engine._INVERT = 0x150A;
  12475. Engine._INCR_WRAP = 0x8507;
  12476. Engine._DECR_WRAP = 0x8508;
  12477. // Texture rescaling mode
  12478. Engine._SCALEMODE_FLOOR = 1;
  12479. Engine._SCALEMODE_NEAREST = 2;
  12480. Engine._SCALEMODE_CEILING = 3;
  12481. // Updatable statics so stick with vars here
  12482. Engine.CollisionsEpsilon = 0.001;
  12483. Engine.CodeRepository = "src/";
  12484. Engine.ShadersRepository = "src/Shaders/";
  12485. return Engine;
  12486. }());
  12487. BABYLON.Engine = Engine;
  12488. })(BABYLON || (BABYLON = {}));
  12489. //# sourceMappingURL=babylon.engine.js.map
  12490. var BABYLON;
  12491. (function (BABYLON) {
  12492. /**
  12493. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12494. */
  12495. var Node = /** @class */ (function () {
  12496. /**
  12497. * @constructor
  12498. * @param {string} name - the name and id to be given to this node
  12499. * @param {BABYLON.Scene} the scene this node will be added to
  12500. */
  12501. function Node(name, scene) {
  12502. if (scene === void 0) { scene = null; }
  12503. this.state = "";
  12504. this.metadata = null;
  12505. this.doNotSerialize = false;
  12506. this.animations = new Array();
  12507. this._ranges = {};
  12508. this._isEnabled = true;
  12509. this._isReady = true;
  12510. this._currentRenderId = -1;
  12511. this._parentRenderId = -1;
  12512. /**
  12513. * An event triggered when the mesh is disposed.
  12514. * @type {BABYLON.Observable}
  12515. */
  12516. this.onDisposeObservable = new BABYLON.Observable();
  12517. // Behaviors
  12518. this._behaviors = new Array();
  12519. this.name = name;
  12520. this.id = name;
  12521. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12522. this.uniqueId = this._scene.getUniqueId();
  12523. this._initCache();
  12524. }
  12525. Object.defineProperty(Node.prototype, "parent", {
  12526. get: function () {
  12527. return this._parentNode;
  12528. },
  12529. set: function (parent) {
  12530. if (this._parentNode === parent) {
  12531. return;
  12532. }
  12533. if (this._parentNode) {
  12534. var index = this._parentNode._children.indexOf(this);
  12535. if (index !== -1) {
  12536. this._parentNode._children.splice(index, 1);
  12537. }
  12538. }
  12539. this._parentNode = parent;
  12540. if (this._parentNode) {
  12541. if (!this._parentNode._children) {
  12542. this._parentNode._children = new Array();
  12543. }
  12544. this._parentNode._children.push(this);
  12545. }
  12546. },
  12547. enumerable: true,
  12548. configurable: true
  12549. });
  12550. Node.prototype.getClassName = function () {
  12551. return "Node";
  12552. };
  12553. Object.defineProperty(Node.prototype, "onDispose", {
  12554. set: function (callback) {
  12555. if (this._onDisposeObserver) {
  12556. this.onDisposeObservable.remove(this._onDisposeObserver);
  12557. }
  12558. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. Node.prototype.getScene = function () {
  12564. return this._scene;
  12565. };
  12566. Node.prototype.getEngine = function () {
  12567. return this._scene.getEngine();
  12568. };
  12569. Node.prototype.addBehavior = function (behavior) {
  12570. var _this = this;
  12571. var index = this._behaviors.indexOf(behavior);
  12572. if (index !== -1) {
  12573. return this;
  12574. }
  12575. behavior.init();
  12576. if (this._scene.isLoading) {
  12577. // We defer the attach when the scene will be loaded
  12578. var observer = this._scene.onDataLoadedObservable.add(function () {
  12579. behavior.attach(_this);
  12580. setTimeout(function () {
  12581. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12582. _this._scene.onDataLoadedObservable.remove(observer);
  12583. }, 0);
  12584. });
  12585. }
  12586. else {
  12587. behavior.attach(this);
  12588. }
  12589. this._behaviors.push(behavior);
  12590. return this;
  12591. };
  12592. Node.prototype.removeBehavior = function (behavior) {
  12593. var index = this._behaviors.indexOf(behavior);
  12594. if (index === -1) {
  12595. return this;
  12596. }
  12597. this._behaviors[index].detach();
  12598. this._behaviors.splice(index, 1);
  12599. return this;
  12600. };
  12601. Object.defineProperty(Node.prototype, "behaviors", {
  12602. get: function () {
  12603. return this._behaviors;
  12604. },
  12605. enumerable: true,
  12606. configurable: true
  12607. });
  12608. Node.prototype.getBehaviorByName = function (name) {
  12609. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12610. var behavior = _a[_i];
  12611. if (behavior.name === name) {
  12612. return behavior;
  12613. }
  12614. }
  12615. return null;
  12616. };
  12617. // override it in derived class
  12618. Node.prototype.getWorldMatrix = function () {
  12619. return BABYLON.Matrix.Identity();
  12620. };
  12621. // override it in derived class if you add new variables to the cache
  12622. // and call the parent class method
  12623. Node.prototype._initCache = function () {
  12624. this._cache = {};
  12625. this._cache.parent = undefined;
  12626. };
  12627. Node.prototype.updateCache = function (force) {
  12628. if (!force && this.isSynchronized())
  12629. return;
  12630. this._cache.parent = this.parent;
  12631. this._updateCache();
  12632. };
  12633. // override it in derived class if you add new variables to the cache
  12634. // and call the parent class method if !ignoreParentClass
  12635. Node.prototype._updateCache = function (ignoreParentClass) {
  12636. };
  12637. // override it in derived class if you add new variables to the cache
  12638. Node.prototype._isSynchronized = function () {
  12639. return true;
  12640. };
  12641. Node.prototype._markSyncedWithParent = function () {
  12642. if (this.parent) {
  12643. this._parentRenderId = this.parent._currentRenderId;
  12644. }
  12645. };
  12646. Node.prototype.isSynchronizedWithParent = function () {
  12647. if (!this.parent) {
  12648. return true;
  12649. }
  12650. if (this._parentRenderId !== this.parent._currentRenderId) {
  12651. return false;
  12652. }
  12653. return this.parent.isSynchronized();
  12654. };
  12655. Node.prototype.isSynchronized = function (updateCache) {
  12656. var check = this.hasNewParent();
  12657. check = check || !this.isSynchronizedWithParent();
  12658. check = check || !this._isSynchronized();
  12659. if (updateCache)
  12660. this.updateCache(true);
  12661. return !check;
  12662. };
  12663. Node.prototype.hasNewParent = function (update) {
  12664. if (this._cache.parent === this.parent)
  12665. return false;
  12666. if (update)
  12667. this._cache.parent = this.parent;
  12668. return true;
  12669. };
  12670. /**
  12671. * Is this node ready to be used/rendered
  12672. * @return {boolean} is it ready
  12673. */
  12674. Node.prototype.isReady = function () {
  12675. return this._isReady;
  12676. };
  12677. /**
  12678. * Is this node enabled.
  12679. * If the node has a parent and is enabled, the parent will be inspected as well.
  12680. * @return {boolean} whether this node (and its parent) is enabled.
  12681. * @see setEnabled
  12682. */
  12683. Node.prototype.isEnabled = function () {
  12684. if (!this._isEnabled) {
  12685. return false;
  12686. }
  12687. if (this.parent) {
  12688. return this.parent.isEnabled();
  12689. }
  12690. return true;
  12691. };
  12692. /**
  12693. * Set the enabled state of this node.
  12694. * @param {boolean} value - the new enabled state
  12695. * @see isEnabled
  12696. */
  12697. Node.prototype.setEnabled = function (value) {
  12698. this._isEnabled = value;
  12699. };
  12700. /**
  12701. * Is this node a descendant of the given node.
  12702. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12703. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12704. * @see parent
  12705. */
  12706. Node.prototype.isDescendantOf = function (ancestor) {
  12707. if (this.parent) {
  12708. if (this.parent === ancestor) {
  12709. return true;
  12710. }
  12711. return this.parent.isDescendantOf(ancestor);
  12712. }
  12713. return false;
  12714. };
  12715. /**
  12716. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12717. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12718. * @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.
  12719. * @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.
  12720. */
  12721. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12722. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12723. if (!this._children) {
  12724. return;
  12725. }
  12726. for (var index = 0; index < this._children.length; index++) {
  12727. var item = this._children[index];
  12728. if (!predicate || predicate(item)) {
  12729. results.push(item);
  12730. }
  12731. if (!directDescendantsOnly) {
  12732. item._getDescendants(results, false, predicate);
  12733. }
  12734. }
  12735. };
  12736. /**
  12737. * Will return all nodes that have this node as ascendant.
  12738. * @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.
  12739. * @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.
  12740. * @return {BABYLON.Node[]} all children nodes of all types.
  12741. */
  12742. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12743. var results = new Array();
  12744. this._getDescendants(results, directDescendantsOnly, predicate);
  12745. return results;
  12746. };
  12747. /**
  12748. * Get all child-meshes of this node.
  12749. */
  12750. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12751. var results = [];
  12752. this._getDescendants(results, directDescendantsOnly, function (node) {
  12753. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12754. });
  12755. return results;
  12756. };
  12757. /**
  12758. * Get all child-transformNodes of this node.
  12759. */
  12760. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12761. var results = [];
  12762. this._getDescendants(results, directDescendantsOnly, function (node) {
  12763. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12764. });
  12765. return results;
  12766. };
  12767. /**
  12768. * Get all direct children of this node.
  12769. */
  12770. Node.prototype.getChildren = function (predicate) {
  12771. return this.getDescendants(true, predicate);
  12772. };
  12773. Node.prototype._setReady = function (state) {
  12774. if (state === this._isReady) {
  12775. return;
  12776. }
  12777. if (!state) {
  12778. this._isReady = false;
  12779. return;
  12780. }
  12781. this._isReady = true;
  12782. if (this.onReady) {
  12783. this.onReady(this);
  12784. }
  12785. };
  12786. Node.prototype.getAnimationByName = function (name) {
  12787. for (var i = 0; i < this.animations.length; i++) {
  12788. var animation = this.animations[i];
  12789. if (animation.name === name) {
  12790. return animation;
  12791. }
  12792. }
  12793. return null;
  12794. };
  12795. Node.prototype.createAnimationRange = function (name, from, to) {
  12796. // check name not already in use
  12797. if (!this._ranges[name]) {
  12798. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12799. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12800. if (this.animations[i]) {
  12801. this.animations[i].createRange(name, from, to);
  12802. }
  12803. }
  12804. }
  12805. };
  12806. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12807. if (deleteFrames === void 0) { deleteFrames = true; }
  12808. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12809. if (this.animations[i]) {
  12810. this.animations[i].deleteRange(name, deleteFrames);
  12811. }
  12812. }
  12813. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12814. };
  12815. Node.prototype.getAnimationRange = function (name) {
  12816. return this._ranges[name];
  12817. };
  12818. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12819. var range = this.getAnimationRange(name);
  12820. if (!range) {
  12821. return;
  12822. }
  12823. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12824. };
  12825. Node.prototype.serializeAnimationRanges = function () {
  12826. var serializationRanges = [];
  12827. for (var name in this._ranges) {
  12828. var localRange = this._ranges[name];
  12829. if (!localRange) {
  12830. continue;
  12831. }
  12832. var range = {};
  12833. range.name = name;
  12834. range.from = localRange.from;
  12835. range.to = localRange.to;
  12836. serializationRanges.push(range);
  12837. }
  12838. return serializationRanges;
  12839. };
  12840. // override it in derived class
  12841. Node.prototype.computeWorldMatrix = function (force) {
  12842. return BABYLON.Matrix.Identity();
  12843. };
  12844. Node.prototype.dispose = function () {
  12845. this.parent = null;
  12846. // Callback
  12847. this.onDisposeObservable.notifyObservers(this);
  12848. this.onDisposeObservable.clear();
  12849. // Behaviors
  12850. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12851. var behavior = _a[_i];
  12852. behavior.detach();
  12853. }
  12854. this._behaviors = [];
  12855. };
  12856. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12857. if (parsedNode.ranges) {
  12858. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12859. var data = parsedNode.ranges[index];
  12860. node.createAnimationRange(data.name, data.from, data.to);
  12861. }
  12862. }
  12863. };
  12864. __decorate([
  12865. BABYLON.serialize()
  12866. ], Node.prototype, "name", void 0);
  12867. __decorate([
  12868. BABYLON.serialize()
  12869. ], Node.prototype, "id", void 0);
  12870. __decorate([
  12871. BABYLON.serialize()
  12872. ], Node.prototype, "uniqueId", void 0);
  12873. __decorate([
  12874. BABYLON.serialize()
  12875. ], Node.prototype, "state", void 0);
  12876. __decorate([
  12877. BABYLON.serialize()
  12878. ], Node.prototype, "metadata", void 0);
  12879. return Node;
  12880. }());
  12881. BABYLON.Node = Node;
  12882. })(BABYLON || (BABYLON = {}));
  12883. //# sourceMappingURL=babylon.node.js.map
  12884. var BABYLON;
  12885. (function (BABYLON) {
  12886. var BoundingSphere = /** @class */ (function () {
  12887. function BoundingSphere(minimum, maximum) {
  12888. this.minimum = minimum;
  12889. this.maximum = maximum;
  12890. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12891. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12892. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12893. this.radius = distance * 0.5;
  12894. this.centerWorld = BABYLON.Vector3.Zero();
  12895. this._update(BABYLON.Matrix.Identity());
  12896. }
  12897. // Methods
  12898. BoundingSphere.prototype._update = function (world) {
  12899. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12900. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12901. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12902. };
  12903. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12904. for (var i = 0; i < 6; i++) {
  12905. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12906. return false;
  12907. }
  12908. return true;
  12909. };
  12910. BoundingSphere.prototype.intersectsPoint = function (point) {
  12911. var x = this.centerWorld.x - point.x;
  12912. var y = this.centerWorld.y - point.y;
  12913. var z = this.centerWorld.z - point.z;
  12914. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12915. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12916. return false;
  12917. return true;
  12918. };
  12919. // Statics
  12920. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12921. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12922. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12923. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12924. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12925. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12926. return false;
  12927. return true;
  12928. };
  12929. return BoundingSphere;
  12930. }());
  12931. BABYLON.BoundingSphere = BoundingSphere;
  12932. })(BABYLON || (BABYLON = {}));
  12933. //# sourceMappingURL=babylon.boundingSphere.js.map
  12934. var BABYLON;
  12935. (function (BABYLON) {
  12936. var BoundingBox = /** @class */ (function () {
  12937. function BoundingBox(minimum, maximum) {
  12938. this.minimum = minimum;
  12939. this.maximum = maximum;
  12940. this.vectors = new Array();
  12941. this.vectorsWorld = new Array();
  12942. // Bounding vectors
  12943. this.vectors.push(this.minimum.clone());
  12944. this.vectors.push(this.maximum.clone());
  12945. this.vectors.push(this.minimum.clone());
  12946. this.vectors[2].x = this.maximum.x;
  12947. this.vectors.push(this.minimum.clone());
  12948. this.vectors[3].y = this.maximum.y;
  12949. this.vectors.push(this.minimum.clone());
  12950. this.vectors[4].z = this.maximum.z;
  12951. this.vectors.push(this.maximum.clone());
  12952. this.vectors[5].z = this.minimum.z;
  12953. this.vectors.push(this.maximum.clone());
  12954. this.vectors[6].x = this.minimum.x;
  12955. this.vectors.push(this.maximum.clone());
  12956. this.vectors[7].y = this.minimum.y;
  12957. // OBB
  12958. this.center = this.maximum.add(this.minimum).scale(0.5);
  12959. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12960. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12961. // World
  12962. for (var index = 0; index < this.vectors.length; index++) {
  12963. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12964. }
  12965. this.minimumWorld = BABYLON.Vector3.Zero();
  12966. this.maximumWorld = BABYLON.Vector3.Zero();
  12967. this.centerWorld = BABYLON.Vector3.Zero();
  12968. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12969. this._update(BABYLON.Matrix.Identity());
  12970. }
  12971. // Methods
  12972. BoundingBox.prototype.getWorldMatrix = function () {
  12973. return this._worldMatrix;
  12974. };
  12975. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12976. this._worldMatrix.copyFrom(matrix);
  12977. return this;
  12978. };
  12979. BoundingBox.prototype._update = function (world) {
  12980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12982. for (var index = 0; index < this.vectors.length; index++) {
  12983. var v = this.vectorsWorld[index];
  12984. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12985. if (v.x < this.minimumWorld.x)
  12986. this.minimumWorld.x = v.x;
  12987. if (v.y < this.minimumWorld.y)
  12988. this.minimumWorld.y = v.y;
  12989. if (v.z < this.minimumWorld.z)
  12990. this.minimumWorld.z = v.z;
  12991. if (v.x > this.maximumWorld.x)
  12992. this.maximumWorld.x = v.x;
  12993. if (v.y > this.maximumWorld.y)
  12994. this.maximumWorld.y = v.y;
  12995. if (v.z > this.maximumWorld.z)
  12996. this.maximumWorld.z = v.z;
  12997. }
  12998. // Extend
  12999. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13000. this.extendSizeWorld.scaleInPlace(0.5);
  13001. // OBB
  13002. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13003. this.centerWorld.scaleInPlace(0.5);
  13004. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13005. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13006. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13007. this._worldMatrix = world;
  13008. };
  13009. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13010. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13011. };
  13012. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13013. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13014. };
  13015. BoundingBox.prototype.intersectsPoint = function (point) {
  13016. var delta = -BABYLON.Epsilon;
  13017. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13018. return false;
  13019. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13020. return false;
  13021. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13022. return false;
  13023. return true;
  13024. };
  13025. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13026. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13027. };
  13028. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13029. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13030. return false;
  13031. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13032. return false;
  13033. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13034. return false;
  13035. return true;
  13036. };
  13037. // Statics
  13038. BoundingBox.Intersects = function (box0, box1) {
  13039. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13040. return false;
  13041. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13042. return false;
  13043. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13044. return false;
  13045. return true;
  13046. };
  13047. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13048. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13049. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13050. return (num <= (sphereRadius * sphereRadius));
  13051. };
  13052. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13053. for (var p = 0; p < 6; p++) {
  13054. for (var i = 0; i < 8; i++) {
  13055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13056. return false;
  13057. }
  13058. }
  13059. }
  13060. return true;
  13061. };
  13062. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13063. for (var p = 0; p < 6; p++) {
  13064. var inCount = 8;
  13065. for (var i = 0; i < 8; i++) {
  13066. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13067. --inCount;
  13068. }
  13069. else {
  13070. break;
  13071. }
  13072. }
  13073. if (inCount === 0)
  13074. return false;
  13075. }
  13076. return true;
  13077. };
  13078. return BoundingBox;
  13079. }());
  13080. BABYLON.BoundingBox = BoundingBox;
  13081. })(BABYLON || (BABYLON = {}));
  13082. //# sourceMappingURL=babylon.boundingBox.js.map
  13083. var BABYLON;
  13084. (function (BABYLON) {
  13085. var computeBoxExtents = function (axis, box) {
  13086. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13087. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13088. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13089. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13090. var r = r0 + r1 + r2;
  13091. return {
  13092. min: p - r,
  13093. max: p + r
  13094. };
  13095. };
  13096. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13097. var axisOverlap = function (axis, box0, box1) {
  13098. var result0 = computeBoxExtents(axis, box0);
  13099. var result1 = computeBoxExtents(axis, box1);
  13100. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13101. };
  13102. var BoundingInfo = /** @class */ (function () {
  13103. function BoundingInfo(minimum, maximum) {
  13104. this.minimum = minimum;
  13105. this.maximum = maximum;
  13106. this._isLocked = false;
  13107. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13108. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13109. }
  13110. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13111. get: function () {
  13112. return this._isLocked;
  13113. },
  13114. set: function (value) {
  13115. this._isLocked = value;
  13116. },
  13117. enumerable: true,
  13118. configurable: true
  13119. });
  13120. // Methods
  13121. BoundingInfo.prototype.update = function (world) {
  13122. if (this._isLocked) {
  13123. return;
  13124. }
  13125. this.boundingBox._update(world);
  13126. this.boundingSphere._update(world);
  13127. };
  13128. /**
  13129. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13130. * @param center New center of the bounding info
  13131. * @param extend New extend of the bounding info
  13132. */
  13133. BoundingInfo.prototype.centerOn = function (center, extend) {
  13134. this.minimum = center.subtract(extend);
  13135. this.maximum = center.add(extend);
  13136. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13137. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13138. return this;
  13139. };
  13140. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13141. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13142. return false;
  13143. return this.boundingBox.isInFrustum(frustumPlanes);
  13144. };
  13145. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13146. /**
  13147. * Gets the world distance between the min and max points of the bounding box
  13148. */
  13149. get: function () {
  13150. var boundingBox = this.boundingBox;
  13151. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13152. return size.length();
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13158. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13159. };
  13160. BoundingInfo.prototype._checkCollision = function (collider) {
  13161. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13162. };
  13163. BoundingInfo.prototype.intersectsPoint = function (point) {
  13164. if (!this.boundingSphere.centerWorld) {
  13165. return false;
  13166. }
  13167. if (!this.boundingSphere.intersectsPoint(point)) {
  13168. return false;
  13169. }
  13170. if (!this.boundingBox.intersectsPoint(point)) {
  13171. return false;
  13172. }
  13173. return true;
  13174. };
  13175. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13176. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13177. return false;
  13178. }
  13179. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13180. return false;
  13181. }
  13182. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13183. return false;
  13184. }
  13185. if (!precise) {
  13186. return true;
  13187. }
  13188. var box0 = this.boundingBox;
  13189. var box1 = boundingInfo.boundingBox;
  13190. if (!axisOverlap(box0.directions[0], box0, box1))
  13191. return false;
  13192. if (!axisOverlap(box0.directions[1], box0, box1))
  13193. return false;
  13194. if (!axisOverlap(box0.directions[2], box0, box1))
  13195. return false;
  13196. if (!axisOverlap(box1.directions[0], box0, box1))
  13197. return false;
  13198. if (!axisOverlap(box1.directions[1], box0, box1))
  13199. return false;
  13200. if (!axisOverlap(box1.directions[2], box0, box1))
  13201. return false;
  13202. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13203. return false;
  13204. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13205. return false;
  13206. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13207. return false;
  13208. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13209. return false;
  13210. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13211. return false;
  13212. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13213. return false;
  13214. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13215. return false;
  13216. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13217. return false;
  13218. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13219. return false;
  13220. return true;
  13221. };
  13222. return BoundingInfo;
  13223. }());
  13224. BABYLON.BoundingInfo = BoundingInfo;
  13225. })(BABYLON || (BABYLON = {}));
  13226. //# sourceMappingURL=babylon.boundingInfo.js.map
  13227. var BABYLON;
  13228. (function (BABYLON) {
  13229. var TransformNode = /** @class */ (function (_super) {
  13230. __extends(TransformNode, _super);
  13231. function TransformNode(name, scene, isPure) {
  13232. if (scene === void 0) { scene = null; }
  13233. if (isPure === void 0) { isPure = true; }
  13234. var _this = _super.call(this, name, scene) || this;
  13235. // Properties
  13236. _this._rotation = BABYLON.Vector3.Zero();
  13237. _this._scaling = BABYLON.Vector3.One();
  13238. _this._isDirty = false;
  13239. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13240. _this.scalingDeterminant = 1;
  13241. _this.infiniteDistance = false;
  13242. _this.position = BABYLON.Vector3.Zero();
  13243. _this._localWorld = BABYLON.Matrix.Zero();
  13244. _this._worldMatrix = BABYLON.Matrix.Zero();
  13245. _this._absolutePosition = BABYLON.Vector3.Zero();
  13246. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13247. _this._postMultiplyPivotMatrix = false;
  13248. _this._isWorldMatrixFrozen = false;
  13249. /**
  13250. * An event triggered after the world matrix is updated
  13251. * @type {BABYLON.Observable}
  13252. */
  13253. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13254. _this._nonUniformScaling = false;
  13255. if (isPure) {
  13256. _this.getScene().addTransformNode(_this);
  13257. }
  13258. return _this;
  13259. }
  13260. Object.defineProperty(TransformNode.prototype, "rotation", {
  13261. /**
  13262. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13263. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13264. * Default : (0.0, 0.0, 0.0)
  13265. */
  13266. get: function () {
  13267. return this._rotation;
  13268. },
  13269. set: function (newRotation) {
  13270. this._rotation = newRotation;
  13271. },
  13272. enumerable: true,
  13273. configurable: true
  13274. });
  13275. Object.defineProperty(TransformNode.prototype, "scaling", {
  13276. /**
  13277. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13278. * Default : (1.0, 1.0, 1.0)
  13279. */
  13280. get: function () {
  13281. return this._scaling;
  13282. },
  13283. /**
  13284. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13285. * Default : (1.0, 1.0, 1.0)
  13286. */
  13287. set: function (newScaling) {
  13288. this._scaling = newScaling;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13294. /**
  13295. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13296. * It's null by default.
  13297. * 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)
  13298. */
  13299. get: function () {
  13300. return this._rotationQuaternion;
  13301. },
  13302. set: function (quaternion) {
  13303. this._rotationQuaternion = quaternion;
  13304. //reset the rotation vector.
  13305. if (quaternion && this.rotation.length()) {
  13306. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13307. }
  13308. },
  13309. enumerable: true,
  13310. configurable: true
  13311. });
  13312. /**
  13313. * Returns the latest update of the World matrix
  13314. * Returns a Matrix.
  13315. */
  13316. TransformNode.prototype.getWorldMatrix = function () {
  13317. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13318. this.computeWorldMatrix();
  13319. }
  13320. return this._worldMatrix;
  13321. };
  13322. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13323. /**
  13324. * Returns directly the latest state of the mesh World matrix.
  13325. * A Matrix is returned.
  13326. */
  13327. get: function () {
  13328. return this._worldMatrix;
  13329. },
  13330. enumerable: true,
  13331. configurable: true
  13332. });
  13333. /**
  13334. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13335. * Returns the AbstractMesh.
  13336. */
  13337. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13338. this._poseMatrix.copyFrom(matrix);
  13339. return this;
  13340. };
  13341. /**
  13342. * Returns the mesh Pose matrix.
  13343. * Returned object : Matrix
  13344. */
  13345. TransformNode.prototype.getPoseMatrix = function () {
  13346. return this._poseMatrix;
  13347. };
  13348. TransformNode.prototype._isSynchronized = function () {
  13349. if (this._isDirty) {
  13350. return false;
  13351. }
  13352. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13353. return false;
  13354. if (this._cache.pivotMatrixUpdated) {
  13355. return false;
  13356. }
  13357. if (this.infiniteDistance) {
  13358. return false;
  13359. }
  13360. if (!this._cache.position.equals(this.position))
  13361. return false;
  13362. if (this.rotationQuaternion) {
  13363. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13364. return false;
  13365. }
  13366. if (!this._cache.rotation.equals(this.rotation))
  13367. return false;
  13368. if (!this._cache.scaling.equals(this.scaling))
  13369. return false;
  13370. return true;
  13371. };
  13372. TransformNode.prototype._initCache = function () {
  13373. _super.prototype._initCache.call(this);
  13374. this._cache.localMatrixUpdated = false;
  13375. this._cache.position = BABYLON.Vector3.Zero();
  13376. this._cache.scaling = BABYLON.Vector3.Zero();
  13377. this._cache.rotation = BABYLON.Vector3.Zero();
  13378. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13379. this._cache.billboardMode = -1;
  13380. };
  13381. TransformNode.prototype.markAsDirty = function (property) {
  13382. if (property === "rotation") {
  13383. this.rotationQuaternion = null;
  13384. }
  13385. this._currentRenderId = Number.MAX_VALUE;
  13386. this._isDirty = true;
  13387. return this;
  13388. };
  13389. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13390. /**
  13391. * Returns the current mesh absolute position.
  13392. * Retuns a Vector3.
  13393. */
  13394. get: function () {
  13395. return this._absolutePosition;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. /**
  13401. * Sets a new pivot matrix to the mesh.
  13402. * Returns the AbstractMesh.
  13403. */
  13404. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13405. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13406. this._pivotMatrix = matrix.clone();
  13407. this._cache.pivotMatrixUpdated = true;
  13408. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13409. if (this._postMultiplyPivotMatrix) {
  13410. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13411. }
  13412. return this;
  13413. };
  13414. /**
  13415. * Returns the mesh pivot matrix.
  13416. * Default : Identity.
  13417. * A Matrix is returned.
  13418. */
  13419. TransformNode.prototype.getPivotMatrix = function () {
  13420. return this._pivotMatrix;
  13421. };
  13422. /**
  13423. * Prevents the World matrix to be computed any longer.
  13424. * Returns the AbstractMesh.
  13425. */
  13426. TransformNode.prototype.freezeWorldMatrix = function () {
  13427. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13428. this.computeWorldMatrix(true);
  13429. this._isWorldMatrixFrozen = true;
  13430. return this;
  13431. };
  13432. /**
  13433. * Allows back the World matrix computation.
  13434. * Returns the AbstractMesh.
  13435. */
  13436. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13437. this._isWorldMatrixFrozen = false;
  13438. this.computeWorldMatrix(true);
  13439. return this;
  13440. };
  13441. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13442. /**
  13443. * True if the World matrix has been frozen.
  13444. * Returns a boolean.
  13445. */
  13446. get: function () {
  13447. return this._isWorldMatrixFrozen;
  13448. },
  13449. enumerable: true,
  13450. configurable: true
  13451. });
  13452. /**
  13453. * Retuns the mesh absolute position in the World.
  13454. * Returns a Vector3.
  13455. */
  13456. TransformNode.prototype.getAbsolutePosition = function () {
  13457. this.computeWorldMatrix();
  13458. return this._absolutePosition;
  13459. };
  13460. /**
  13461. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13462. * Returns the AbstractMesh.
  13463. */
  13464. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13465. if (!absolutePosition) {
  13466. return this;
  13467. }
  13468. var absolutePositionX;
  13469. var absolutePositionY;
  13470. var absolutePositionZ;
  13471. if (absolutePosition.x === undefined) {
  13472. if (arguments.length < 3) {
  13473. return this;
  13474. }
  13475. absolutePositionX = arguments[0];
  13476. absolutePositionY = arguments[1];
  13477. absolutePositionZ = arguments[2];
  13478. }
  13479. else {
  13480. absolutePositionX = absolutePosition.x;
  13481. absolutePositionY = absolutePosition.y;
  13482. absolutePositionZ = absolutePosition.z;
  13483. }
  13484. if (this.parent) {
  13485. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13486. invertParentWorldMatrix.invert();
  13487. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13488. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13489. }
  13490. else {
  13491. this.position.x = absolutePositionX;
  13492. this.position.y = absolutePositionY;
  13493. this.position.z = absolutePositionZ;
  13494. }
  13495. return this;
  13496. };
  13497. /**
  13498. * Sets the mesh position in its local space.
  13499. * Returns the AbstractMesh.
  13500. */
  13501. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13502. this.computeWorldMatrix();
  13503. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13504. return this;
  13505. };
  13506. /**
  13507. * Returns the mesh position in the local space from the current World matrix values.
  13508. * Returns a new Vector3.
  13509. */
  13510. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13511. this.computeWorldMatrix();
  13512. var invLocalWorldMatrix = this._localWorld.clone();
  13513. invLocalWorldMatrix.invert();
  13514. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13515. };
  13516. /**
  13517. * Translates the mesh along the passed Vector3 in its local space.
  13518. * Returns the AbstractMesh.
  13519. */
  13520. TransformNode.prototype.locallyTranslate = function (vector3) {
  13521. this.computeWorldMatrix(true);
  13522. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13523. return this;
  13524. };
  13525. /**
  13526. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13527. * @param targetPoint the position (must be in same space as current mesh) to look at
  13528. * @param yawCor optional yaw (y-axis) correction in radians
  13529. * @param pitchCor optional pitch (x-axis) correction in radians
  13530. * @param rollCor optional roll (z-axis) correction in radians
  13531. * @param space the choosen space of the target
  13532. * @returns the TransformNode.
  13533. */
  13534. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13535. if (yawCor === void 0) { yawCor = 0; }
  13536. if (pitchCor === void 0) { pitchCor = 0; }
  13537. if (rollCor === void 0) { rollCor = 0; }
  13538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13539. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13540. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13541. targetPoint.subtractToRef(pos, dv);
  13542. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13543. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13544. var pitch = Math.atan2(dv.y, len);
  13545. if (this.rotationQuaternion) {
  13546. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13547. }
  13548. else {
  13549. this.rotation.x = pitch + pitchCor;
  13550. this.rotation.y = yaw + yawCor;
  13551. this.rotation.z = rollCor;
  13552. }
  13553. return this;
  13554. };
  13555. /**
  13556. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13557. * This Vector3 is expressed in the World space.
  13558. */
  13559. TransformNode.prototype.getDirection = function (localAxis) {
  13560. var result = BABYLON.Vector3.Zero();
  13561. this.getDirectionToRef(localAxis, result);
  13562. return result;
  13563. };
  13564. /**
  13565. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13566. * localAxis is expressed in the mesh local space.
  13567. * result is computed in the Wordl space from the mesh World matrix.
  13568. * Returns the AbstractMesh.
  13569. */
  13570. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13571. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13572. return this;
  13573. };
  13574. TransformNode.prototype.setPivotPoint = function (point, space) {
  13575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13576. if (this.getScene().getRenderId() == 0) {
  13577. this.computeWorldMatrix(true);
  13578. }
  13579. var wm = this.getWorldMatrix();
  13580. if (space == BABYLON.Space.WORLD) {
  13581. var tmat = BABYLON.Tmp.Matrix[0];
  13582. wm.invertToRef(tmat);
  13583. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13584. }
  13585. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13586. this._pivotMatrix.m[12] = -point.x;
  13587. this._pivotMatrix.m[13] = -point.y;
  13588. this._pivotMatrix.m[14] = -point.z;
  13589. this._cache.pivotMatrixUpdated = true;
  13590. return this;
  13591. };
  13592. /**
  13593. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13594. */
  13595. TransformNode.prototype.getPivotPoint = function () {
  13596. var point = BABYLON.Vector3.Zero();
  13597. this.getPivotPointToRef(point);
  13598. return point;
  13599. };
  13600. /**
  13601. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13602. * Returns the AbstractMesh.
  13603. */
  13604. TransformNode.prototype.getPivotPointToRef = function (result) {
  13605. result.x = -this._pivotMatrix.m[12];
  13606. result.y = -this._pivotMatrix.m[13];
  13607. result.z = -this._pivotMatrix.m[14];
  13608. return this;
  13609. };
  13610. /**
  13611. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13612. */
  13613. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13614. var point = BABYLON.Vector3.Zero();
  13615. this.getAbsolutePivotPointToRef(point);
  13616. return point;
  13617. };
  13618. /**
  13619. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13620. * Returns the AbstractMesh.
  13621. */
  13622. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13623. result.x = this._pivotMatrix.m[12];
  13624. result.y = this._pivotMatrix.m[13];
  13625. result.z = this._pivotMatrix.m[14];
  13626. this.getPivotPointToRef(result);
  13627. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13628. return this;
  13629. };
  13630. /**
  13631. * Defines the passed node as the parent of the current node.
  13632. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13633. * Returns the TransformNode.
  13634. */
  13635. TransformNode.prototype.setParent = function (node) {
  13636. if (node == null) {
  13637. var rotation = BABYLON.Tmp.Quaternion[0];
  13638. var position = BABYLON.Tmp.Vector3[0];
  13639. var scale = BABYLON.Tmp.Vector3[1];
  13640. if (this.parent && this.parent.computeWorldMatrix) {
  13641. this.parent.computeWorldMatrix(true);
  13642. }
  13643. this.computeWorldMatrix(true);
  13644. this.getWorldMatrix().decompose(scale, rotation, position);
  13645. if (this.rotationQuaternion) {
  13646. this.rotationQuaternion.copyFrom(rotation);
  13647. }
  13648. else {
  13649. rotation.toEulerAnglesToRef(this.rotation);
  13650. }
  13651. this.scaling.x = scale.x;
  13652. this.scaling.y = scale.y;
  13653. this.scaling.z = scale.z;
  13654. this.position.x = position.x;
  13655. this.position.y = position.y;
  13656. this.position.z = position.z;
  13657. }
  13658. else {
  13659. var rotation = BABYLON.Tmp.Quaternion[0];
  13660. var position = BABYLON.Tmp.Vector3[0];
  13661. var scale = BABYLON.Tmp.Vector3[1];
  13662. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13663. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13664. this.computeWorldMatrix(true);
  13665. node.computeWorldMatrix(true);
  13666. node.getWorldMatrix().invertToRef(invParentMatrix);
  13667. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13668. diffMatrix.decompose(scale, rotation, position);
  13669. if (this.rotationQuaternion) {
  13670. this.rotationQuaternion.copyFrom(rotation);
  13671. }
  13672. else {
  13673. rotation.toEulerAnglesToRef(this.rotation);
  13674. }
  13675. this.position.x = position.x;
  13676. this.position.y = position.y;
  13677. this.position.z = position.z;
  13678. this.scaling.x = scale.x;
  13679. this.scaling.y = scale.y;
  13680. this.scaling.z = scale.z;
  13681. }
  13682. this.parent = node;
  13683. return this;
  13684. };
  13685. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13686. get: function () {
  13687. return this._nonUniformScaling;
  13688. },
  13689. enumerable: true,
  13690. configurable: true
  13691. });
  13692. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13693. if (this._nonUniformScaling === value) {
  13694. return false;
  13695. }
  13696. this._nonUniformScaling = true;
  13697. return true;
  13698. };
  13699. /**
  13700. * Attach the current TransformNode to another TransformNode associated with a bone
  13701. * @param bone Bone affecting the TransformNode
  13702. * @param affectedTransformNode TransformNode associated with the bone
  13703. */
  13704. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13705. this._transformToBoneReferal = affectedTransformNode;
  13706. this.parent = bone;
  13707. if (bone.getWorldMatrix().determinant() < 0) {
  13708. this.scalingDeterminant *= -1;
  13709. }
  13710. return this;
  13711. };
  13712. TransformNode.prototype.detachFromBone = function () {
  13713. if (!this.parent) {
  13714. return this;
  13715. }
  13716. if (this.parent.getWorldMatrix().determinant() < 0) {
  13717. this.scalingDeterminant *= -1;
  13718. }
  13719. this._transformToBoneReferal = null;
  13720. this.parent = null;
  13721. return this;
  13722. };
  13723. /**
  13724. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13725. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13726. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13727. * The passed axis is also normalized.
  13728. * Returns the AbstractMesh.
  13729. */
  13730. TransformNode.prototype.rotate = function (axis, amount, space) {
  13731. axis.normalize();
  13732. if (!this.rotationQuaternion) {
  13733. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13734. this.rotation = BABYLON.Vector3.Zero();
  13735. }
  13736. var rotationQuaternion;
  13737. if (!space || space === BABYLON.Space.LOCAL) {
  13738. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13739. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13740. }
  13741. else {
  13742. if (this.parent) {
  13743. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13744. invertParentWorldMatrix.invert();
  13745. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13746. }
  13747. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13748. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13749. }
  13750. return this;
  13751. };
  13752. /**
  13753. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13754. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13755. * The passed axis is also normalized.
  13756. * Returns the AbstractMesh.
  13757. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13758. */
  13759. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13760. axis.normalize();
  13761. if (!this.rotationQuaternion) {
  13762. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13763. this.rotation.copyFromFloats(0, 0, 0);
  13764. }
  13765. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13766. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13767. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13768. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13769. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13770. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13771. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13772. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13773. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13774. return this;
  13775. };
  13776. /**
  13777. * Translates the mesh along the axis vector for the passed distance in the given space.
  13778. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13779. * Returns the AbstractMesh.
  13780. */
  13781. TransformNode.prototype.translate = function (axis, distance, space) {
  13782. var displacementVector = axis.scale(distance);
  13783. if (!space || space === BABYLON.Space.LOCAL) {
  13784. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13785. this.setPositionWithLocalVector(tempV3);
  13786. }
  13787. else {
  13788. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13789. }
  13790. return this;
  13791. };
  13792. /**
  13793. * Adds a rotation step to the mesh current rotation.
  13794. * x, y, z are Euler angles expressed in radians.
  13795. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13796. * This means this rotation is made in the mesh local space only.
  13797. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13798. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13799. * ```javascript
  13800. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13801. * ```
  13802. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13803. * 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.
  13804. * Returns the AbstractMesh.
  13805. */
  13806. TransformNode.prototype.addRotation = function (x, y, z) {
  13807. var rotationQuaternion;
  13808. if (this.rotationQuaternion) {
  13809. rotationQuaternion = this.rotationQuaternion;
  13810. }
  13811. else {
  13812. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13813. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13814. }
  13815. var accumulation = BABYLON.Tmp.Quaternion[0];
  13816. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13817. rotationQuaternion.multiplyInPlace(accumulation);
  13818. if (!this.rotationQuaternion) {
  13819. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13820. }
  13821. return this;
  13822. };
  13823. /**
  13824. * Computes the mesh World matrix and returns it.
  13825. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13826. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13827. * If the parameter `force`is set to `true`, the actual computation is done.
  13828. * Returns the mesh World Matrix.
  13829. */
  13830. TransformNode.prototype.computeWorldMatrix = function (force) {
  13831. if (this._isWorldMatrixFrozen) {
  13832. return this._worldMatrix;
  13833. }
  13834. if (!force && this.isSynchronized(true)) {
  13835. return this._worldMatrix;
  13836. }
  13837. this._cache.position.copyFrom(this.position);
  13838. this._cache.scaling.copyFrom(this.scaling);
  13839. this._cache.pivotMatrixUpdated = false;
  13840. this._cache.billboardMode = this.billboardMode;
  13841. this._currentRenderId = this.getScene().getRenderId();
  13842. this._isDirty = false;
  13843. // Scaling
  13844. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13845. // Rotation
  13846. //rotate, if quaternion is set and rotation was used
  13847. if (this.rotationQuaternion) {
  13848. var len = this.rotation.length();
  13849. if (len) {
  13850. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13851. this.rotation.copyFromFloats(0, 0, 0);
  13852. }
  13853. }
  13854. if (this.rotationQuaternion) {
  13855. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13857. }
  13858. else {
  13859. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13860. this._cache.rotation.copyFrom(this.rotation);
  13861. }
  13862. // Translation
  13863. var camera = this.getScene().activeCamera;
  13864. if (this.infiniteDistance && !this.parent && camera) {
  13865. var cameraWorldMatrix = camera.getWorldMatrix();
  13866. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13867. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13868. }
  13869. else {
  13870. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13871. }
  13872. // Composing transformations
  13873. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13874. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13875. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13876. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13877. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13878. // Need to decompose each rotation here
  13879. var currentPosition = BABYLON.Tmp.Vector3[3];
  13880. if (this.parent && this.parent.getWorldMatrix) {
  13881. if (this._transformToBoneReferal) {
  13882. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13883. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13884. }
  13885. else {
  13886. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13887. }
  13888. }
  13889. else {
  13890. currentPosition.copyFrom(this.position);
  13891. }
  13892. currentPosition.subtractInPlace(camera.globalPosition);
  13893. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13894. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13895. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13896. }
  13897. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13898. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13899. }
  13900. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13901. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13902. }
  13903. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13904. }
  13905. else {
  13906. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13907. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13908. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13909. }
  13910. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13911. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13912. }
  13913. // Local world
  13914. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13915. // Parent
  13916. if (this.parent && this.parent.getWorldMatrix) {
  13917. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13918. if (this._transformToBoneReferal) {
  13919. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13920. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13921. }
  13922. else {
  13923. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13924. }
  13925. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13926. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13927. this._worldMatrix.copyFrom(this._localWorld);
  13928. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13929. }
  13930. else {
  13931. if (this._transformToBoneReferal) {
  13932. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13933. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13934. }
  13935. else {
  13936. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13937. }
  13938. }
  13939. this._markSyncedWithParent();
  13940. }
  13941. else {
  13942. this._worldMatrix.copyFrom(this._localWorld);
  13943. }
  13944. // Post multiply inverse of pivotMatrix
  13945. if (this._postMultiplyPivotMatrix) {
  13946. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13947. }
  13948. // Normal matrix
  13949. if (this.scaling.isNonUniform) {
  13950. this._updateNonUniformScalingState(true);
  13951. }
  13952. else if (this.parent && this.parent._nonUniformScaling) {
  13953. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13954. }
  13955. else {
  13956. this._updateNonUniformScalingState(false);
  13957. }
  13958. this._afterComputeWorldMatrix();
  13959. // Absolute position
  13960. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13961. // Callbacks
  13962. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13963. if (!this._poseMatrix) {
  13964. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13965. }
  13966. return this._worldMatrix;
  13967. };
  13968. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13969. };
  13970. /**
  13971. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13972. * @param func: callback function to add
  13973. *
  13974. * Returns the TransformNode.
  13975. */
  13976. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13977. this.onAfterWorldMatrixUpdateObservable.add(func);
  13978. return this;
  13979. };
  13980. /**
  13981. * Removes a registered callback function.
  13982. * Returns the TransformNode.
  13983. */
  13984. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13985. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13986. return this;
  13987. };
  13988. /**
  13989. * Clone the current transform node
  13990. * Returns the new transform node
  13991. * @param name Name of the new clone
  13992. * @param newParent New parent for the clone
  13993. * @param doNotCloneChildren Do not clone children hierarchy
  13994. */
  13995. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13996. var _this = this;
  13997. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13998. result.name = name;
  13999. result.id = name;
  14000. if (newParent) {
  14001. result.parent = newParent;
  14002. }
  14003. if (!doNotCloneChildren) {
  14004. // Children
  14005. var directDescendants = this.getDescendants(true);
  14006. for (var index = 0; index < directDescendants.length; index++) {
  14007. var child = directDescendants[index];
  14008. if (child.clone) {
  14009. child.clone(name + "." + child.name, result);
  14010. }
  14011. }
  14012. }
  14013. return result;
  14014. };
  14015. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14016. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14017. serializationObject.type = this.getClassName();
  14018. // Parent
  14019. if (this.parent) {
  14020. serializationObject.parentId = this.parent.id;
  14021. }
  14022. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14023. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14024. }
  14025. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14026. serializationObject.isEnabled = this.isEnabled();
  14027. // Parent
  14028. if (this.parent) {
  14029. serializationObject.parentId = this.parent.id;
  14030. }
  14031. return serializationObject;
  14032. };
  14033. // Statics
  14034. /**
  14035. * Returns a new TransformNode object parsed from the source provided.
  14036. * The parameter `parsedMesh` is the source.
  14037. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14038. */
  14039. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14040. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14041. if (BABYLON.Tags) {
  14042. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14043. }
  14044. if (parsedTransformNode.localMatrix) {
  14045. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14046. }
  14047. else if (parsedTransformNode.pivotMatrix) {
  14048. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14049. }
  14050. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14051. // Parent
  14052. if (parsedTransformNode.parentId) {
  14053. transformNode._waitingParentId = parsedTransformNode.parentId;
  14054. }
  14055. return transformNode;
  14056. };
  14057. /**
  14058. * Disposes the TransformNode.
  14059. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14060. * Returns nothing.
  14061. */
  14062. TransformNode.prototype.dispose = function (doNotRecurse) {
  14063. // Animations
  14064. this.getScene().stopAnimation(this);
  14065. // Remove from scene
  14066. this.getScene().removeTransformNode(this);
  14067. this._cache = {};
  14068. if (!doNotRecurse) {
  14069. // Children
  14070. var objects = this.getDescendants(true);
  14071. for (var index = 0; index < objects.length; index++) {
  14072. objects[index].dispose();
  14073. }
  14074. }
  14075. else {
  14076. var childMeshes = this.getChildMeshes(true);
  14077. for (index = 0; index < childMeshes.length; index++) {
  14078. var child = childMeshes[index];
  14079. child.parent = null;
  14080. child.computeWorldMatrix(true);
  14081. }
  14082. }
  14083. this.onAfterWorldMatrixUpdateObservable.clear();
  14084. _super.prototype.dispose.call(this);
  14085. };
  14086. // Statics
  14087. TransformNode.BILLBOARDMODE_NONE = 0;
  14088. TransformNode.BILLBOARDMODE_X = 1;
  14089. TransformNode.BILLBOARDMODE_Y = 2;
  14090. TransformNode.BILLBOARDMODE_Z = 4;
  14091. TransformNode.BILLBOARDMODE_ALL = 7;
  14092. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14093. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14094. __decorate([
  14095. BABYLON.serializeAsVector3()
  14096. ], TransformNode.prototype, "_rotation", void 0);
  14097. __decorate([
  14098. BABYLON.serializeAsQuaternion()
  14099. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14100. __decorate([
  14101. BABYLON.serializeAsVector3()
  14102. ], TransformNode.prototype, "_scaling", void 0);
  14103. __decorate([
  14104. BABYLON.serialize()
  14105. ], TransformNode.prototype, "billboardMode", void 0);
  14106. __decorate([
  14107. BABYLON.serialize()
  14108. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14109. __decorate([
  14110. BABYLON.serialize()
  14111. ], TransformNode.prototype, "infiniteDistance", void 0);
  14112. __decorate([
  14113. BABYLON.serializeAsVector3()
  14114. ], TransformNode.prototype, "position", void 0);
  14115. return TransformNode;
  14116. }(BABYLON.Node));
  14117. BABYLON.TransformNode = TransformNode;
  14118. })(BABYLON || (BABYLON = {}));
  14119. //# sourceMappingURL=babylon.transformNode.js.map
  14120. var BABYLON;
  14121. (function (BABYLON) {
  14122. var AbstractMesh = /** @class */ (function (_super) {
  14123. __extends(AbstractMesh, _super);
  14124. // Constructor
  14125. function AbstractMesh(name, scene) {
  14126. if (scene === void 0) { scene = null; }
  14127. var _this = _super.call(this, name, scene, false) || this;
  14128. _this._facetNb = 0; // facet number
  14129. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14130. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14131. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14132. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14133. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14134. _this._subDiv = {
  14135. max: 1,
  14136. X: 1,
  14137. Y: 1,
  14138. Z: 1
  14139. };
  14140. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14141. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14142. // Events
  14143. /**
  14144. * An event triggered when this mesh collides with another one
  14145. * @type {BABYLON.Observable}
  14146. */
  14147. _this.onCollideObservable = new BABYLON.Observable();
  14148. /**
  14149. * An event triggered when the collision's position changes
  14150. * @type {BABYLON.Observable}
  14151. */
  14152. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14153. /**
  14154. * An event triggered when material is changed
  14155. * @type {BABYLON.Observable}
  14156. */
  14157. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14158. // Properties
  14159. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14160. /**
  14161. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14162. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14163. * or
  14164. * 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.
  14165. * for more info check WebGl documentations
  14166. */
  14167. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14168. /**
  14169. * 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:
  14170. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14171. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14172. * 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.
  14173. */
  14174. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14175. /**
  14176. * 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.
  14177. * The default value is -1 which means don't break the query and wait till the result.
  14178. */
  14179. _this.occlusionRetryCount = -1;
  14180. _this._occlusionInternalRetryCounter = 0;
  14181. _this._isOccluded = false;
  14182. _this._isOcclusionQueryInProgress = false;
  14183. _this.visibility = 1.0;
  14184. _this.alphaIndex = Number.MAX_VALUE;
  14185. _this.isVisible = true;
  14186. _this.isPickable = true;
  14187. _this.showBoundingBox = false;
  14188. _this.showSubMeshesBoundingBox = false;
  14189. _this.isBlocker = false;
  14190. _this.enablePointerMoveEvents = false;
  14191. _this.renderingGroupId = 0;
  14192. _this._receiveShadows = false;
  14193. _this.renderOutline = false;
  14194. _this.outlineColor = BABYLON.Color3.Red();
  14195. _this.outlineWidth = 0.02;
  14196. _this.renderOverlay = false;
  14197. _this.overlayColor = BABYLON.Color3.Red();
  14198. _this.overlayAlpha = 0.5;
  14199. _this._hasVertexAlpha = false;
  14200. _this._useVertexColors = true;
  14201. _this._computeBonesUsingShaders = true;
  14202. _this._numBoneInfluencers = 4;
  14203. _this._applyFog = true;
  14204. _this.useOctreeForRenderingSelection = true;
  14205. _this.useOctreeForPicking = true;
  14206. _this.useOctreeForCollisions = true;
  14207. _this._layerMask = 0x0FFFFFFF;
  14208. /**
  14209. * True if the mesh must be rendered in any case.
  14210. */
  14211. _this.alwaysSelectAsActiveMesh = false;
  14212. /**
  14213. * This scene's action manager
  14214. * @type {BABYLON.ActionManager}
  14215. */
  14216. _this.actionManager = null;
  14217. // Physics
  14218. _this.physicsImpostor = null;
  14219. // Collisions
  14220. _this._checkCollisions = false;
  14221. _this._collisionMask = -1;
  14222. _this._collisionGroup = -1;
  14223. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14224. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14225. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14226. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14227. // Edges
  14228. _this.edgesWidth = 1;
  14229. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14230. // Cache
  14231. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14232. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14233. _this._isDisposed = false;
  14234. _this._renderId = 0;
  14235. _this._intersectionsInProgress = new Array();
  14236. _this._unIndexed = false;
  14237. _this._lightSources = new Array();
  14238. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14239. if (collidedMesh === void 0) { collidedMesh = null; }
  14240. //TODO move this to the collision coordinator!
  14241. if (_this.getScene().workerCollisions)
  14242. newPosition.multiplyInPlace(_this._collider._radius);
  14243. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14244. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14245. _this.position.addInPlace(_this._diffPositionForCollisions);
  14246. }
  14247. if (collidedMesh) {
  14248. _this.onCollideObservable.notifyObservers(collidedMesh);
  14249. }
  14250. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14251. };
  14252. _this.getScene().addMesh(_this);
  14253. _this._resyncLightSources();
  14254. return _this;
  14255. }
  14256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14257. get: function () {
  14258. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14264. get: function () {
  14265. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14271. get: function () {
  14272. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14278. get: function () {
  14279. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14285. get: function () {
  14286. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14292. /**
  14293. * Read-only : the number of facets in the mesh
  14294. */
  14295. get: function () {
  14296. return this._facetNb;
  14297. },
  14298. enumerable: true,
  14299. configurable: true
  14300. });
  14301. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14302. /**
  14303. * The number (integer) of subdivisions per axis in the partioning space
  14304. */
  14305. get: function () {
  14306. return this._partitioningSubdivisions;
  14307. },
  14308. set: function (nb) {
  14309. this._partitioningSubdivisions = nb;
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14315. /**
  14316. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14317. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14318. */
  14319. get: function () {
  14320. return this._partitioningBBoxRatio;
  14321. },
  14322. set: function (ratio) {
  14323. this._partitioningBBoxRatio = ratio;
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14329. /**
  14330. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14331. * Works only for updatable meshes.
  14332. * Doesn't work with multi-materials.
  14333. */
  14334. get: function () {
  14335. return this._facetDepthSort;
  14336. },
  14337. set: function (sort) {
  14338. this._facetDepthSort = sort;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14344. /**
  14345. * The location (Vector3) where the facet depth sort must be computed from.
  14346. * By default, the active camera position.
  14347. * Used only when facet depth sort is enabled.
  14348. */
  14349. get: function () {
  14350. return this._facetDepthSortFrom;
  14351. },
  14352. set: function (location) {
  14353. this._facetDepthSortFrom = location;
  14354. },
  14355. enumerable: true,
  14356. configurable: true
  14357. });
  14358. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14359. /**
  14360. * Read-only boolean : is the feature facetData enabled ?
  14361. */
  14362. get: function () {
  14363. return this._facetDataEnabled;
  14364. },
  14365. enumerable: true,
  14366. configurable: true
  14367. });
  14368. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14369. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14370. return false;
  14371. }
  14372. this._markSubMeshesAsMiscDirty();
  14373. return true;
  14374. };
  14375. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14376. set: function (callback) {
  14377. if (this._onCollideObserver) {
  14378. this.onCollideObservable.remove(this._onCollideObserver);
  14379. }
  14380. this._onCollideObserver = this.onCollideObservable.add(callback);
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14386. set: function (callback) {
  14387. if (this._onCollisionPositionChangeObserver) {
  14388. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14389. }
  14390. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14396. /**
  14397. * 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.
  14398. */
  14399. get: function () {
  14400. return this._isOccluded;
  14401. },
  14402. set: function (value) {
  14403. this._isOccluded = value;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14409. /**
  14410. * Flag to check the progress status of the query
  14411. */
  14412. get: function () {
  14413. return this._isOcclusionQueryInProgress;
  14414. },
  14415. enumerable: true,
  14416. configurable: true
  14417. });
  14418. Object.defineProperty(AbstractMesh.prototype, "material", {
  14419. get: function () {
  14420. return this._material;
  14421. },
  14422. set: function (value) {
  14423. if (this._material === value) {
  14424. return;
  14425. }
  14426. this._material = value;
  14427. if (this.onMaterialChangedObservable.hasObservers) {
  14428. this.onMaterialChangedObservable.notifyObservers(this);
  14429. }
  14430. if (!this.subMeshes) {
  14431. return;
  14432. }
  14433. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14434. var subMesh = _a[_i];
  14435. subMesh.setEffect(null);
  14436. }
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14442. get: function () {
  14443. return this._receiveShadows;
  14444. },
  14445. set: function (value) {
  14446. if (this._receiveShadows === value) {
  14447. return;
  14448. }
  14449. this._receiveShadows = value;
  14450. this._markSubMeshesAsLightDirty();
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14456. get: function () {
  14457. return this._hasVertexAlpha;
  14458. },
  14459. set: function (value) {
  14460. if (this._hasVertexAlpha === value) {
  14461. return;
  14462. }
  14463. this._hasVertexAlpha = value;
  14464. this._markSubMeshesAsAttributesDirty();
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14470. get: function () {
  14471. return this._useVertexColors;
  14472. },
  14473. set: function (value) {
  14474. if (this._useVertexColors === value) {
  14475. return;
  14476. }
  14477. this._useVertexColors = value;
  14478. this._markSubMeshesAsAttributesDirty();
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14484. get: function () {
  14485. return this._computeBonesUsingShaders;
  14486. },
  14487. set: function (value) {
  14488. if (this._computeBonesUsingShaders === value) {
  14489. return;
  14490. }
  14491. this._computeBonesUsingShaders = value;
  14492. this._markSubMeshesAsAttributesDirty();
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14498. get: function () {
  14499. return this._numBoneInfluencers;
  14500. },
  14501. set: function (value) {
  14502. if (this._numBoneInfluencers === value) {
  14503. return;
  14504. }
  14505. this._numBoneInfluencers = value;
  14506. this._markSubMeshesAsAttributesDirty();
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14512. get: function () {
  14513. return this._applyFog;
  14514. },
  14515. set: function (value) {
  14516. if (this._applyFog === value) {
  14517. return;
  14518. }
  14519. this._applyFog = value;
  14520. this._markSubMeshesAsMiscDirty();
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14526. get: function () {
  14527. return this._layerMask;
  14528. },
  14529. set: function (value) {
  14530. if (value === this._layerMask) {
  14531. return;
  14532. }
  14533. this._layerMask = value;
  14534. this._resyncLightSources();
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14540. get: function () {
  14541. return this._collisionMask;
  14542. },
  14543. set: function (mask) {
  14544. this._collisionMask = !isNaN(mask) ? mask : -1;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14550. get: function () {
  14551. return this._collisionGroup;
  14552. },
  14553. set: function (mask) {
  14554. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14555. },
  14556. enumerable: true,
  14557. configurable: true
  14558. });
  14559. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14560. get: function () {
  14561. return null;
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14567. get: function () {
  14568. return this._skeleton;
  14569. },
  14570. set: function (value) {
  14571. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14572. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14573. }
  14574. if (value && value.needInitialSkinMatrix) {
  14575. value._registerMeshWithPoseMatrix(this);
  14576. }
  14577. this._skeleton = value;
  14578. if (!this._skeleton) {
  14579. this._bonesTransformMatrices = null;
  14580. }
  14581. this._markSubMeshesAsAttributesDirty();
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. /**
  14587. * Boolean : true if the mesh has been disposed.
  14588. */
  14589. AbstractMesh.prototype.isDisposed = function () {
  14590. return this._isDisposed;
  14591. };
  14592. /**
  14593. * Returns the string "AbstractMesh"
  14594. */
  14595. AbstractMesh.prototype.getClassName = function () {
  14596. return "AbstractMesh";
  14597. };
  14598. /**
  14599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14600. */
  14601. AbstractMesh.prototype.toString = function (fullDetails) {
  14602. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14603. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14604. if (this._skeleton) {
  14605. ret += ", skeleton: " + this._skeleton.name;
  14606. }
  14607. if (fullDetails) {
  14608. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14609. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14610. }
  14611. return ret;
  14612. };
  14613. AbstractMesh.prototype._rebuild = function () {
  14614. if (this._occlusionQuery) {
  14615. this._occlusionQuery = null;
  14616. }
  14617. if (this._edgesRenderer) {
  14618. this._edgesRenderer._rebuild();
  14619. }
  14620. if (!this.subMeshes) {
  14621. return;
  14622. }
  14623. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14624. var subMesh = _a[_i];
  14625. subMesh._rebuild();
  14626. }
  14627. };
  14628. AbstractMesh.prototype._resyncLightSources = function () {
  14629. this._lightSources.length = 0;
  14630. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14631. var light = _a[_i];
  14632. if (!light.isEnabled()) {
  14633. continue;
  14634. }
  14635. if (light.canAffectMesh(this)) {
  14636. this._lightSources.push(light);
  14637. }
  14638. }
  14639. this._markSubMeshesAsLightDirty();
  14640. };
  14641. AbstractMesh.prototype._resyncLighSource = function (light) {
  14642. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14643. var index = this._lightSources.indexOf(light);
  14644. if (index === -1) {
  14645. if (!isIn) {
  14646. return;
  14647. }
  14648. this._lightSources.push(light);
  14649. }
  14650. else {
  14651. if (isIn) {
  14652. return;
  14653. }
  14654. this._lightSources.splice(index, 1);
  14655. }
  14656. this._markSubMeshesAsLightDirty();
  14657. };
  14658. AbstractMesh.prototype._removeLightSource = function (light) {
  14659. var index = this._lightSources.indexOf(light);
  14660. if (index === -1) {
  14661. return;
  14662. }
  14663. this._lightSources.splice(index, 1);
  14664. };
  14665. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14666. if (!this.subMeshes) {
  14667. return;
  14668. }
  14669. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14670. var subMesh = _a[_i];
  14671. if (subMesh._materialDefines) {
  14672. func(subMesh._materialDefines);
  14673. }
  14674. }
  14675. };
  14676. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14677. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14678. };
  14679. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14680. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14681. };
  14682. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14683. if (!this.subMeshes) {
  14684. return;
  14685. }
  14686. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14687. var subMesh = _a[_i];
  14688. var material = subMesh.getMaterial();
  14689. if (material) {
  14690. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14691. }
  14692. }
  14693. };
  14694. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14695. /**
  14696. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14697. * Default : (1.0, 1.0, 1.0)
  14698. */
  14699. get: function () {
  14700. return this._scaling;
  14701. },
  14702. /**
  14703. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14704. * Default : (1.0, 1.0, 1.0)
  14705. */
  14706. set: function (newScaling) {
  14707. this._scaling = newScaling;
  14708. if (this.physicsImpostor) {
  14709. this.physicsImpostor.forceUpdate();
  14710. }
  14711. },
  14712. enumerable: true,
  14713. configurable: true
  14714. });
  14715. // Methods
  14716. /**
  14717. * Disables the mesh edger rendering mode.
  14718. * Returns the AbstractMesh.
  14719. */
  14720. AbstractMesh.prototype.disableEdgesRendering = function () {
  14721. if (this._edgesRenderer) {
  14722. this._edgesRenderer.dispose();
  14723. this._edgesRenderer = null;
  14724. }
  14725. return this;
  14726. };
  14727. /**
  14728. * Enables the edge rendering mode on the mesh.
  14729. * This mode makes the mesh edges visible.
  14730. * Returns the AbstractMesh.
  14731. */
  14732. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14733. if (epsilon === void 0) { epsilon = 0.95; }
  14734. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14735. this.disableEdgesRendering();
  14736. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14737. return this;
  14738. };
  14739. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14740. /**
  14741. * Returns true if the mesh is blocked. Used by the class Mesh.
  14742. * Returns the boolean `false` by default.
  14743. */
  14744. get: function () {
  14745. return false;
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. /**
  14751. * Returns the mesh itself by default, used by the class Mesh.
  14752. * Returned type : AbstractMesh
  14753. */
  14754. AbstractMesh.prototype.getLOD = function (camera) {
  14755. return this;
  14756. };
  14757. /**
  14758. * Returns 0 by default, used by the class Mesh.
  14759. * Returns an integer.
  14760. */
  14761. AbstractMesh.prototype.getTotalVertices = function () {
  14762. return 0;
  14763. };
  14764. /**
  14765. * Returns null by default, used by the class Mesh.
  14766. * Returned type : integer array
  14767. */
  14768. AbstractMesh.prototype.getIndices = function () {
  14769. return null;
  14770. };
  14771. /**
  14772. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14773. * Returned type : float array or Float32Array
  14774. */
  14775. AbstractMesh.prototype.getVerticesData = function (kind) {
  14776. return null;
  14777. };
  14778. /**
  14779. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14780. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14781. * The `data` are either a numeric array either a Float32Array.
  14782. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14783. * 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).
  14784. * Note that a new underlying VertexBuffer object is created each call.
  14785. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14786. *
  14787. * Possible `kind` values :
  14788. * - BABYLON.VertexBuffer.PositionKind
  14789. * - BABYLON.VertexBuffer.UVKind
  14790. * - BABYLON.VertexBuffer.UV2Kind
  14791. * - BABYLON.VertexBuffer.UV3Kind
  14792. * - BABYLON.VertexBuffer.UV4Kind
  14793. * - BABYLON.VertexBuffer.UV5Kind
  14794. * - BABYLON.VertexBuffer.UV6Kind
  14795. * - BABYLON.VertexBuffer.ColorKind
  14796. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14797. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14798. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14799. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14800. *
  14801. * Returns the Mesh.
  14802. */
  14803. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14804. return this;
  14805. };
  14806. /**
  14807. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14808. * If the mesh has no geometry, it is simply returned as it is.
  14809. * The `data` are either a numeric array either a Float32Array.
  14810. * No new underlying VertexBuffer object is created.
  14811. * 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.
  14812. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14813. *
  14814. * Possible `kind` values :
  14815. * - BABYLON.VertexBuffer.PositionKind
  14816. * - BABYLON.VertexBuffer.UVKind
  14817. * - BABYLON.VertexBuffer.UV2Kind
  14818. * - BABYLON.VertexBuffer.UV3Kind
  14819. * - BABYLON.VertexBuffer.UV4Kind
  14820. * - BABYLON.VertexBuffer.UV5Kind
  14821. * - BABYLON.VertexBuffer.UV6Kind
  14822. * - BABYLON.VertexBuffer.ColorKind
  14823. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14824. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14825. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14826. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14827. *
  14828. * Returns the Mesh.
  14829. */
  14830. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14831. return this;
  14832. };
  14833. /**
  14834. * Sets the mesh indices.
  14835. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14836. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14837. * This method creates a new index buffer each call.
  14838. * Returns the Mesh.
  14839. */
  14840. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14841. return this;
  14842. };
  14843. /** Returns false by default, used by the class Mesh.
  14844. * Returns a boolean
  14845. */
  14846. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14847. return false;
  14848. };
  14849. /**
  14850. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14851. * Returns a BoundingInfo
  14852. */
  14853. AbstractMesh.prototype.getBoundingInfo = function () {
  14854. if (this._masterMesh) {
  14855. return this._masterMesh.getBoundingInfo();
  14856. }
  14857. if (!this._boundingInfo) {
  14858. // this._boundingInfo is being created here
  14859. this._updateBoundingInfo();
  14860. }
  14861. // cannot be null.
  14862. return this._boundingInfo;
  14863. };
  14864. /**
  14865. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14866. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14867. */
  14868. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14869. if (includeDescendants === void 0) { includeDescendants = true; }
  14870. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14871. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14872. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14873. if (maxDimension === 0) {
  14874. return this;
  14875. }
  14876. var scale = 1 / maxDimension;
  14877. this.scaling.scaleInPlace(scale);
  14878. return this;
  14879. };
  14880. /**
  14881. * Sets a mesh new object BoundingInfo.
  14882. * Returns the AbstractMesh.
  14883. */
  14884. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14885. this._boundingInfo = boundingInfo;
  14886. return this;
  14887. };
  14888. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14889. get: function () {
  14890. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. AbstractMesh.prototype._preActivate = function () {
  14896. };
  14897. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14898. };
  14899. AbstractMesh.prototype._activate = function (renderId) {
  14900. this._renderId = renderId;
  14901. };
  14902. /**
  14903. * Returns the latest update of the World matrix
  14904. * Returns a Matrix.
  14905. */
  14906. AbstractMesh.prototype.getWorldMatrix = function () {
  14907. if (this._masterMesh) {
  14908. return this._masterMesh.getWorldMatrix();
  14909. }
  14910. return _super.prototype.getWorldMatrix.call(this);
  14911. };
  14912. // ================================== Point of View Movement =================================
  14913. /**
  14914. * Perform relative position change from the point of view of behind the front of the mesh.
  14915. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14916. * Supports definition of mesh facing forward or backward.
  14917. * @param {number} amountRight
  14918. * @param {number} amountUp
  14919. * @param {number} amountForward
  14920. *
  14921. * Returns the AbstractMesh.
  14922. */
  14923. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14924. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14925. return this;
  14926. };
  14927. /**
  14928. * Calculate relative position change from the point of view of behind the front of the mesh.
  14929. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14930. * Supports definition of mesh facing forward or backward.
  14931. * @param {number} amountRight
  14932. * @param {number} amountUp
  14933. * @param {number} amountForward
  14934. *
  14935. * Returns a new Vector3.
  14936. */
  14937. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14938. var rotMatrix = new BABYLON.Matrix();
  14939. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14940. rotQuaternion.toRotationMatrix(rotMatrix);
  14941. var translationDelta = BABYLON.Vector3.Zero();
  14942. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14943. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14944. return translationDelta;
  14945. };
  14946. // ================================== Point of View Rotation =================================
  14947. /**
  14948. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14949. * Supports definition of mesh facing forward or backward.
  14950. * @param {number} flipBack
  14951. * @param {number} twirlClockwise
  14952. * @param {number} tiltRight
  14953. *
  14954. * Returns the AbstractMesh.
  14955. */
  14956. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14957. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14958. return this;
  14959. };
  14960. /**
  14961. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14962. * Supports definition of mesh facing forward or backward.
  14963. * @param {number} flipBack
  14964. * @param {number} twirlClockwise
  14965. * @param {number} tiltRight
  14966. *
  14967. * Returns a new Vector3.
  14968. */
  14969. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14970. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14971. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14972. };
  14973. /**
  14974. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14975. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14976. */
  14977. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14978. if (includeDescendants === void 0) { includeDescendants = true; }
  14979. this.computeWorldMatrix(true);
  14980. var min;
  14981. var max;
  14982. var boundingInfo = this.getBoundingInfo();
  14983. if (!this.subMeshes) {
  14984. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14985. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14986. }
  14987. else {
  14988. min = boundingInfo.boundingBox.minimumWorld;
  14989. max = boundingInfo.boundingBox.maximumWorld;
  14990. }
  14991. if (includeDescendants) {
  14992. var descendants = this.getDescendants(false);
  14993. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14994. var descendant = descendants_1[_i];
  14995. var childMesh = descendant;
  14996. //make sure we have the needed params to get mix and max
  14997. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  14998. continue;
  14999. }
  15000. childMesh.computeWorldMatrix(true);
  15001. var childBoundingInfo = childMesh.getBoundingInfo();
  15002. var boundingBox = childBoundingInfo.boundingBox;
  15003. var minBox = boundingBox.minimumWorld;
  15004. var maxBox = boundingBox.maximumWorld;
  15005. BABYLON.Tools.CheckExtends(minBox, min, max);
  15006. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15007. }
  15008. }
  15009. return {
  15010. min: min,
  15011. max: max
  15012. };
  15013. };
  15014. /**
  15015. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15016. * Returns the AbstractMesh.
  15017. */
  15018. AbstractMesh.prototype._updateBoundingInfo = function () {
  15019. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15020. this._boundingInfo.update(this.worldMatrixFromCache);
  15021. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15022. return this;
  15023. };
  15024. /**
  15025. * Update a mesh's children BoundingInfo objects only.
  15026. * Returns the AbstractMesh.
  15027. */
  15028. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15029. if (!this.subMeshes) {
  15030. return this;
  15031. }
  15032. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15033. var subMesh = this.subMeshes[subIndex];
  15034. if (!subMesh.IsGlobal) {
  15035. subMesh.updateBoundingInfo(matrix);
  15036. }
  15037. }
  15038. return this;
  15039. };
  15040. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15041. // Bounding info
  15042. this._updateBoundingInfo();
  15043. };
  15044. /**
  15045. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15046. * A mesh is in the frustum if its bounding box intersects the frustum.
  15047. * Boolean returned.
  15048. */
  15049. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15050. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15051. };
  15052. /**
  15053. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15054. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15055. * Boolean returned.
  15056. */
  15057. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15058. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15059. ;
  15060. };
  15061. /**
  15062. * True if the mesh intersects another mesh or a SolidParticle object.
  15063. * 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)
  15064. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15065. * Returns a boolean.
  15066. */
  15067. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15068. if (precise === void 0) { precise = false; }
  15069. if (!this._boundingInfo || !mesh._boundingInfo) {
  15070. return false;
  15071. }
  15072. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15073. return true;
  15074. }
  15075. if (includeDescendants) {
  15076. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15077. var child = _a[_i];
  15078. if (child.intersectsMesh(mesh, precise, true)) {
  15079. return true;
  15080. }
  15081. }
  15082. }
  15083. return false;
  15084. };
  15085. /**
  15086. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15087. * Returns a boolean.
  15088. */
  15089. AbstractMesh.prototype.intersectsPoint = function (point) {
  15090. if (!this._boundingInfo) {
  15091. return false;
  15092. }
  15093. return this._boundingInfo.intersectsPoint(point);
  15094. };
  15095. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15096. return this.physicsImpostor;
  15097. };
  15098. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15099. if (camera === void 0) { camera = null; }
  15100. if (!camera) {
  15101. camera = this.getScene().activeCamera;
  15102. }
  15103. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15104. };
  15105. /**
  15106. * Returns the distance from the mesh to the active camera.
  15107. * Returns a float.
  15108. */
  15109. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15110. if (camera === void 0) { camera = null; }
  15111. if (!camera) {
  15112. camera = this.getScene().activeCamera;
  15113. }
  15114. return this.absolutePosition.subtract(camera.position).length();
  15115. };
  15116. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15117. if (!this.physicsImpostor) {
  15118. return this;
  15119. }
  15120. this.physicsImpostor.applyImpulse(force, contactPoint);
  15121. return this;
  15122. };
  15123. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15124. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15125. return this;
  15126. }
  15127. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15128. mainPivot: pivot1,
  15129. connectedPivot: pivot2,
  15130. nativeParams: options
  15131. });
  15132. return this;
  15133. };
  15134. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15135. // Collisions
  15136. /**
  15137. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15138. * Default `false`.
  15139. */
  15140. get: function () {
  15141. return this._checkCollisions;
  15142. },
  15143. set: function (collisionEnabled) {
  15144. this._checkCollisions = collisionEnabled;
  15145. if (this.getScene().workerCollisions) {
  15146. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15147. }
  15148. },
  15149. enumerable: true,
  15150. configurable: true
  15151. });
  15152. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15153. /**
  15154. * Gets Collider object used to compute collisions (not physics)
  15155. */
  15156. get: function () {
  15157. return this._collider;
  15158. },
  15159. enumerable: true,
  15160. configurable: true
  15161. });
  15162. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15163. var globalPosition = this.getAbsolutePosition();
  15164. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15165. if (!this._collider) {
  15166. this._collider = new BABYLON.Collider();
  15167. }
  15168. this._collider._radius = this.ellipsoid;
  15169. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15170. return this;
  15171. };
  15172. // Submeshes octree
  15173. /**
  15174. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15175. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15176. * Returns an Octree of submeshes.
  15177. */
  15178. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15179. if (maxCapacity === void 0) { maxCapacity = 64; }
  15180. if (maxDepth === void 0) { maxDepth = 2; }
  15181. if (!this._submeshesOctree) {
  15182. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15183. }
  15184. this.computeWorldMatrix(true);
  15185. var boundingInfo = this.getBoundingInfo();
  15186. // Update octree
  15187. var bbox = boundingInfo.boundingBox;
  15188. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15189. return this._submeshesOctree;
  15190. };
  15191. // Collisions
  15192. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15193. this._generatePointsArray();
  15194. if (!this._positions) {
  15195. return this;
  15196. }
  15197. // Transformation
  15198. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15199. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15200. subMesh._lastColliderWorldVertices = [];
  15201. subMesh._trianglePlanes = [];
  15202. var start = subMesh.verticesStart;
  15203. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15204. for (var i = start; i < end; i++) {
  15205. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15206. }
  15207. }
  15208. // Collide
  15209. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15210. if (collider.collisionFound) {
  15211. collider.collidedMesh = this;
  15212. }
  15213. return this;
  15214. };
  15215. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15216. var subMeshes;
  15217. var len;
  15218. // Octrees
  15219. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15220. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15221. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15222. len = intersections.length;
  15223. subMeshes = intersections.data;
  15224. }
  15225. else {
  15226. subMeshes = this.subMeshes;
  15227. len = subMeshes.length;
  15228. }
  15229. for (var index = 0; index < len; index++) {
  15230. var subMesh = subMeshes[index];
  15231. // Bounding test
  15232. if (len > 1 && !subMesh._checkCollision(collider))
  15233. continue;
  15234. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15235. }
  15236. return this;
  15237. };
  15238. AbstractMesh.prototype._checkCollision = function (collider) {
  15239. // Bounding box test
  15240. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15241. return this;
  15242. // Transformation matrix
  15243. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15244. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15245. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15246. return this;
  15247. };
  15248. // Picking
  15249. AbstractMesh.prototype._generatePointsArray = function () {
  15250. return false;
  15251. };
  15252. /**
  15253. * Checks if the passed Ray intersects with the mesh.
  15254. * Returns an object PickingInfo.
  15255. */
  15256. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15257. var pickingInfo = new BABYLON.PickingInfo();
  15258. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15259. return pickingInfo;
  15260. }
  15261. if (!this._generatePointsArray()) {
  15262. return pickingInfo;
  15263. }
  15264. var intersectInfo = null;
  15265. // Octrees
  15266. var subMeshes;
  15267. var len;
  15268. if (this._submeshesOctree && this.useOctreeForPicking) {
  15269. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15270. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15271. len = intersections.length;
  15272. subMeshes = intersections.data;
  15273. }
  15274. else {
  15275. subMeshes = this.subMeshes;
  15276. len = subMeshes.length;
  15277. }
  15278. for (var index = 0; index < len; index++) {
  15279. var subMesh = subMeshes[index];
  15280. // Bounding test
  15281. if (len > 1 && !subMesh.canIntersects(ray))
  15282. continue;
  15283. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15284. if (currentIntersectInfo) {
  15285. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15286. intersectInfo = currentIntersectInfo;
  15287. intersectInfo.subMeshId = index;
  15288. if (fastCheck) {
  15289. break;
  15290. }
  15291. }
  15292. }
  15293. }
  15294. if (intersectInfo) {
  15295. // Get picked point
  15296. var world = this.getWorldMatrix();
  15297. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15298. var direction = ray.direction.clone();
  15299. direction = direction.scale(intersectInfo.distance);
  15300. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15301. var pickedPoint = worldOrigin.add(worldDirection);
  15302. // Return result
  15303. pickingInfo.hit = true;
  15304. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15305. pickingInfo.pickedPoint = pickedPoint;
  15306. pickingInfo.pickedMesh = this;
  15307. pickingInfo.bu = intersectInfo.bu || 0;
  15308. pickingInfo.bv = intersectInfo.bv || 0;
  15309. pickingInfo.faceId = intersectInfo.faceId;
  15310. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15311. return pickingInfo;
  15312. }
  15313. return pickingInfo;
  15314. };
  15315. /**
  15316. * Clones the mesh, used by the class Mesh.
  15317. * Just returns `null` for an AbstractMesh.
  15318. */
  15319. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15320. return null;
  15321. };
  15322. /**
  15323. * Disposes all the mesh submeshes.
  15324. * Returns the AbstractMesh.
  15325. */
  15326. AbstractMesh.prototype.releaseSubMeshes = function () {
  15327. if (this.subMeshes) {
  15328. while (this.subMeshes.length) {
  15329. this.subMeshes[0].dispose();
  15330. }
  15331. }
  15332. else {
  15333. this.subMeshes = new Array();
  15334. }
  15335. return this;
  15336. };
  15337. /**
  15338. * Disposes the AbstractMesh.
  15339. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15340. * Returns nothing.
  15341. */
  15342. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15343. var _this = this;
  15344. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15345. var index;
  15346. // Action manager
  15347. if (this.actionManager) {
  15348. this.actionManager.dispose();
  15349. this.actionManager = null;
  15350. }
  15351. // Skeleton
  15352. this.skeleton = null;
  15353. // Physics
  15354. if (this.physicsImpostor) {
  15355. this.physicsImpostor.dispose();
  15356. }
  15357. // Intersections in progress
  15358. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15359. var other = this._intersectionsInProgress[index];
  15360. var pos = other._intersectionsInProgress.indexOf(this);
  15361. other._intersectionsInProgress.splice(pos, 1);
  15362. }
  15363. this._intersectionsInProgress = [];
  15364. // Lights
  15365. var lights = this.getScene().lights;
  15366. lights.forEach(function (light) {
  15367. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15368. if (meshIndex !== -1) {
  15369. light.includedOnlyMeshes.splice(meshIndex, 1);
  15370. }
  15371. meshIndex = light.excludedMeshes.indexOf(_this);
  15372. if (meshIndex !== -1) {
  15373. light.excludedMeshes.splice(meshIndex, 1);
  15374. }
  15375. // Shadow generators
  15376. var generator = light.getShadowGenerator();
  15377. if (generator) {
  15378. var shadowMap = generator.getShadowMap();
  15379. if (shadowMap && shadowMap.renderList) {
  15380. meshIndex = shadowMap.renderList.indexOf(_this);
  15381. if (meshIndex !== -1) {
  15382. shadowMap.renderList.splice(meshIndex, 1);
  15383. }
  15384. }
  15385. }
  15386. });
  15387. // Edges
  15388. if (this._edgesRenderer) {
  15389. this._edgesRenderer.dispose();
  15390. this._edgesRenderer = null;
  15391. }
  15392. // SubMeshes
  15393. if (this.getClassName() !== "InstancedMesh") {
  15394. this.releaseSubMeshes();
  15395. }
  15396. // Octree
  15397. var sceneOctree = this.getScene().selectionOctree;
  15398. if (sceneOctree) {
  15399. var index = sceneOctree.dynamicContent.indexOf(this);
  15400. if (index !== -1) {
  15401. sceneOctree.dynamicContent.splice(index, 1);
  15402. }
  15403. }
  15404. // Query
  15405. var engine = this.getScene().getEngine();
  15406. if (this._occlusionQuery) {
  15407. this._isOcclusionQueryInProgress = false;
  15408. engine.deleteQuery(this._occlusionQuery);
  15409. this._occlusionQuery = null;
  15410. }
  15411. // Engine
  15412. engine.wipeCaches();
  15413. // Remove from scene
  15414. this.getScene().removeMesh(this);
  15415. if (disposeMaterialAndTextures) {
  15416. if (this.material) {
  15417. this.material.dispose(false, true);
  15418. }
  15419. }
  15420. if (!doNotRecurse) {
  15421. // Particles
  15422. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15423. if (this.getScene().particleSystems[index].emitter === this) {
  15424. this.getScene().particleSystems[index].dispose();
  15425. index--;
  15426. }
  15427. }
  15428. }
  15429. // facet data
  15430. if (this._facetDataEnabled) {
  15431. this.disableFacetData();
  15432. }
  15433. this.onAfterWorldMatrixUpdateObservable.clear();
  15434. this.onCollideObservable.clear();
  15435. this.onCollisionPositionChangeObservable.clear();
  15436. this._isDisposed = true;
  15437. _super.prototype.dispose.call(this, doNotRecurse);
  15438. };
  15439. /**
  15440. * Adds the passed mesh as a child to the current mesh.
  15441. * Returns the AbstractMesh.
  15442. */
  15443. AbstractMesh.prototype.addChild = function (mesh) {
  15444. mesh.setParent(this);
  15445. return this;
  15446. };
  15447. /**
  15448. * Removes the passed mesh from the current mesh children list.
  15449. * Returns the AbstractMesh.
  15450. */
  15451. AbstractMesh.prototype.removeChild = function (mesh) {
  15452. mesh.setParent(null);
  15453. return this;
  15454. };
  15455. // Facet data
  15456. /**
  15457. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15458. * Returns the AbstractMesh.
  15459. */
  15460. AbstractMesh.prototype._initFacetData = function () {
  15461. if (!this._facetNormals) {
  15462. this._facetNormals = new Array();
  15463. }
  15464. if (!this._facetPositions) {
  15465. this._facetPositions = new Array();
  15466. }
  15467. if (!this._facetPartitioning) {
  15468. this._facetPartitioning = new Array();
  15469. }
  15470. this._facetNb = (this.getIndices().length / 3) | 0;
  15471. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15472. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15473. for (var f = 0; f < this._facetNb; f++) {
  15474. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15475. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15476. }
  15477. this._facetDataEnabled = true;
  15478. return this;
  15479. };
  15480. /**
  15481. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15482. * This method can be called within the render loop.
  15483. * 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.
  15484. * Returns the AbstractMesh.
  15485. */
  15486. AbstractMesh.prototype.updateFacetData = function () {
  15487. if (!this._facetDataEnabled) {
  15488. this._initFacetData();
  15489. }
  15490. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15491. var indices = this.getIndices();
  15492. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15493. var bInfo = this.getBoundingInfo();
  15494. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15495. // init arrays, matrix and sort function on first call
  15496. this._facetDepthSortEnabled = true;
  15497. if (indices instanceof Uint16Array) {
  15498. this._depthSortedIndices = new Uint16Array(indices);
  15499. }
  15500. else if (indices instanceof Uint32Array) {
  15501. this._depthSortedIndices = new Uint32Array(indices);
  15502. }
  15503. else {
  15504. var needs32bits = false;
  15505. for (var i = 0; i < indices.length; i++) {
  15506. if (indices[i] > 65535) {
  15507. needs32bits = true;
  15508. break;
  15509. }
  15510. }
  15511. if (needs32bits) {
  15512. this._depthSortedIndices = new Uint32Array(indices);
  15513. }
  15514. else {
  15515. this._depthSortedIndices = new Uint16Array(indices);
  15516. }
  15517. }
  15518. this._facetDepthSortFunction = function (f1, f2) {
  15519. return (f2.sqDistance - f1.sqDistance);
  15520. };
  15521. if (!this._facetDepthSortFrom) {
  15522. var camera = this.getScene().activeCamera;
  15523. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15524. }
  15525. this._depthSortedFacets = [];
  15526. for (var f = 0; f < this._facetNb; f++) {
  15527. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15528. this._depthSortedFacets.push(depthSortedFacet);
  15529. }
  15530. this._invertedMatrix = BABYLON.Matrix.Identity();
  15531. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15532. }
  15533. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15534. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15535. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15536. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15537. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15538. this._subDiv.max = this._partitioningSubdivisions;
  15539. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15540. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15541. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15542. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15543. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15544. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15545. // set the parameters for ComputeNormals()
  15546. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15547. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15548. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15549. this._facetParameters.bInfo = bInfo;
  15550. this._facetParameters.bbSize = this._bbSize;
  15551. this._facetParameters.subDiv = this._subDiv;
  15552. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15553. this._facetParameters.depthSort = this._facetDepthSort;
  15554. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15555. this.computeWorldMatrix(true);
  15556. this._worldMatrix.invertToRef(this._invertedMatrix);
  15557. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15558. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15559. }
  15560. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15561. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15562. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15563. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15564. var l = (this._depthSortedIndices.length / 3) | 0;
  15565. for (var f = 0; f < l; f++) {
  15566. var sind = this._depthSortedFacets[f].ind;
  15567. this._depthSortedIndices[f * 3] = indices[sind];
  15568. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15569. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15570. }
  15571. this.updateIndices(this._depthSortedIndices);
  15572. }
  15573. return this;
  15574. };
  15575. /**
  15576. * Returns the facetLocalNormals array.
  15577. * The normals are expressed in the mesh local space.
  15578. */
  15579. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15580. if (!this._facetNormals) {
  15581. this.updateFacetData();
  15582. }
  15583. return this._facetNormals;
  15584. };
  15585. /**
  15586. * Returns the facetLocalPositions array.
  15587. * The facet positions are expressed in the mesh local space.
  15588. */
  15589. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15590. if (!this._facetPositions) {
  15591. this.updateFacetData();
  15592. }
  15593. return this._facetPositions;
  15594. };
  15595. /**
  15596. * Returns the facetLocalPartioning array.
  15597. */
  15598. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15599. if (!this._facetPartitioning) {
  15600. this.updateFacetData();
  15601. }
  15602. return this._facetPartitioning;
  15603. };
  15604. /**
  15605. * Returns the i-th facet position in the world system.
  15606. * This method allocates a new Vector3 per call.
  15607. */
  15608. AbstractMesh.prototype.getFacetPosition = function (i) {
  15609. var pos = BABYLON.Vector3.Zero();
  15610. this.getFacetPositionToRef(i, pos);
  15611. return pos;
  15612. };
  15613. /**
  15614. * Sets the reference Vector3 with the i-th facet position in the world system.
  15615. * Returns the AbstractMesh.
  15616. */
  15617. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15618. var localPos = (this.getFacetLocalPositions())[i];
  15619. var world = this.getWorldMatrix();
  15620. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15621. return this;
  15622. };
  15623. /**
  15624. * Returns the i-th facet normal in the world system.
  15625. * This method allocates a new Vector3 per call.
  15626. */
  15627. AbstractMesh.prototype.getFacetNormal = function (i) {
  15628. var norm = BABYLON.Vector3.Zero();
  15629. this.getFacetNormalToRef(i, norm);
  15630. return norm;
  15631. };
  15632. /**
  15633. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15634. * Returns the AbstractMesh.
  15635. */
  15636. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15637. var localNorm = (this.getFacetLocalNormals())[i];
  15638. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15639. return this;
  15640. };
  15641. /**
  15642. * 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).
  15643. */
  15644. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15645. var bInfo = this.getBoundingInfo();
  15646. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15647. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15648. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15649. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15650. return null;
  15651. }
  15652. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15653. };
  15654. /**
  15655. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15656. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15657. * 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.
  15658. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15659. * 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.
  15660. */
  15661. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15662. if (checkFace === void 0) { checkFace = false; }
  15663. if (facing === void 0) { facing = true; }
  15664. var world = this.getWorldMatrix();
  15665. var invMat = BABYLON.Tmp.Matrix[5];
  15666. world.invertToRef(invMat);
  15667. var invVect = BABYLON.Tmp.Vector3[8];
  15668. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15669. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15670. if (projected) {
  15671. // tranform the local computed projected vector to world coordinates
  15672. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15673. }
  15674. return closest;
  15675. };
  15676. /**
  15677. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15678. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15679. * 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.
  15680. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15681. * 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.
  15682. */
  15683. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15684. if (checkFace === void 0) { checkFace = false; }
  15685. if (facing === void 0) { facing = true; }
  15686. var closest = null;
  15687. var tmpx = 0.0;
  15688. var tmpy = 0.0;
  15689. var tmpz = 0.0;
  15690. var d = 0.0; // tmp dot facet normal * facet position
  15691. var t0 = 0.0;
  15692. var projx = 0.0;
  15693. var projy = 0.0;
  15694. var projz = 0.0;
  15695. // Get all the facets in the same partitioning block than (x, y, z)
  15696. var facetPositions = this.getFacetLocalPositions();
  15697. var facetNormals = this.getFacetLocalNormals();
  15698. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15699. if (!facetsInBlock) {
  15700. return null;
  15701. }
  15702. // Get the closest facet to (x, y, z)
  15703. var shortest = Number.MAX_VALUE; // init distance vars
  15704. var tmpDistance = shortest;
  15705. var fib; // current facet in the block
  15706. var norm; // current facet normal
  15707. var p0; // current facet barycenter position
  15708. // loop on all the facets in the current partitioning block
  15709. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15710. fib = facetsInBlock[idx];
  15711. norm = facetNormals[fib];
  15712. p0 = facetPositions[fib];
  15713. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15714. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15715. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15716. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15717. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15718. projx = x + norm.x * t0;
  15719. projy = y + norm.y * t0;
  15720. projz = z + norm.z * t0;
  15721. tmpx = projx - x;
  15722. tmpy = projy - y;
  15723. tmpz = projz - z;
  15724. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15725. if (tmpDistance < shortest) {
  15726. shortest = tmpDistance;
  15727. closest = fib;
  15728. if (projected) {
  15729. projected.x = projx;
  15730. projected.y = projy;
  15731. projected.z = projz;
  15732. }
  15733. }
  15734. }
  15735. }
  15736. return closest;
  15737. };
  15738. /**
  15739. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15740. */
  15741. AbstractMesh.prototype.getFacetDataParameters = function () {
  15742. return this._facetParameters;
  15743. };
  15744. /**
  15745. * Disables the feature FacetData and frees the related memory.
  15746. * Returns the AbstractMesh.
  15747. */
  15748. AbstractMesh.prototype.disableFacetData = function () {
  15749. if (this._facetDataEnabled) {
  15750. this._facetDataEnabled = false;
  15751. this._facetPositions = new Array();
  15752. this._facetNormals = new Array();
  15753. this._facetPartitioning = new Array();
  15754. this._facetParameters = null;
  15755. this._depthSortedIndices = new Uint32Array(0);
  15756. }
  15757. return this;
  15758. };
  15759. /**
  15760. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15761. * Returns the mesh.
  15762. */
  15763. AbstractMesh.prototype.updateIndices = function (indices) {
  15764. return this;
  15765. };
  15766. /**
  15767. * The mesh Geometry. Actually used by the Mesh object.
  15768. * Returns a blank geometry object.
  15769. */
  15770. /**
  15771. * Creates new normals data for the mesh.
  15772. * @param updatable.
  15773. */
  15774. AbstractMesh.prototype.createNormals = function (updatable) {
  15775. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15776. var indices = this.getIndices();
  15777. var normals;
  15778. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15779. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15780. }
  15781. else {
  15782. normals = [];
  15783. }
  15784. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15785. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15786. };
  15787. /**
  15788. * Align the mesh with a normal.
  15789. * Returns the mesh.
  15790. */
  15791. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15792. if (!upDirection) {
  15793. upDirection = BABYLON.Axis.Y;
  15794. }
  15795. var axisX = BABYLON.Tmp.Vector3[0];
  15796. var axisZ = BABYLON.Tmp.Vector3[1];
  15797. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15798. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15799. if (this.rotationQuaternion) {
  15800. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15801. }
  15802. else {
  15803. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15804. }
  15805. return this;
  15806. };
  15807. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15808. var engine = this.getEngine();
  15809. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15810. this._isOccluded = false;
  15811. return;
  15812. }
  15813. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15814. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15815. if (isOcclusionQueryAvailable) {
  15816. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15817. this._isOcclusionQueryInProgress = false;
  15818. this._occlusionInternalRetryCounter = 0;
  15819. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15820. }
  15821. else {
  15822. this._occlusionInternalRetryCounter++;
  15823. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15824. this._isOcclusionQueryInProgress = false;
  15825. this._occlusionInternalRetryCounter = 0;
  15826. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15827. // if strict continue the last state of the object.
  15828. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15829. }
  15830. else {
  15831. return;
  15832. }
  15833. }
  15834. }
  15835. var scene = this.getScene();
  15836. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15837. if (!this._occlusionQuery) {
  15838. this._occlusionQuery = engine.createQuery();
  15839. }
  15840. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15841. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15842. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15843. this._isOcclusionQueryInProgress = true;
  15844. };
  15845. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15846. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15847. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15848. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15849. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15850. return AbstractMesh;
  15851. }(BABYLON.TransformNode));
  15852. BABYLON.AbstractMesh = AbstractMesh;
  15853. })(BABYLON || (BABYLON = {}));
  15854. //# sourceMappingURL=babylon.abstractMesh.js.map
  15855. var BABYLON;
  15856. (function (BABYLON) {
  15857. var Light = /** @class */ (function (_super) {
  15858. __extends(Light, _super);
  15859. /**
  15860. * Creates a Light object in the scene.
  15861. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15862. */
  15863. function Light(name, scene) {
  15864. var _this = _super.call(this, name, scene) || this;
  15865. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15866. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15867. _this.intensity = 1.0;
  15868. _this.range = Number.MAX_VALUE;
  15869. /**
  15870. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15871. * of light.
  15872. */
  15873. _this._photometricScale = 1.0;
  15874. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15875. _this._radius = 0.00001;
  15876. _this.renderPriority = 0;
  15877. /**
  15878. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15879. * the current shadow generator.
  15880. */
  15881. _this.shadowEnabled = true;
  15882. _this._excludeWithLayerMask = 0;
  15883. _this._includeOnlyWithLayerMask = 0;
  15884. _this._lightmapMode = 0;
  15885. _this._excludedMeshesIds = new Array();
  15886. _this._includedOnlyMeshesIds = new Array();
  15887. _this.getScene().addLight(_this);
  15888. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15889. _this._buildUniformLayout();
  15890. _this.includedOnlyMeshes = new Array();
  15891. _this.excludedMeshes = new Array();
  15892. _this._resyncMeshes();
  15893. return _this;
  15894. }
  15895. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15896. /**
  15897. * If every light affecting the material is in this lightmapMode,
  15898. * material.lightmapTexture adds or multiplies
  15899. * (depends on material.useLightmapAsShadowmap)
  15900. * after every other light calculations.
  15901. */
  15902. get: function () {
  15903. return Light._LIGHTMAP_DEFAULT;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15909. /**
  15910. * material.lightmapTexture as only diffuse lighting from this light
  15911. * adds pnly specular lighting from this light
  15912. * adds dynamic shadows
  15913. */
  15914. get: function () {
  15915. return Light._LIGHTMAP_SPECULAR;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15921. /**
  15922. * material.lightmapTexture as only lighting
  15923. * no light calculation from this light
  15924. * only adds dynamic shadows from this light
  15925. */
  15926. get: function () {
  15927. return Light._LIGHTMAP_SHADOWSONLY;
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15933. /**
  15934. * Each light type uses the default quantity according to its type:
  15935. * point/spot lights use luminous intensity
  15936. * directional lights use illuminance
  15937. */
  15938. get: function () {
  15939. return Light._INTENSITYMODE_AUTOMATIC;
  15940. },
  15941. enumerable: true,
  15942. configurable: true
  15943. });
  15944. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15945. /**
  15946. * lumen (lm)
  15947. */
  15948. get: function () {
  15949. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15955. /**
  15956. * candela (lm/sr)
  15957. */
  15958. get: function () {
  15959. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15965. /**
  15966. * lux (lm/m^2)
  15967. */
  15968. get: function () {
  15969. return Light._INTENSITYMODE_ILLUMINANCE;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15975. /**
  15976. * nit (cd/m^2)
  15977. */
  15978. get: function () {
  15979. return Light._INTENSITYMODE_LUMINANCE;
  15980. },
  15981. enumerable: true,
  15982. configurable: true
  15983. });
  15984. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15985. /**
  15986. * Light type const id of the point light.
  15987. */
  15988. get: function () {
  15989. return Light._LIGHTTYPEID_POINTLIGHT;
  15990. },
  15991. enumerable: true,
  15992. configurable: true
  15993. });
  15994. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15995. /**
  15996. * Light type const id of the directional light.
  15997. */
  15998. get: function () {
  15999. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16005. /**
  16006. * Light type const id of the spot light.
  16007. */
  16008. get: function () {
  16009. return Light._LIGHTTYPEID_SPOTLIGHT;
  16010. },
  16011. enumerable: true,
  16012. configurable: true
  16013. });
  16014. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16015. /**
  16016. * Light type const id of the hemispheric light.
  16017. */
  16018. get: function () {
  16019. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16020. },
  16021. enumerable: true,
  16022. configurable: true
  16023. });
  16024. Object.defineProperty(Light.prototype, "intensityMode", {
  16025. /**
  16026. * Gets the photometric scale used to interpret the intensity.
  16027. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16028. */
  16029. get: function () {
  16030. return this._intensityMode;
  16031. },
  16032. /**
  16033. * Sets the photometric scale used to interpret the intensity.
  16034. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16035. */
  16036. set: function (value) {
  16037. this._intensityMode = value;
  16038. this._computePhotometricScale();
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. ;
  16044. ;
  16045. Object.defineProperty(Light.prototype, "radius", {
  16046. /**
  16047. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16048. */
  16049. get: function () {
  16050. return this._radius;
  16051. },
  16052. /**
  16053. * sets the light radius used by PBR Materials to simulate soft area lights.
  16054. */
  16055. set: function (value) {
  16056. this._radius = value;
  16057. this._computePhotometricScale();
  16058. },
  16059. enumerable: true,
  16060. configurable: true
  16061. });
  16062. ;
  16063. ;
  16064. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16065. get: function () {
  16066. return this._includedOnlyMeshes;
  16067. },
  16068. set: function (value) {
  16069. this._includedOnlyMeshes = value;
  16070. this._hookArrayForIncludedOnly(value);
  16071. },
  16072. enumerable: true,
  16073. configurable: true
  16074. });
  16075. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16076. get: function () {
  16077. return this._excludedMeshes;
  16078. },
  16079. set: function (value) {
  16080. this._excludedMeshes = value;
  16081. this._hookArrayForExcluded(value);
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16087. get: function () {
  16088. return this._excludeWithLayerMask;
  16089. },
  16090. set: function (value) {
  16091. this._excludeWithLayerMask = value;
  16092. this._resyncMeshes();
  16093. },
  16094. enumerable: true,
  16095. configurable: true
  16096. });
  16097. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16098. get: function () {
  16099. return this._includeOnlyWithLayerMask;
  16100. },
  16101. set: function (value) {
  16102. this._includeOnlyWithLayerMask = value;
  16103. this._resyncMeshes();
  16104. },
  16105. enumerable: true,
  16106. configurable: true
  16107. });
  16108. Object.defineProperty(Light.prototype, "lightmapMode", {
  16109. get: function () {
  16110. return this._lightmapMode;
  16111. },
  16112. set: function (value) {
  16113. if (this._lightmapMode === value) {
  16114. return;
  16115. }
  16116. this._lightmapMode = value;
  16117. this._markMeshesAsLightDirty();
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Light.prototype._buildUniformLayout = function () {
  16123. // Overridden
  16124. };
  16125. /**
  16126. * Returns the string "Light".
  16127. */
  16128. Light.prototype.getClassName = function () {
  16129. return "Light";
  16130. };
  16131. /**
  16132. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16133. */
  16134. Light.prototype.toString = function (fullDetails) {
  16135. var ret = "Name: " + this.name;
  16136. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16137. if (this.animations) {
  16138. for (var i = 0; i < this.animations.length; i++) {
  16139. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16140. }
  16141. }
  16142. if (fullDetails) {
  16143. }
  16144. return ret;
  16145. };
  16146. /**
  16147. * Set the enabled state of this node.
  16148. * @param {boolean} value - the new enabled state
  16149. * @see isEnabled
  16150. */
  16151. Light.prototype.setEnabled = function (value) {
  16152. _super.prototype.setEnabled.call(this, value);
  16153. this._resyncMeshes();
  16154. };
  16155. /**
  16156. * Returns the Light associated shadow generator.
  16157. */
  16158. Light.prototype.getShadowGenerator = function () {
  16159. return this._shadowGenerator;
  16160. };
  16161. /**
  16162. * Returns a Vector3, the absolute light position in the World.
  16163. */
  16164. Light.prototype.getAbsolutePosition = function () {
  16165. return BABYLON.Vector3.Zero();
  16166. };
  16167. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16168. };
  16169. Light.prototype._getWorldMatrix = function () {
  16170. return BABYLON.Matrix.Identity();
  16171. };
  16172. /**
  16173. * Boolean : True if the light will affect the passed mesh.
  16174. */
  16175. Light.prototype.canAffectMesh = function (mesh) {
  16176. if (!mesh) {
  16177. return true;
  16178. }
  16179. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16180. return false;
  16181. }
  16182. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16183. return false;
  16184. }
  16185. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16186. return false;
  16187. }
  16188. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16189. return false;
  16190. }
  16191. return true;
  16192. };
  16193. /**
  16194. * Returns the light World matrix.
  16195. */
  16196. Light.prototype.getWorldMatrix = function () {
  16197. this._currentRenderId = this.getScene().getRenderId();
  16198. var worldMatrix = this._getWorldMatrix();
  16199. if (this.parent && this.parent.getWorldMatrix) {
  16200. if (!this._parentedWorldMatrix) {
  16201. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16202. }
  16203. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16204. this._markSyncedWithParent();
  16205. return this._parentedWorldMatrix;
  16206. }
  16207. return worldMatrix;
  16208. };
  16209. /**
  16210. * Sort function to order lights for rendering.
  16211. * @param a First Light object to compare to second.
  16212. * @param b Second Light object to compare first.
  16213. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16214. */
  16215. Light.compareLightsPriority = function (a, b) {
  16216. //shadow-casting lights have priority over non-shadow-casting lights
  16217. //the renderPrioirty is a secondary sort criterion
  16218. if (a.shadowEnabled !== b.shadowEnabled) {
  16219. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16220. }
  16221. return b.renderPriority - a.renderPriority;
  16222. };
  16223. /**
  16224. * Disposes the light.
  16225. */
  16226. Light.prototype.dispose = function () {
  16227. if (this._shadowGenerator) {
  16228. this._shadowGenerator.dispose();
  16229. this._shadowGenerator = null;
  16230. }
  16231. // Animations
  16232. this.getScene().stopAnimation(this);
  16233. // Remove from meshes
  16234. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16235. var mesh = _a[_i];
  16236. mesh._removeLightSource(this);
  16237. }
  16238. this._uniformBuffer.dispose();
  16239. // Remove from scene
  16240. this.getScene().removeLight(this);
  16241. _super.prototype.dispose.call(this);
  16242. };
  16243. /**
  16244. * Returns the light type ID (integer).
  16245. */
  16246. Light.prototype.getTypeID = function () {
  16247. return 0;
  16248. };
  16249. /**
  16250. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16251. */
  16252. Light.prototype.getScaledIntensity = function () {
  16253. return this._photometricScale * this.intensity;
  16254. };
  16255. /**
  16256. * Returns a new Light object, named "name", from the current one.
  16257. */
  16258. Light.prototype.clone = function (name) {
  16259. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16260. if (!constructor) {
  16261. return null;
  16262. }
  16263. return BABYLON.SerializationHelper.Clone(constructor, this);
  16264. };
  16265. /**
  16266. * Serializes the current light into a Serialization object.
  16267. * Returns the serialized object.
  16268. */
  16269. Light.prototype.serialize = function () {
  16270. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16271. // Type
  16272. serializationObject.type = this.getTypeID();
  16273. // Parent
  16274. if (this.parent) {
  16275. serializationObject.parentId = this.parent.id;
  16276. }
  16277. // Inclusion / exclusions
  16278. if (this.excludedMeshes.length > 0) {
  16279. serializationObject.excludedMeshesIds = [];
  16280. this.excludedMeshes.forEach(function (mesh) {
  16281. serializationObject.excludedMeshesIds.push(mesh.id);
  16282. });
  16283. }
  16284. if (this.includedOnlyMeshes.length > 0) {
  16285. serializationObject.includedOnlyMeshesIds = [];
  16286. this.includedOnlyMeshes.forEach(function (mesh) {
  16287. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16288. });
  16289. }
  16290. // Animations
  16291. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16292. serializationObject.ranges = this.serializeAnimationRanges();
  16293. return serializationObject;
  16294. };
  16295. /**
  16296. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16297. * This new light is named "name" and added to the passed scene.
  16298. */
  16299. Light.GetConstructorFromName = function (type, name, scene) {
  16300. switch (type) {
  16301. case 0:
  16302. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16303. case 1:
  16304. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16305. case 2:
  16306. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16307. case 3:
  16308. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16309. }
  16310. return null;
  16311. };
  16312. /**
  16313. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16314. */
  16315. Light.Parse = function (parsedLight, scene) {
  16316. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16317. if (!constructor) {
  16318. return null;
  16319. }
  16320. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16321. // Inclusion / exclusions
  16322. if (parsedLight.excludedMeshesIds) {
  16323. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16324. }
  16325. if (parsedLight.includedOnlyMeshesIds) {
  16326. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16327. }
  16328. // Parent
  16329. if (parsedLight.parentId) {
  16330. light._waitingParentId = parsedLight.parentId;
  16331. }
  16332. // Animations
  16333. if (parsedLight.animations) {
  16334. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16335. var parsedAnimation = parsedLight.animations[animationIndex];
  16336. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16337. }
  16338. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16339. }
  16340. if (parsedLight.autoAnimate) {
  16341. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16342. }
  16343. return light;
  16344. };
  16345. Light.prototype._hookArrayForExcluded = function (array) {
  16346. var _this = this;
  16347. var oldPush = array.push;
  16348. array.push = function () {
  16349. var items = [];
  16350. for (var _i = 0; _i < arguments.length; _i++) {
  16351. items[_i] = arguments[_i];
  16352. }
  16353. var result = oldPush.apply(array, items);
  16354. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16355. var item = items_1[_a];
  16356. item._resyncLighSource(_this);
  16357. }
  16358. return result;
  16359. };
  16360. var oldSplice = array.splice;
  16361. array.splice = function (index, deleteCount) {
  16362. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16363. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16364. var item = deleted_1[_i];
  16365. item._resyncLighSource(_this);
  16366. }
  16367. return deleted;
  16368. };
  16369. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16370. var item = array_1[_i];
  16371. item._resyncLighSource(this);
  16372. }
  16373. };
  16374. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16375. var _this = this;
  16376. var oldPush = array.push;
  16377. array.push = function () {
  16378. var items = [];
  16379. for (var _i = 0; _i < arguments.length; _i++) {
  16380. items[_i] = arguments[_i];
  16381. }
  16382. var result = oldPush.apply(array, items);
  16383. _this._resyncMeshes();
  16384. return result;
  16385. };
  16386. var oldSplice = array.splice;
  16387. array.splice = function (index, deleteCount) {
  16388. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16389. _this._resyncMeshes();
  16390. return deleted;
  16391. };
  16392. this._resyncMeshes();
  16393. };
  16394. Light.prototype._resyncMeshes = function () {
  16395. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16396. var mesh = _a[_i];
  16397. mesh._resyncLighSource(this);
  16398. }
  16399. };
  16400. Light.prototype._markMeshesAsLightDirty = function () {
  16401. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16402. var mesh = _a[_i];
  16403. if (mesh._lightSources.indexOf(this) !== -1) {
  16404. mesh._markSubMeshesAsLightDirty();
  16405. }
  16406. }
  16407. };
  16408. /**
  16409. * Recomputes the cached photometric scale if needed.
  16410. */
  16411. Light.prototype._computePhotometricScale = function () {
  16412. this._photometricScale = this._getPhotometricScale();
  16413. this.getScene().resetCachedMaterial();
  16414. };
  16415. /**
  16416. * Returns the Photometric Scale according to the light type and intensity mode.
  16417. */
  16418. Light.prototype._getPhotometricScale = function () {
  16419. var photometricScale = 0.0;
  16420. var lightTypeID = this.getTypeID();
  16421. //get photometric mode
  16422. var photometricMode = this.intensityMode;
  16423. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16424. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16425. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16426. }
  16427. else {
  16428. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16429. }
  16430. }
  16431. //compute photometric scale
  16432. switch (lightTypeID) {
  16433. case Light.LIGHTTYPEID_POINTLIGHT:
  16434. case Light.LIGHTTYPEID_SPOTLIGHT:
  16435. switch (photometricMode) {
  16436. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16437. photometricScale = 1.0 / (4.0 * Math.PI);
  16438. break;
  16439. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16440. photometricScale = 1.0;
  16441. break;
  16442. case Light.INTENSITYMODE_LUMINANCE:
  16443. photometricScale = this.radius * this.radius;
  16444. break;
  16445. }
  16446. break;
  16447. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16448. switch (photometricMode) {
  16449. case Light.INTENSITYMODE_ILLUMINANCE:
  16450. photometricScale = 1.0;
  16451. break;
  16452. case Light.INTENSITYMODE_LUMINANCE:
  16453. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16454. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16455. var apexAngleRadians = this.radius;
  16456. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16457. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16458. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16459. photometricScale = solidAngle;
  16460. break;
  16461. }
  16462. break;
  16463. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16464. // No fall off in hemisperic light.
  16465. photometricScale = 1.0;
  16466. break;
  16467. }
  16468. return photometricScale;
  16469. };
  16470. Light.prototype._reorderLightsInScene = function () {
  16471. var scene = this.getScene();
  16472. if (this._renderPriority != 0) {
  16473. scene.requireLightSorting = true;
  16474. }
  16475. this.getScene().sortLightsByPriority();
  16476. };
  16477. //lightmapMode Consts
  16478. Light._LIGHTMAP_DEFAULT = 0;
  16479. Light._LIGHTMAP_SPECULAR = 1;
  16480. Light._LIGHTMAP_SHADOWSONLY = 2;
  16481. // Intensity Mode Consts
  16482. Light._INTENSITYMODE_AUTOMATIC = 0;
  16483. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16484. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16485. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16486. Light._INTENSITYMODE_LUMINANCE = 4;
  16487. // Light types ids const.
  16488. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16489. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16490. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16491. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16492. __decorate([
  16493. BABYLON.serializeAsColor3()
  16494. ], Light.prototype, "diffuse", void 0);
  16495. __decorate([
  16496. BABYLON.serializeAsColor3()
  16497. ], Light.prototype, "specular", void 0);
  16498. __decorate([
  16499. BABYLON.serialize()
  16500. ], Light.prototype, "intensity", void 0);
  16501. __decorate([
  16502. BABYLON.serialize()
  16503. ], Light.prototype, "range", void 0);
  16504. __decorate([
  16505. BABYLON.serialize()
  16506. ], Light.prototype, "intensityMode", null);
  16507. __decorate([
  16508. BABYLON.serialize()
  16509. ], Light.prototype, "radius", null);
  16510. __decorate([
  16511. BABYLON.serialize()
  16512. ], Light.prototype, "_renderPriority", void 0);
  16513. __decorate([
  16514. BABYLON.expandToProperty("_reorderLightsInScene")
  16515. ], Light.prototype, "renderPriority", void 0);
  16516. __decorate([
  16517. BABYLON.serialize()
  16518. ], Light.prototype, "shadowEnabled", void 0);
  16519. __decorate([
  16520. BABYLON.serialize("excludeWithLayerMask")
  16521. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16522. __decorate([
  16523. BABYLON.serialize("includeOnlyWithLayerMask")
  16524. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16525. __decorate([
  16526. BABYLON.serialize("lightmapMode")
  16527. ], Light.prototype, "_lightmapMode", void 0);
  16528. return Light;
  16529. }(BABYLON.Node));
  16530. BABYLON.Light = Light;
  16531. })(BABYLON || (BABYLON = {}));
  16532. //# sourceMappingURL=babylon.light.js.map
  16533. var BABYLON;
  16534. (function (BABYLON) {
  16535. var Camera = /** @class */ (function (_super) {
  16536. __extends(Camera, _super);
  16537. function Camera(name, position, scene) {
  16538. var _this = _super.call(this, name, scene) || this;
  16539. _this.upVector = BABYLON.Vector3.Up();
  16540. _this.orthoLeft = null;
  16541. _this.orthoRight = null;
  16542. _this.orthoBottom = null;
  16543. _this.orthoTop = null;
  16544. _this.fov = 0.8;
  16545. _this.minZ = 1;
  16546. _this.maxZ = 10000.0;
  16547. _this.inertia = 0.9;
  16548. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16549. _this.isIntermediate = false;
  16550. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16551. _this.layerMask = 0x0FFFFFFF;
  16552. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16553. // Camera rig members
  16554. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16555. _this._rigCameras = new Array();
  16556. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16557. _this._skipRendering = false;
  16558. _this.customRenderTargets = new Array();
  16559. // Observables
  16560. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16561. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16562. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16563. _this.onRestoreStateObservable = new BABYLON.Observable();
  16564. // Cache
  16565. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16566. _this._projectionMatrix = new BABYLON.Matrix();
  16567. _this._doNotComputeProjectionMatrix = false;
  16568. _this._postProcesses = new Array();
  16569. _this._transformMatrix = BABYLON.Matrix.Zero();
  16570. _this._activeMeshes = new BABYLON.SmartArray(256);
  16571. _this._globalPosition = BABYLON.Vector3.Zero();
  16572. _this._refreshFrustumPlanes = true;
  16573. _this.getScene().addCamera(_this);
  16574. if (!_this.getScene().activeCamera) {
  16575. _this.getScene().activeCamera = _this;
  16576. }
  16577. _this.position = position;
  16578. return _this;
  16579. }
  16580. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16581. get: function () {
  16582. return Camera._PERSPECTIVE_CAMERA;
  16583. },
  16584. enumerable: true,
  16585. configurable: true
  16586. });
  16587. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16588. get: function () {
  16589. return Camera._ORTHOGRAPHIC_CAMERA;
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16595. get: function () {
  16596. return Camera._FOVMODE_VERTICAL_FIXED;
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16602. get: function () {
  16603. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16604. },
  16605. enumerable: true,
  16606. configurable: true
  16607. });
  16608. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16609. get: function () {
  16610. return Camera._RIG_MODE_NONE;
  16611. },
  16612. enumerable: true,
  16613. configurable: true
  16614. });
  16615. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16616. get: function () {
  16617. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16618. },
  16619. enumerable: true,
  16620. configurable: true
  16621. });
  16622. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16623. get: function () {
  16624. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16630. get: function () {
  16631. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16637. get: function () {
  16638. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16639. },
  16640. enumerable: true,
  16641. configurable: true
  16642. });
  16643. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16644. get: function () {
  16645. return Camera._RIG_MODE_VR;
  16646. },
  16647. enumerable: true,
  16648. configurable: true
  16649. });
  16650. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16651. get: function () {
  16652. return Camera._RIG_MODE_WEBVR;
  16653. },
  16654. enumerable: true,
  16655. configurable: true
  16656. });
  16657. /**
  16658. * Store current camera state (fov, position, etc..)
  16659. */
  16660. Camera.prototype.storeState = function () {
  16661. this._stateStored = true;
  16662. this._storedFov = this.fov;
  16663. return this;
  16664. };
  16665. /**
  16666. * Restores the camera state values if it has been stored. You must call storeState() first
  16667. */
  16668. Camera.prototype._restoreStateValues = function () {
  16669. if (!this._stateStored) {
  16670. return false;
  16671. }
  16672. this.fov = this._storedFov;
  16673. return true;
  16674. };
  16675. /**
  16676. * Restored camera state. You must call storeState() first
  16677. */
  16678. Camera.prototype.restoreState = function () {
  16679. if (this._restoreStateValues()) {
  16680. this.onRestoreStateObservable.notifyObservers(this);
  16681. return true;
  16682. }
  16683. return false;
  16684. };
  16685. Camera.prototype.getClassName = function () {
  16686. return "Camera";
  16687. };
  16688. /**
  16689. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16690. */
  16691. Camera.prototype.toString = function (fullDetails) {
  16692. var ret = "Name: " + this.name;
  16693. ret += ", type: " + this.getClassName();
  16694. if (this.animations) {
  16695. for (var i = 0; i < this.animations.length; i++) {
  16696. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16697. }
  16698. }
  16699. if (fullDetails) {
  16700. }
  16701. return ret;
  16702. };
  16703. Object.defineProperty(Camera.prototype, "globalPosition", {
  16704. get: function () {
  16705. return this._globalPosition;
  16706. },
  16707. enumerable: true,
  16708. configurable: true
  16709. });
  16710. Camera.prototype.getActiveMeshes = function () {
  16711. return this._activeMeshes;
  16712. };
  16713. Camera.prototype.isActiveMesh = function (mesh) {
  16714. return (this._activeMeshes.indexOf(mesh) !== -1);
  16715. };
  16716. //Cache
  16717. Camera.prototype._initCache = function () {
  16718. _super.prototype._initCache.call(this);
  16719. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16720. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16721. this._cache.mode = undefined;
  16722. this._cache.minZ = undefined;
  16723. this._cache.maxZ = undefined;
  16724. this._cache.fov = undefined;
  16725. this._cache.fovMode = undefined;
  16726. this._cache.aspectRatio = undefined;
  16727. this._cache.orthoLeft = undefined;
  16728. this._cache.orthoRight = undefined;
  16729. this._cache.orthoBottom = undefined;
  16730. this._cache.orthoTop = undefined;
  16731. this._cache.renderWidth = undefined;
  16732. this._cache.renderHeight = undefined;
  16733. };
  16734. Camera.prototype._updateCache = function (ignoreParentClass) {
  16735. if (!ignoreParentClass) {
  16736. _super.prototype._updateCache.call(this);
  16737. }
  16738. this._cache.position.copyFrom(this.position);
  16739. this._cache.upVector.copyFrom(this.upVector);
  16740. };
  16741. // Synchronized
  16742. Camera.prototype._isSynchronized = function () {
  16743. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16744. };
  16745. Camera.prototype._isSynchronizedViewMatrix = function () {
  16746. if (!_super.prototype._isSynchronized.call(this))
  16747. return false;
  16748. return this._cache.position.equals(this.position)
  16749. && this._cache.upVector.equals(this.upVector)
  16750. && this.isSynchronizedWithParent();
  16751. };
  16752. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16753. var check = this._cache.mode === this.mode
  16754. && this._cache.minZ === this.minZ
  16755. && this._cache.maxZ === this.maxZ;
  16756. if (!check) {
  16757. return false;
  16758. }
  16759. var engine = this.getEngine();
  16760. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16761. check = this._cache.fov === this.fov
  16762. && this._cache.fovMode === this.fovMode
  16763. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16764. }
  16765. else {
  16766. check = this._cache.orthoLeft === this.orthoLeft
  16767. && this._cache.orthoRight === this.orthoRight
  16768. && this._cache.orthoBottom === this.orthoBottom
  16769. && this._cache.orthoTop === this.orthoTop
  16770. && this._cache.renderWidth === engine.getRenderWidth()
  16771. && this._cache.renderHeight === engine.getRenderHeight();
  16772. }
  16773. return check;
  16774. };
  16775. // Controls
  16776. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16777. };
  16778. Camera.prototype.detachControl = function (element) {
  16779. };
  16780. Camera.prototype.update = function () {
  16781. this._checkInputs();
  16782. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16783. this._updateRigCameras();
  16784. }
  16785. };
  16786. Camera.prototype._checkInputs = function () {
  16787. this.onAfterCheckInputsObservable.notifyObservers(this);
  16788. };
  16789. Object.defineProperty(Camera.prototype, "rigCameras", {
  16790. get: function () {
  16791. return this._rigCameras;
  16792. },
  16793. enumerable: true,
  16794. configurable: true
  16795. });
  16796. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16797. get: function () {
  16798. return this._rigPostProcess;
  16799. },
  16800. enumerable: true,
  16801. configurable: true
  16802. });
  16803. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16804. // invalidate framebuffer
  16805. if (this._postProcesses.length > 0) {
  16806. this._postProcesses[0].markTextureDirty();
  16807. }
  16808. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16809. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16810. var cam = this._rigCameras[i];
  16811. var rigPostProcess = cam._rigPostProcess;
  16812. // for VR rig, there does not have to be a post process
  16813. if (rigPostProcess) {
  16814. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16815. if (isPass) {
  16816. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16817. cam.isIntermediate = this._postProcesses.length === 0;
  16818. }
  16819. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16820. rigPostProcess.markTextureDirty();
  16821. }
  16822. else {
  16823. cam._postProcesses = this._postProcesses.slice(0);
  16824. }
  16825. }
  16826. };
  16827. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16828. if (insertAt === void 0) { insertAt = null; }
  16829. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16830. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16831. return 0;
  16832. }
  16833. if (insertAt == null || insertAt < 0) {
  16834. this._postProcesses.push(postProcess);
  16835. }
  16836. else {
  16837. this._postProcesses.splice(insertAt, 0, postProcess);
  16838. }
  16839. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16840. return this._postProcesses.indexOf(postProcess);
  16841. };
  16842. Camera.prototype.detachPostProcess = function (postProcess) {
  16843. var idx = this._postProcesses.indexOf(postProcess);
  16844. if (idx !== -1) {
  16845. this._postProcesses.splice(idx, 1);
  16846. }
  16847. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16848. };
  16849. Camera.prototype.getWorldMatrix = function () {
  16850. if (!this._worldMatrix) {
  16851. this._worldMatrix = BABYLON.Matrix.Identity();
  16852. }
  16853. var viewMatrix = this.getViewMatrix();
  16854. viewMatrix.invertToRef(this._worldMatrix);
  16855. return this._worldMatrix;
  16856. };
  16857. Camera.prototype._getViewMatrix = function () {
  16858. return BABYLON.Matrix.Identity();
  16859. };
  16860. Camera.prototype.getViewMatrix = function (force) {
  16861. if (!force && this._isSynchronizedViewMatrix()) {
  16862. return this._computedViewMatrix;
  16863. }
  16864. this.updateCache();
  16865. this._computedViewMatrix = this._getViewMatrix();
  16866. this._currentRenderId = this.getScene().getRenderId();
  16867. this._refreshFrustumPlanes = true;
  16868. if (!this.parent || !this.parent.getWorldMatrix) {
  16869. this._globalPosition.copyFrom(this.position);
  16870. }
  16871. else {
  16872. if (!this._worldMatrix) {
  16873. this._worldMatrix = BABYLON.Matrix.Identity();
  16874. }
  16875. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16876. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16877. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16878. this._computedViewMatrix.invert();
  16879. this._markSyncedWithParent();
  16880. }
  16881. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16882. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16883. }
  16884. this.onViewMatrixChangedObservable.notifyObservers(this);
  16885. return this._computedViewMatrix;
  16886. };
  16887. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16888. this._doNotComputeProjectionMatrix = true;
  16889. if (projection !== undefined) {
  16890. this._projectionMatrix = projection;
  16891. }
  16892. };
  16893. ;
  16894. Camera.prototype.unfreezeProjectionMatrix = function () {
  16895. this._doNotComputeProjectionMatrix = false;
  16896. };
  16897. ;
  16898. Camera.prototype.getProjectionMatrix = function (force) {
  16899. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16900. return this._projectionMatrix;
  16901. }
  16902. // Cache
  16903. this._cache.mode = this.mode;
  16904. this._cache.minZ = this.minZ;
  16905. this._cache.maxZ = this.maxZ;
  16906. // Matrix
  16907. this._refreshFrustumPlanes = true;
  16908. var engine = this.getEngine();
  16909. var scene = this.getScene();
  16910. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16911. this._cache.fov = this.fov;
  16912. this._cache.fovMode = this.fovMode;
  16913. this._cache.aspectRatio = engine.getAspectRatio(this);
  16914. if (this.minZ <= 0) {
  16915. this.minZ = 0.1;
  16916. }
  16917. if (scene.useRightHandedSystem) {
  16918. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16919. }
  16920. else {
  16921. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16922. }
  16923. }
  16924. else {
  16925. var halfWidth = engine.getRenderWidth() / 2.0;
  16926. var halfHeight = engine.getRenderHeight() / 2.0;
  16927. if (scene.useRightHandedSystem) {
  16928. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16929. }
  16930. else {
  16931. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16932. }
  16933. this._cache.orthoLeft = this.orthoLeft;
  16934. this._cache.orthoRight = this.orthoRight;
  16935. this._cache.orthoBottom = this.orthoBottom;
  16936. this._cache.orthoTop = this.orthoTop;
  16937. this._cache.renderWidth = engine.getRenderWidth();
  16938. this._cache.renderHeight = engine.getRenderHeight();
  16939. }
  16940. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16941. return this._projectionMatrix;
  16942. };
  16943. Camera.prototype.getTranformationMatrix = function () {
  16944. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16945. return this._transformMatrix;
  16946. };
  16947. Camera.prototype.updateFrustumPlanes = function () {
  16948. if (!this._refreshFrustumPlanes) {
  16949. return;
  16950. }
  16951. this.getTranformationMatrix();
  16952. if (!this._frustumPlanes) {
  16953. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16954. }
  16955. else {
  16956. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16957. }
  16958. this._refreshFrustumPlanes = false;
  16959. };
  16960. Camera.prototype.isInFrustum = function (target) {
  16961. this.updateFrustumPlanes();
  16962. return target.isInFrustum(this._frustumPlanes);
  16963. };
  16964. Camera.prototype.isCompletelyInFrustum = function (target) {
  16965. this.updateFrustumPlanes();
  16966. return target.isCompletelyInFrustum(this._frustumPlanes);
  16967. };
  16968. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16969. if (length === void 0) { length = 100; }
  16970. if (!transform) {
  16971. transform = this.getWorldMatrix();
  16972. }
  16973. if (!origin) {
  16974. origin = this.position;
  16975. }
  16976. var forward = new BABYLON.Vector3(0, 0, 1);
  16977. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16978. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16979. return new BABYLON.Ray(origin, direction, length);
  16980. };
  16981. Camera.prototype.dispose = function () {
  16982. // Observables
  16983. this.onViewMatrixChangedObservable.clear();
  16984. this.onProjectionMatrixChangedObservable.clear();
  16985. this.onAfterCheckInputsObservable.clear();
  16986. this.onRestoreStateObservable.clear();
  16987. // Inputs
  16988. if (this.inputs) {
  16989. this.inputs.clear();
  16990. }
  16991. // Animations
  16992. this.getScene().stopAnimation(this);
  16993. // Remove from scene
  16994. this.getScene().removeCamera(this);
  16995. while (this._rigCameras.length > 0) {
  16996. var camera = this._rigCameras.pop();
  16997. if (camera) {
  16998. camera.dispose();
  16999. }
  17000. }
  17001. // Postprocesses
  17002. if (this._rigPostProcess) {
  17003. this._rigPostProcess.dispose(this);
  17004. this._rigPostProcess = null;
  17005. this._postProcesses = [];
  17006. }
  17007. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17008. this._rigPostProcess = null;
  17009. this._postProcesses = [];
  17010. }
  17011. else {
  17012. var i = this._postProcesses.length;
  17013. while (--i >= 0) {
  17014. this._postProcesses[i].dispose(this);
  17015. }
  17016. }
  17017. // Render targets
  17018. var i = this.customRenderTargets.length;
  17019. while (--i >= 0) {
  17020. this.customRenderTargets[i].dispose();
  17021. }
  17022. this.customRenderTargets = [];
  17023. // Active Meshes
  17024. this._activeMeshes.dispose();
  17025. _super.prototype.dispose.call(this);
  17026. };
  17027. Object.defineProperty(Camera.prototype, "leftCamera", {
  17028. // ---- Camera rigs section ----
  17029. get: function () {
  17030. if (this._rigCameras.length < 1) {
  17031. return null;
  17032. }
  17033. return this._rigCameras[0];
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(Camera.prototype, "rightCamera", {
  17039. get: function () {
  17040. if (this._rigCameras.length < 2) {
  17041. return null;
  17042. }
  17043. return this._rigCameras[1];
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Camera.prototype.getLeftTarget = function () {
  17049. if (this._rigCameras.length < 1) {
  17050. return null;
  17051. }
  17052. return this._rigCameras[0].getTarget();
  17053. };
  17054. Camera.prototype.getRightTarget = function () {
  17055. if (this._rigCameras.length < 2) {
  17056. return null;
  17057. }
  17058. return this._rigCameras[1].getTarget();
  17059. };
  17060. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17061. if (this.cameraRigMode === mode) {
  17062. return;
  17063. }
  17064. while (this._rigCameras.length > 0) {
  17065. var camera = this._rigCameras.pop();
  17066. if (camera) {
  17067. camera.dispose();
  17068. }
  17069. }
  17070. this.cameraRigMode = mode;
  17071. this._cameraRigParams = {};
  17072. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17073. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17074. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17075. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17076. // create the rig cameras, unless none
  17077. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17078. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17079. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17080. if (leftCamera && rightCamera) {
  17081. this._rigCameras.push(leftCamera);
  17082. this._rigCameras.push(rightCamera);
  17083. }
  17084. }
  17085. switch (this.cameraRigMode) {
  17086. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17087. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17088. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17089. break;
  17090. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17091. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17092. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17093. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17094. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17095. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17096. break;
  17097. case Camera.RIG_MODE_VR:
  17098. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17099. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17100. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17101. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17102. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17103. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17104. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17105. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17106. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17107. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17108. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17109. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17110. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17111. if (metrics.compensateDistortion) {
  17112. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17113. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17114. }
  17115. break;
  17116. case Camera.RIG_MODE_WEBVR:
  17117. if (rigParams.vrDisplay) {
  17118. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17119. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17120. //Left eye
  17121. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17122. this._rigCameras[0].setCameraRigParameter("left", true);
  17123. //leaving this for future reference
  17124. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17125. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17126. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17127. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17128. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17129. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17130. this._rigCameras[0].parent = this;
  17131. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17132. //Right eye
  17133. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17134. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17135. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17136. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17137. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17138. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17139. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17140. this._rigCameras[1].parent = this;
  17141. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17142. if (Camera.UseAlternateWebVRRendering) {
  17143. this._rigCameras[1]._skipRendering = true;
  17144. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17145. }
  17146. }
  17147. break;
  17148. }
  17149. this._cascadePostProcessesToRigCams();
  17150. this.update();
  17151. };
  17152. Camera.prototype._getVRProjectionMatrix = function () {
  17153. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17154. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17155. return this._projectionMatrix;
  17156. };
  17157. Camera.prototype._updateCameraRotationMatrix = function () {
  17158. //Here for WebVR
  17159. };
  17160. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17161. //Here for WebVR
  17162. };
  17163. /**
  17164. * This function MUST be overwritten by the different WebVR cameras available.
  17165. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17166. */
  17167. Camera.prototype._getWebVRProjectionMatrix = function () {
  17168. return BABYLON.Matrix.Identity();
  17169. };
  17170. /**
  17171. * This function MUST be overwritten by the different WebVR cameras available.
  17172. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17173. */
  17174. Camera.prototype._getWebVRViewMatrix = function () {
  17175. return BABYLON.Matrix.Identity();
  17176. };
  17177. Camera.prototype.setCameraRigParameter = function (name, value) {
  17178. if (!this._cameraRigParams) {
  17179. this._cameraRigParams = {};
  17180. }
  17181. this._cameraRigParams[name] = value;
  17182. //provisionnally:
  17183. if (name === "interaxialDistance") {
  17184. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17185. }
  17186. };
  17187. /**
  17188. * needs to be overridden by children so sub has required properties to be copied
  17189. */
  17190. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17191. return null;
  17192. };
  17193. /**
  17194. * May need to be overridden by children
  17195. */
  17196. Camera.prototype._updateRigCameras = function () {
  17197. for (var i = 0; i < this._rigCameras.length; i++) {
  17198. this._rigCameras[i].minZ = this.minZ;
  17199. this._rigCameras[i].maxZ = this.maxZ;
  17200. this._rigCameras[i].fov = this.fov;
  17201. }
  17202. // only update viewport when ANAGLYPH
  17203. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17204. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17205. }
  17206. };
  17207. Camera.prototype._setupInputs = function () {
  17208. };
  17209. Camera.prototype.serialize = function () {
  17210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17211. // Type
  17212. serializationObject.type = this.getClassName();
  17213. // Parent
  17214. if (this.parent) {
  17215. serializationObject.parentId = this.parent.id;
  17216. }
  17217. if (this.inputs) {
  17218. this.inputs.serialize(serializationObject);
  17219. }
  17220. // Animations
  17221. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17222. serializationObject.ranges = this.serializeAnimationRanges();
  17223. return serializationObject;
  17224. };
  17225. Camera.prototype.clone = function (name) {
  17226. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17227. };
  17228. Camera.prototype.getDirection = function (localAxis) {
  17229. var result = BABYLON.Vector3.Zero();
  17230. this.getDirectionToRef(localAxis, result);
  17231. return result;
  17232. };
  17233. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17234. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17235. };
  17236. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17237. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17238. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17239. switch (type) {
  17240. case "ArcRotateCamera":
  17241. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17242. case "DeviceOrientationCamera":
  17243. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17244. case "FollowCamera":
  17245. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17246. case "ArcFollowCamera":
  17247. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17248. case "GamepadCamera":
  17249. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17250. case "TouchCamera":
  17251. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17252. case "VirtualJoysticksCamera":
  17253. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17254. case "WebVRFreeCamera":
  17255. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17256. case "WebVRGamepadCamera":
  17257. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17258. case "VRDeviceOrientationFreeCamera":
  17259. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17260. case "VRDeviceOrientationGamepadCamera":
  17261. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17262. case "AnaglyphArcRotateCamera":
  17263. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17264. case "AnaglyphFreeCamera":
  17265. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17266. case "AnaglyphGamepadCamera":
  17267. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17268. case "AnaglyphUniversalCamera":
  17269. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17270. case "StereoscopicArcRotateCamera":
  17271. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17272. case "StereoscopicFreeCamera":
  17273. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17274. case "StereoscopicGamepadCamera":
  17275. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17276. case "StereoscopicUniversalCamera":
  17277. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17278. case "FreeCamera":// Forcing Universal here
  17279. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17280. default:// Universal Camera is the default value
  17281. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17282. }
  17283. };
  17284. Camera.prototype.computeWorldMatrix = function () {
  17285. return this.getWorldMatrix();
  17286. };
  17287. Camera.Parse = function (parsedCamera, scene) {
  17288. var type = parsedCamera.type;
  17289. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17290. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17291. // Parent
  17292. if (parsedCamera.parentId) {
  17293. camera._waitingParentId = parsedCamera.parentId;
  17294. }
  17295. //If camera has an input manager, let it parse inputs settings
  17296. if (camera.inputs) {
  17297. camera.inputs.parse(parsedCamera);
  17298. camera._setupInputs();
  17299. }
  17300. if (camera.setPosition) {
  17301. camera.position.copyFromFloats(0, 0, 0);
  17302. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17303. }
  17304. // Target
  17305. if (parsedCamera.target) {
  17306. if (camera.setTarget) {
  17307. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17308. }
  17309. }
  17310. // Apply 3d rig, when found
  17311. if (parsedCamera.cameraRigMode) {
  17312. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17313. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17314. }
  17315. // Animations
  17316. if (parsedCamera.animations) {
  17317. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17318. var parsedAnimation = parsedCamera.animations[animationIndex];
  17319. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17320. }
  17321. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17322. }
  17323. if (parsedCamera.autoAnimate) {
  17324. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17325. }
  17326. return camera;
  17327. };
  17328. // Statics
  17329. Camera._PERSPECTIVE_CAMERA = 0;
  17330. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17331. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17332. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17333. Camera._RIG_MODE_NONE = 0;
  17334. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17335. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17336. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17337. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17338. Camera._RIG_MODE_VR = 20;
  17339. Camera._RIG_MODE_WEBVR = 21;
  17340. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17341. Camera.UseAlternateWebVRRendering = false;
  17342. __decorate([
  17343. BABYLON.serializeAsVector3()
  17344. ], Camera.prototype, "position", void 0);
  17345. __decorate([
  17346. BABYLON.serializeAsVector3()
  17347. ], Camera.prototype, "upVector", void 0);
  17348. __decorate([
  17349. BABYLON.serialize()
  17350. ], Camera.prototype, "orthoLeft", void 0);
  17351. __decorate([
  17352. BABYLON.serialize()
  17353. ], Camera.prototype, "orthoRight", void 0);
  17354. __decorate([
  17355. BABYLON.serialize()
  17356. ], Camera.prototype, "orthoBottom", void 0);
  17357. __decorate([
  17358. BABYLON.serialize()
  17359. ], Camera.prototype, "orthoTop", void 0);
  17360. __decorate([
  17361. BABYLON.serialize()
  17362. ], Camera.prototype, "fov", void 0);
  17363. __decorate([
  17364. BABYLON.serialize()
  17365. ], Camera.prototype, "minZ", void 0);
  17366. __decorate([
  17367. BABYLON.serialize()
  17368. ], Camera.prototype, "maxZ", void 0);
  17369. __decorate([
  17370. BABYLON.serialize()
  17371. ], Camera.prototype, "inertia", void 0);
  17372. __decorate([
  17373. BABYLON.serialize()
  17374. ], Camera.prototype, "mode", void 0);
  17375. __decorate([
  17376. BABYLON.serialize()
  17377. ], Camera.prototype, "layerMask", void 0);
  17378. __decorate([
  17379. BABYLON.serialize()
  17380. ], Camera.prototype, "fovMode", void 0);
  17381. __decorate([
  17382. BABYLON.serialize()
  17383. ], Camera.prototype, "cameraRigMode", void 0);
  17384. __decorate([
  17385. BABYLON.serialize()
  17386. ], Camera.prototype, "interaxialDistance", void 0);
  17387. __decorate([
  17388. BABYLON.serialize()
  17389. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17390. return Camera;
  17391. }(BABYLON.Node));
  17392. BABYLON.Camera = Camera;
  17393. })(BABYLON || (BABYLON = {}));
  17394. //# sourceMappingURL=babylon.camera.js.map
  17395. var BABYLON;
  17396. (function (BABYLON) {
  17397. var RenderingManager = /** @class */ (function () {
  17398. function RenderingManager(scene) {
  17399. this._renderingGroups = new Array();
  17400. this._autoClearDepthStencil = {};
  17401. this._customOpaqueSortCompareFn = {};
  17402. this._customAlphaTestSortCompareFn = {};
  17403. this._customTransparentSortCompareFn = {};
  17404. this._renderinGroupInfo = null;
  17405. this._scene = scene;
  17406. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17407. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17408. }
  17409. }
  17410. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17411. if (depth === void 0) { depth = true; }
  17412. if (stencil === void 0) { stencil = true; }
  17413. if (this._depthStencilBufferAlreadyCleaned) {
  17414. return;
  17415. }
  17416. this._scene.getEngine().clear(null, false, depth, stencil);
  17417. this._depthStencilBufferAlreadyCleaned = true;
  17418. };
  17419. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17420. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17421. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17422. var info = null;
  17423. if (observable) {
  17424. if (!this._renderinGroupInfo) {
  17425. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17426. }
  17427. info = this._renderinGroupInfo;
  17428. info.scene = this._scene;
  17429. info.camera = this._scene.activeCamera;
  17430. }
  17431. // Dispatch sprites
  17432. if (renderSprites) {
  17433. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17434. var manager = this._scene.spriteManagers[index];
  17435. this.dispatchSprites(manager);
  17436. }
  17437. }
  17438. // Render
  17439. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17440. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17441. var renderingGroup = this._renderingGroups[index];
  17442. if (!renderingGroup && !observable)
  17443. continue;
  17444. var renderingGroupMask = 0;
  17445. // Fire PRECLEAR stage
  17446. if (observable && info) {
  17447. renderingGroupMask = Math.pow(2, index);
  17448. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17449. info.renderingGroupId = index;
  17450. observable.notifyObservers(info, renderingGroupMask);
  17451. }
  17452. // Clear depth/stencil if needed
  17453. if (RenderingManager.AUTOCLEAR) {
  17454. var autoClear = this._autoClearDepthStencil[index];
  17455. if (autoClear && autoClear.autoClear) {
  17456. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17457. }
  17458. }
  17459. if (observable && info) {
  17460. // Fire PREOPAQUE stage
  17461. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17462. observable.notifyObservers(info, renderingGroupMask);
  17463. // Fire PRETRANSPARENT stage
  17464. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17465. observable.notifyObservers(info, renderingGroupMask);
  17466. }
  17467. if (renderingGroup)
  17468. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17469. // Fire POSTTRANSPARENT stage
  17470. if (observable && info) {
  17471. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17472. observable.notifyObservers(info, renderingGroupMask);
  17473. }
  17474. }
  17475. };
  17476. RenderingManager.prototype.reset = function () {
  17477. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17478. var renderingGroup = this._renderingGroups[index];
  17479. if (renderingGroup) {
  17480. renderingGroup.prepare();
  17481. }
  17482. }
  17483. };
  17484. RenderingManager.prototype.dispose = function () {
  17485. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17486. var renderingGroup = this._renderingGroups[index];
  17487. if (renderingGroup) {
  17488. renderingGroup.dispose();
  17489. }
  17490. }
  17491. this._renderingGroups.length = 0;
  17492. };
  17493. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17494. if (!this._renderingGroups[renderingGroupId]) {
  17495. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17496. }
  17497. };
  17498. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17499. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17500. this._prepareRenderingGroup(renderingGroupId);
  17501. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17502. };
  17503. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17504. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17505. this._prepareRenderingGroup(renderingGroupId);
  17506. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17507. };
  17508. RenderingManager.prototype.dispatch = function (subMesh) {
  17509. var mesh = subMesh.getMesh();
  17510. var renderingGroupId = mesh.renderingGroupId || 0;
  17511. this._prepareRenderingGroup(renderingGroupId);
  17512. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17513. };
  17514. /**
  17515. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17516. * This allowed control for front to back rendering or reversly depending of the special needs.
  17517. *
  17518. * @param renderingGroupId The rendering group id corresponding to its index
  17519. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17520. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17521. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17522. */
  17523. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17524. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17525. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17526. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17527. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17528. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17529. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17530. if (this._renderingGroups[renderingGroupId]) {
  17531. var group = this._renderingGroups[renderingGroupId];
  17532. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17533. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17534. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17535. }
  17536. };
  17537. /**
  17538. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17539. *
  17540. * @param renderingGroupId The rendering group id corresponding to its index
  17541. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17542. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17543. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17544. */
  17545. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17546. if (depth === void 0) { depth = true; }
  17547. if (stencil === void 0) { stencil = true; }
  17548. this._autoClearDepthStencil[renderingGroupId] = {
  17549. autoClear: autoClearDepthStencil,
  17550. depth: depth,
  17551. stencil: stencil
  17552. };
  17553. };
  17554. /**
  17555. * The max id used for rendering groups (not included)
  17556. */
  17557. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17558. /**
  17559. * The min id used for rendering groups (included)
  17560. */
  17561. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17562. /**
  17563. * Used to globally prevent autoclearing scenes.
  17564. */
  17565. RenderingManager.AUTOCLEAR = true;
  17566. return RenderingManager;
  17567. }());
  17568. BABYLON.RenderingManager = RenderingManager;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.renderingManager.js.map
  17571. var BABYLON;
  17572. (function (BABYLON) {
  17573. var RenderingGroup = /** @class */ (function () {
  17574. /**
  17575. * Creates a new rendering group.
  17576. * @param index The rendering group index
  17577. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17578. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17579. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17580. */
  17581. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17582. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17583. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17584. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17585. this.index = index;
  17586. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17587. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17588. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17589. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17590. this._particleSystems = new BABYLON.SmartArray(256);
  17591. this._spriteManagers = new BABYLON.SmartArray(256);
  17592. this._edgesRenderers = new BABYLON.SmartArray(16);
  17593. this._scene = scene;
  17594. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17595. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17596. this.transparentSortCompareFn = transparentSortCompareFn;
  17597. }
  17598. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17599. /**
  17600. * Set the opaque sort comparison function.
  17601. * If null the sub meshes will be render in the order they were created
  17602. */
  17603. set: function (value) {
  17604. this._opaqueSortCompareFn = value;
  17605. if (value) {
  17606. this._renderOpaque = this.renderOpaqueSorted;
  17607. }
  17608. else {
  17609. this._renderOpaque = RenderingGroup.renderUnsorted;
  17610. }
  17611. },
  17612. enumerable: true,
  17613. configurable: true
  17614. });
  17615. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17616. /**
  17617. * Set the alpha test sort comparison function.
  17618. * If null the sub meshes will be render in the order they were created
  17619. */
  17620. set: function (value) {
  17621. this._alphaTestSortCompareFn = value;
  17622. if (value) {
  17623. this._renderAlphaTest = this.renderAlphaTestSorted;
  17624. }
  17625. else {
  17626. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17627. }
  17628. },
  17629. enumerable: true,
  17630. configurable: true
  17631. });
  17632. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17633. /**
  17634. * Set the transparent sort comparison function.
  17635. * If null the sub meshes will be render in the order they were created
  17636. */
  17637. set: function (value) {
  17638. if (value) {
  17639. this._transparentSortCompareFn = value;
  17640. }
  17641. else {
  17642. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17643. }
  17644. this._renderTransparent = this.renderTransparentSorted;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. /**
  17650. * Render all the sub meshes contained in the group.
  17651. * @param customRenderFunction Used to override the default render behaviour of the group.
  17652. * @returns true if rendered some submeshes.
  17653. */
  17654. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17655. if (customRenderFunction) {
  17656. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17657. return;
  17658. }
  17659. var engine = this._scene.getEngine();
  17660. // Depth only
  17661. if (this._depthOnlySubMeshes.length !== 0) {
  17662. engine.setAlphaTesting(true);
  17663. engine.setColorWrite(false);
  17664. this._renderAlphaTest(this._depthOnlySubMeshes);
  17665. engine.setAlphaTesting(false);
  17666. engine.setColorWrite(true);
  17667. }
  17668. // Opaque
  17669. if (this._opaqueSubMeshes.length !== 0) {
  17670. this._renderOpaque(this._opaqueSubMeshes);
  17671. }
  17672. // Alpha test
  17673. if (this._alphaTestSubMeshes.length !== 0) {
  17674. engine.setAlphaTesting(true);
  17675. this._renderAlphaTest(this._alphaTestSubMeshes);
  17676. engine.setAlphaTesting(false);
  17677. }
  17678. var stencilState = engine.getStencilBuffer();
  17679. engine.setStencilBuffer(false);
  17680. // Sprites
  17681. if (renderSprites) {
  17682. this._renderSprites();
  17683. }
  17684. // Particles
  17685. if (renderParticles) {
  17686. this._renderParticles(activeMeshes);
  17687. }
  17688. if (this.onBeforeTransparentRendering) {
  17689. this.onBeforeTransparentRendering();
  17690. }
  17691. // Transparent
  17692. if (this._transparentSubMeshes.length !== 0) {
  17693. this._renderTransparent(this._transparentSubMeshes);
  17694. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17695. }
  17696. // Set back stencil to false in case it changes before the edge renderer.
  17697. engine.setStencilBuffer(false);
  17698. // Edges
  17699. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17700. this._edgesRenderers.data[edgesRendererIndex].render();
  17701. }
  17702. // Restore Stencil state.
  17703. engine.setStencilBuffer(stencilState);
  17704. };
  17705. /**
  17706. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17707. * @param subMeshes The submeshes to render
  17708. */
  17709. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17710. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17711. };
  17712. /**
  17713. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17714. * @param subMeshes The submeshes to render
  17715. */
  17716. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17717. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17718. };
  17719. /**
  17720. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17721. * @param subMeshes The submeshes to render
  17722. */
  17723. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17724. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17725. };
  17726. /**
  17727. * Renders the submeshes in a specified order.
  17728. * @param subMeshes The submeshes to sort before render
  17729. * @param sortCompareFn The comparison function use to sort
  17730. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17731. * @param transparent Specifies to activate blending if true
  17732. */
  17733. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17734. var subIndex = 0;
  17735. var subMesh;
  17736. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17737. for (; subIndex < subMeshes.length; subIndex++) {
  17738. subMesh = subMeshes.data[subIndex];
  17739. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17740. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17741. }
  17742. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17743. if (sortCompareFn) {
  17744. sortedArray.sort(sortCompareFn);
  17745. }
  17746. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17747. subMesh = sortedArray[subIndex];
  17748. if (transparent) {
  17749. var material = subMesh.getMaterial();
  17750. if (material && material.needDepthPrePass) {
  17751. var engine = material.getScene().getEngine();
  17752. engine.setColorWrite(false);
  17753. engine.setAlphaTesting(true);
  17754. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17755. subMesh.render(false);
  17756. engine.setAlphaTesting(false);
  17757. engine.setColorWrite(true);
  17758. }
  17759. }
  17760. subMesh.render(transparent);
  17761. }
  17762. };
  17763. /**
  17764. * Renders the submeshes in the order they were dispatched (no sort applied).
  17765. * @param subMeshes The submeshes to render
  17766. */
  17767. RenderingGroup.renderUnsorted = function (subMeshes) {
  17768. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17769. var submesh = subMeshes.data[subIndex];
  17770. submesh.render(false);
  17771. }
  17772. };
  17773. /**
  17774. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17775. * are rendered back to front if in the same alpha index.
  17776. *
  17777. * @param a The first submesh
  17778. * @param b The second submesh
  17779. * @returns The result of the comparison
  17780. */
  17781. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17782. // Alpha index first
  17783. if (a._alphaIndex > b._alphaIndex) {
  17784. return 1;
  17785. }
  17786. if (a._alphaIndex < b._alphaIndex) {
  17787. return -1;
  17788. }
  17789. // Then distance to camera
  17790. return RenderingGroup.backToFrontSortCompare(a, b);
  17791. };
  17792. /**
  17793. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17794. * are rendered back to front.
  17795. *
  17796. * @param a The first submesh
  17797. * @param b The second submesh
  17798. * @returns The result of the comparison
  17799. */
  17800. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17801. // Then distance to camera
  17802. if (a._distanceToCamera < b._distanceToCamera) {
  17803. return 1;
  17804. }
  17805. if (a._distanceToCamera > b._distanceToCamera) {
  17806. return -1;
  17807. }
  17808. return 0;
  17809. };
  17810. /**
  17811. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17812. * are rendered front to back (prevent overdraw).
  17813. *
  17814. * @param a The first submesh
  17815. * @param b The second submesh
  17816. * @returns The result of the comparison
  17817. */
  17818. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17819. // Then distance to camera
  17820. if (a._distanceToCamera < b._distanceToCamera) {
  17821. return -1;
  17822. }
  17823. if (a._distanceToCamera > b._distanceToCamera) {
  17824. return 1;
  17825. }
  17826. return 0;
  17827. };
  17828. /**
  17829. * Resets the different lists of submeshes to prepare a new frame.
  17830. */
  17831. RenderingGroup.prototype.prepare = function () {
  17832. this._opaqueSubMeshes.reset();
  17833. this._transparentSubMeshes.reset();
  17834. this._alphaTestSubMeshes.reset();
  17835. this._depthOnlySubMeshes.reset();
  17836. this._particleSystems.reset();
  17837. this._spriteManagers.reset();
  17838. this._edgesRenderers.reset();
  17839. };
  17840. RenderingGroup.prototype.dispose = function () {
  17841. this._opaqueSubMeshes.dispose();
  17842. this._transparentSubMeshes.dispose();
  17843. this._alphaTestSubMeshes.dispose();
  17844. this._depthOnlySubMeshes.dispose();
  17845. this._particleSystems.dispose();
  17846. this._spriteManagers.dispose();
  17847. this._edgesRenderers.dispose();
  17848. };
  17849. /**
  17850. * Inserts the submesh in its correct queue depending on its material.
  17851. * @param subMesh The submesh to dispatch
  17852. */
  17853. RenderingGroup.prototype.dispatch = function (subMesh) {
  17854. var material = subMesh.getMaterial();
  17855. var mesh = subMesh.getMesh();
  17856. if (!material) {
  17857. return;
  17858. }
  17859. if (material.needAlphaBlendingForMesh(mesh)) {
  17860. this._transparentSubMeshes.push(subMesh);
  17861. }
  17862. else if (material.needAlphaTesting()) {
  17863. if (material.needDepthPrePass) {
  17864. this._depthOnlySubMeshes.push(subMesh);
  17865. }
  17866. this._alphaTestSubMeshes.push(subMesh);
  17867. }
  17868. else {
  17869. if (material.needDepthPrePass) {
  17870. this._depthOnlySubMeshes.push(subMesh);
  17871. }
  17872. this._opaqueSubMeshes.push(subMesh); // Opaque
  17873. }
  17874. if (mesh._edgesRenderer) {
  17875. this._edgesRenderers.push(mesh._edgesRenderer);
  17876. }
  17877. };
  17878. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17879. this._spriteManagers.push(spriteManager);
  17880. };
  17881. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17882. this._particleSystems.push(particleSystem);
  17883. };
  17884. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17885. if (this._particleSystems.length === 0) {
  17886. return;
  17887. }
  17888. // Particles
  17889. var activeCamera = this._scene.activeCamera;
  17890. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17891. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17892. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17893. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17894. continue;
  17895. }
  17896. var emitter = particleSystem.emitter;
  17897. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17898. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17899. }
  17900. }
  17901. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17902. };
  17903. RenderingGroup.prototype._renderSprites = function () {
  17904. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17905. return;
  17906. }
  17907. // Sprites
  17908. var activeCamera = this._scene.activeCamera;
  17909. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17910. for (var id = 0; id < this._spriteManagers.length; id++) {
  17911. var spriteManager = this._spriteManagers.data[id];
  17912. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17913. spriteManager.render();
  17914. }
  17915. }
  17916. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17917. };
  17918. return RenderingGroup;
  17919. }());
  17920. BABYLON.RenderingGroup = RenderingGroup;
  17921. })(BABYLON || (BABYLON = {}));
  17922. //# sourceMappingURL=babylon.renderingGroup.js.map
  17923. var BABYLON;
  17924. (function (BABYLON) {
  17925. var ClickInfo = /** @class */ (function () {
  17926. function ClickInfo() {
  17927. this._singleClick = false;
  17928. this._doubleClick = false;
  17929. this._hasSwiped = false;
  17930. this._ignore = false;
  17931. }
  17932. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17933. get: function () {
  17934. return this._singleClick;
  17935. },
  17936. set: function (b) {
  17937. this._singleClick = b;
  17938. },
  17939. enumerable: true,
  17940. configurable: true
  17941. });
  17942. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17943. get: function () {
  17944. return this._doubleClick;
  17945. },
  17946. set: function (b) {
  17947. this._doubleClick = b;
  17948. },
  17949. enumerable: true,
  17950. configurable: true
  17951. });
  17952. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17953. get: function () {
  17954. return this._hasSwiped;
  17955. },
  17956. set: function (b) {
  17957. this._hasSwiped = b;
  17958. },
  17959. enumerable: true,
  17960. configurable: true
  17961. });
  17962. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17963. get: function () {
  17964. return this._ignore;
  17965. },
  17966. set: function (b) {
  17967. this._ignore = b;
  17968. },
  17969. enumerable: true,
  17970. configurable: true
  17971. });
  17972. return ClickInfo;
  17973. }());
  17974. /**
  17975. * This class is used by the onRenderingGroupObservable
  17976. */
  17977. var RenderingGroupInfo = /** @class */ (function () {
  17978. function RenderingGroupInfo() {
  17979. }
  17980. /**
  17981. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17982. * This stage will be fired no matter what
  17983. */
  17984. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17985. /**
  17986. * Called before opaque object are rendered.
  17987. * This stage will be fired only if there's 3D Opaque content to render
  17988. */
  17989. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17990. /**
  17991. * Called after the opaque objects are rendered and before the transparent ones
  17992. * This stage will be fired only if there's 3D transparent content to render
  17993. */
  17994. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17995. /**
  17996. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17997. * This stage will be fired no matter what
  17998. */
  17999. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  18000. return RenderingGroupInfo;
  18001. }());
  18002. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18003. /**
  18004. * Represents a scene to be rendered by the engine.
  18005. * @see http://doc.babylonjs.com/page.php?p=21911
  18006. */
  18007. var Scene = /** @class */ (function () {
  18008. /**
  18009. * @constructor
  18010. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18011. */
  18012. function Scene(engine) {
  18013. // Members
  18014. this.autoClear = true;
  18015. this.autoClearDepthAndStencil = true;
  18016. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18017. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18018. this.forceWireframe = false;
  18019. this._forcePointsCloud = false;
  18020. this.forceShowBoundingBoxes = false;
  18021. this.animationsEnabled = true;
  18022. this.useConstantAnimationDeltaTime = false;
  18023. this.constantlyUpdateMeshUnderPointer = false;
  18024. this.hoverCursor = "pointer";
  18025. this.defaultCursor = "";
  18026. /**
  18027. * This is used to call preventDefault() on pointer down
  18028. * in order to block unwanted artifacts like system double clicks
  18029. */
  18030. this.preventDefaultOnPointerDown = true;
  18031. // Metadata
  18032. this.metadata = null;
  18033. /**
  18034. * An event triggered when the scene is disposed.
  18035. * @type {BABYLON.Observable}
  18036. */
  18037. this.onDisposeObservable = new BABYLON.Observable();
  18038. /**
  18039. * An event triggered before rendering the scene (right after animations and physics)
  18040. * @type {BABYLON.Observable}
  18041. */
  18042. this.onBeforeRenderObservable = new BABYLON.Observable();
  18043. /**
  18044. * An event triggered after rendering the scene
  18045. * @type {BABYLON.Observable}
  18046. */
  18047. this.onAfterRenderObservable = new BABYLON.Observable();
  18048. /**
  18049. * An event triggered before animating the scene
  18050. * @type {BABYLON.Observable}
  18051. */
  18052. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18053. /**
  18054. * An event triggered after animations processing
  18055. * @type {BABYLON.Observable}
  18056. */
  18057. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18058. /**
  18059. * An event triggered before draw calls are ready to be sent
  18060. * @type {BABYLON.Observable}
  18061. */
  18062. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18063. /**
  18064. * An event triggered after draw calls have been sent
  18065. * @type {BABYLON.Observable}
  18066. */
  18067. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18068. /**
  18069. * An event triggered when physic simulation is about to be run
  18070. * @type {BABYLON.Observable}
  18071. */
  18072. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18073. /**
  18074. * An event triggered when physic simulation has been done
  18075. * @type {BABYLON.Observable}
  18076. */
  18077. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18078. /**
  18079. * An event triggered when the scene is ready
  18080. * @type {BABYLON.Observable}
  18081. */
  18082. this.onReadyObservable = new BABYLON.Observable();
  18083. /**
  18084. * An event triggered before rendering a camera
  18085. * @type {BABYLON.Observable}
  18086. */
  18087. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18088. /**
  18089. * An event triggered after rendering a camera
  18090. * @type {BABYLON.Observable}
  18091. */
  18092. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18093. /**
  18094. * An event triggered when active meshes evaluation is about to start
  18095. * @type {BABYLON.Observable}
  18096. */
  18097. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18098. /**
  18099. * An event triggered when active meshes evaluation is done
  18100. * @type {BABYLON.Observable}
  18101. */
  18102. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18103. /**
  18104. * An event triggered when particles rendering is about to start
  18105. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18106. * @type {BABYLON.Observable}
  18107. */
  18108. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18109. /**
  18110. * An event triggered when particles rendering is done
  18111. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18112. * @type {BABYLON.Observable}
  18113. */
  18114. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18115. /**
  18116. * An event triggered when sprites rendering is about to start
  18117. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18118. * @type {BABYLON.Observable}
  18119. */
  18120. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18121. /**
  18122. * An event triggered when sprites rendering is done
  18123. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18124. * @type {BABYLON.Observable}
  18125. */
  18126. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18127. /**
  18128. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18129. * @type {BABYLON.Observable}
  18130. */
  18131. this.onDataLoadedObservable = new BABYLON.Observable();
  18132. /**
  18133. * An event triggered when a camera is created
  18134. * @type {BABYLON.Observable}
  18135. */
  18136. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18137. /**
  18138. * An event triggered when a camera is removed
  18139. * @type {BABYLON.Observable}
  18140. */
  18141. this.onCameraRemovedObservable = new BABYLON.Observable();
  18142. /**
  18143. * An event triggered when a light is created
  18144. * @type {BABYLON.Observable}
  18145. */
  18146. this.onNewLightAddedObservable = new BABYLON.Observable();
  18147. /**
  18148. * An event triggered when a light is removed
  18149. * @type {BABYLON.Observable}
  18150. */
  18151. this.onLightRemovedObservable = new BABYLON.Observable();
  18152. /**
  18153. * An event triggered when a geometry is created
  18154. * @type {BABYLON.Observable}
  18155. */
  18156. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18157. /**
  18158. * An event triggered when a geometry is removed
  18159. * @type {BABYLON.Observable}
  18160. */
  18161. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18162. /**
  18163. * An event triggered when a transform node is created
  18164. * @type {BABYLON.Observable}
  18165. */
  18166. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18167. /**
  18168. * An event triggered when a transform node is removed
  18169. * @type {BABYLON.Observable}
  18170. */
  18171. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18172. /**
  18173. * An event triggered when a mesh is created
  18174. * @type {BABYLON.Observable}
  18175. */
  18176. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18177. /**
  18178. * An event triggered when a mesh is removed
  18179. * @type {BABYLON.Observable}
  18180. */
  18181. this.onMeshRemovedObservable = new BABYLON.Observable();
  18182. /**
  18183. * An event triggered when render targets are about to be rendered
  18184. * Can happen multiple times per frame.
  18185. * @type {BABYLON.Observable}
  18186. */
  18187. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18188. /**
  18189. * An event triggered when render targets were rendered.
  18190. * Can happen multiple times per frame.
  18191. * @type {BABYLON.Observable}
  18192. */
  18193. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18194. /**
  18195. * An event triggered before calculating deterministic simulation step
  18196. * @type {BABYLON.Observable}
  18197. */
  18198. this.onBeforeStepObservable = new BABYLON.Observable();
  18199. /**
  18200. * An event triggered after calculating deterministic simulation step
  18201. * @type {BABYLON.Observable}
  18202. */
  18203. this.onAfterStepObservable = new BABYLON.Observable();
  18204. /**
  18205. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18206. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18207. * 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)
  18208. */
  18209. this.onRenderingGroupObservable = new BABYLON.Observable();
  18210. // Animations
  18211. this.animations = [];
  18212. /**
  18213. * 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).
  18214. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18215. */
  18216. this.onPrePointerObservable = new BABYLON.Observable();
  18217. /**
  18218. * Observable event triggered each time an input event is received from the rendering canvas
  18219. */
  18220. this.onPointerObservable = new BABYLON.Observable();
  18221. this._meshPickProceed = false;
  18222. this._currentPickResult = null;
  18223. this._previousPickResult = null;
  18224. this._totalPointersPressed = 0;
  18225. this._doubleClickOccured = false;
  18226. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18227. this.cameraToUseForPointers = null;
  18228. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18229. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18230. this._startingPointerTime = 0;
  18231. this._previousStartingPointerTime = 0;
  18232. // Deterministic lockstep
  18233. this._timeAccumulator = 0;
  18234. this._currentStepId = 0;
  18235. this._currentInternalStep = 0;
  18236. // Keyboard
  18237. /**
  18238. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18239. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18240. */
  18241. this.onPreKeyboardObservable = new BABYLON.Observable();
  18242. /**
  18243. * Observable event triggered each time an keyboard event is received from the hosting window
  18244. */
  18245. this.onKeyboardObservable = new BABYLON.Observable();
  18246. // Coordinate system
  18247. /**
  18248. * use right-handed coordinate system on this scene.
  18249. * @type {boolean}
  18250. */
  18251. this._useRightHandedSystem = false;
  18252. // Fog
  18253. this._fogEnabled = true;
  18254. this._fogMode = Scene.FOGMODE_NONE;
  18255. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18256. this.fogDensity = 0.1;
  18257. this.fogStart = 0;
  18258. this.fogEnd = 1000.0;
  18259. // Lights
  18260. /**
  18261. * is shadow enabled on this scene.
  18262. * @type {boolean}
  18263. */
  18264. this._shadowsEnabled = true;
  18265. /**
  18266. * is light enabled on this scene.
  18267. * @type {boolean}
  18268. */
  18269. this._lightsEnabled = true;
  18270. /**
  18271. * All of the lights added to this scene.
  18272. * @see BABYLON.Light
  18273. * @type {BABYLON.Light[]}
  18274. */
  18275. this.lights = new Array();
  18276. // Cameras
  18277. /** All of the cameras added to this scene. */
  18278. this.cameras = new Array();
  18279. /** All of the active cameras added to this scene. */
  18280. this.activeCameras = new Array();
  18281. // Meshes
  18282. /**
  18283. * All of the tranform nodes added to this scene.
  18284. * @see BABYLON.TransformNode
  18285. * @type {BABYLON.TransformNode[]}
  18286. */
  18287. this.transformNodes = new Array();
  18288. /**
  18289. * All of the (abstract) meshes added to this scene.
  18290. * @see BABYLON.AbstractMesh
  18291. * @type {BABYLON.AbstractMesh[]}
  18292. */
  18293. this.meshes = new Array();
  18294. // Geometries
  18295. this._geometries = new Array();
  18296. this.materials = new Array();
  18297. this.multiMaterials = new Array();
  18298. // Textures
  18299. this._texturesEnabled = true;
  18300. this.textures = new Array();
  18301. // Particles
  18302. this.particlesEnabled = true;
  18303. this.particleSystems = new Array();
  18304. // Sprites
  18305. this.spritesEnabled = true;
  18306. this.spriteManagers = new Array();
  18307. // Layers
  18308. this.layers = new Array();
  18309. this.highlightLayers = new Array();
  18310. // Skeletons
  18311. this._skeletonsEnabled = true;
  18312. this.skeletons = new Array();
  18313. // Morph targets
  18314. this.morphTargetManagers = new Array();
  18315. // Lens flares
  18316. this.lensFlaresEnabled = true;
  18317. this.lensFlareSystems = new Array();
  18318. // Collisions
  18319. this.collisionsEnabled = true;
  18320. /** Defines the gravity applied to this scene */
  18321. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18322. // Postprocesses
  18323. this.postProcesses = new Array();
  18324. this.postProcessesEnabled = true;
  18325. // Customs render targets
  18326. this.renderTargetsEnabled = true;
  18327. this.dumpNextRenderTargets = false;
  18328. this.customRenderTargets = new Array();
  18329. // Imported meshes
  18330. this.importedMeshesFiles = new Array();
  18331. // Probes
  18332. this.probesEnabled = true;
  18333. this.reflectionProbes = new Array();
  18334. this._actionManagers = new Array();
  18335. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18336. // Procedural textures
  18337. this.proceduralTexturesEnabled = true;
  18338. this._proceduralTextures = new Array();
  18339. this.soundTracks = new Array();
  18340. this._audioEnabled = true;
  18341. this._headphone = false;
  18342. // Performance counters
  18343. this._totalVertices = new BABYLON.PerfCounter();
  18344. this._activeIndices = new BABYLON.PerfCounter();
  18345. this._activeParticles = new BABYLON.PerfCounter();
  18346. this._activeBones = new BABYLON.PerfCounter();
  18347. this._animationTime = 0;
  18348. this.animationTimeScale = 1;
  18349. this._renderId = 0;
  18350. this._executeWhenReadyTimeoutId = -1;
  18351. this._intermediateRendering = false;
  18352. this._viewUpdateFlag = -1;
  18353. this._projectionUpdateFlag = -1;
  18354. this._alternateViewUpdateFlag = -1;
  18355. this._alternateProjectionUpdateFlag = -1;
  18356. this._toBeDisposed = new BABYLON.SmartArray(256);
  18357. this._pendingData = new Array();
  18358. this._isDisposed = false;
  18359. this._activeMeshes = new BABYLON.SmartArray(256);
  18360. this._processedMaterials = new BABYLON.SmartArray(256);
  18361. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18362. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18363. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18364. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18365. this._activeAnimatables = new Array();
  18366. this._transformMatrix = BABYLON.Matrix.Zero();
  18367. this._useAlternateCameraConfiguration = false;
  18368. this._alternateRendering = false;
  18369. this.requireLightSorting = false;
  18370. this._activeMeshesFrozen = false;
  18371. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18372. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18373. this._engine.scenes.push(this);
  18374. this._uid = null;
  18375. this._renderingManager = new BABYLON.RenderingManager(this);
  18376. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18377. if (BABYLON.OutlineRenderer) {
  18378. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18379. }
  18380. if (BABYLON.Tools.IsWindowObjectExist()) {
  18381. this.attachControl();
  18382. }
  18383. //simplification queue
  18384. if (BABYLON.SimplificationQueue) {
  18385. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18386. }
  18387. //collision coordinator initialization. For now legacy per default.
  18388. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18389. // Uniform Buffer
  18390. this._createUbo();
  18391. // Default Image processing definition.
  18392. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18393. }
  18394. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18395. /** The fog is deactivated */
  18396. get: function () {
  18397. return Scene._FOGMODE_NONE;
  18398. },
  18399. enumerable: true,
  18400. configurable: true
  18401. });
  18402. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18403. /** The fog density is following an exponential function */
  18404. get: function () {
  18405. return Scene._FOGMODE_EXP;
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18411. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18412. get: function () {
  18413. return Scene._FOGMODE_EXP2;
  18414. },
  18415. enumerable: true,
  18416. configurable: true
  18417. });
  18418. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18419. /** The fog density is following a linear function. */
  18420. get: function () {
  18421. return Scene._FOGMODE_LINEAR;
  18422. },
  18423. enumerable: true,
  18424. configurable: true
  18425. });
  18426. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18427. /**
  18428. * Texture used in all pbr material as the reflection texture.
  18429. * As in the majority of the scene they are the same (exception for multi room and so on),
  18430. * this is easier to reference from here than from all the materials.
  18431. */
  18432. get: function () {
  18433. return this._environmentTexture;
  18434. },
  18435. /**
  18436. * Texture used in all pbr material as the reflection texture.
  18437. * As in the majority of the scene they are the same (exception for multi room and so on),
  18438. * this is easier to set here than in all the materials.
  18439. */
  18440. set: function (value) {
  18441. if (this._environmentTexture === value) {
  18442. return;
  18443. }
  18444. this._environmentTexture = value;
  18445. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18451. /**
  18452. * Default image processing configuration used either in the rendering
  18453. * Forward main pass or through the imageProcessingPostProcess if present.
  18454. * As in the majority of the scene they are the same (exception for multi camera),
  18455. * this is easier to reference from here than from all the materials and post process.
  18456. *
  18457. * No setter as we it is a shared configuration, you can set the values instead.
  18458. */
  18459. get: function () {
  18460. return this._imageProcessingConfiguration;
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18466. get: function () {
  18467. return this._forcePointsCloud;
  18468. },
  18469. set: function (value) {
  18470. if (this._forcePointsCloud === value) {
  18471. return;
  18472. }
  18473. this._forcePointsCloud = value;
  18474. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. Object.defineProperty(Scene.prototype, "onDispose", {
  18480. /** A function to be executed when this scene is disposed. */
  18481. set: function (callback) {
  18482. if (this._onDisposeObserver) {
  18483. this.onDisposeObservable.remove(this._onDisposeObserver);
  18484. }
  18485. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18486. },
  18487. enumerable: true,
  18488. configurable: true
  18489. });
  18490. Object.defineProperty(Scene.prototype, "beforeRender", {
  18491. /** A function to be executed before rendering this scene */
  18492. set: function (callback) {
  18493. if (this._onBeforeRenderObserver) {
  18494. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18495. }
  18496. if (callback) {
  18497. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18498. }
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. Object.defineProperty(Scene.prototype, "afterRender", {
  18504. /** A function to be executed after rendering this scene */
  18505. set: function (callback) {
  18506. if (this._onAfterRenderObserver) {
  18507. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18508. }
  18509. if (callback) {
  18510. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18511. }
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18517. set: function (callback) {
  18518. if (this._onBeforeCameraRenderObserver) {
  18519. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18520. }
  18521. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18527. set: function (callback) {
  18528. if (this._onAfterCameraRenderObserver) {
  18529. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18530. }
  18531. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18537. get: function () {
  18538. if (!this._gamepadManager) {
  18539. this._gamepadManager = new BABYLON.GamepadManager(this);
  18540. }
  18541. return this._gamepadManager;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18547. get: function () {
  18548. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18549. },
  18550. enumerable: true,
  18551. configurable: true
  18552. });
  18553. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18554. get: function () {
  18555. return this._useRightHandedSystem;
  18556. },
  18557. set: function (value) {
  18558. if (this._useRightHandedSystem === value) {
  18559. return;
  18560. }
  18561. this._useRightHandedSystem = value;
  18562. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18563. },
  18564. enumerable: true,
  18565. configurable: true
  18566. });
  18567. Scene.prototype.setStepId = function (newStepId) {
  18568. this._currentStepId = newStepId;
  18569. };
  18570. ;
  18571. Scene.prototype.getStepId = function () {
  18572. return this._currentStepId;
  18573. };
  18574. ;
  18575. Scene.prototype.getInternalStep = function () {
  18576. return this._currentInternalStep;
  18577. };
  18578. ;
  18579. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18580. get: function () {
  18581. return this._fogEnabled;
  18582. },
  18583. /**
  18584. * is fog enabled on this scene.
  18585. */
  18586. set: function (value) {
  18587. if (this._fogEnabled === value) {
  18588. return;
  18589. }
  18590. this._fogEnabled = value;
  18591. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. Object.defineProperty(Scene.prototype, "fogMode", {
  18597. get: function () {
  18598. return this._fogMode;
  18599. },
  18600. set: function (value) {
  18601. if (this._fogMode === value) {
  18602. return;
  18603. }
  18604. this._fogMode = value;
  18605. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18606. },
  18607. enumerable: true,
  18608. configurable: true
  18609. });
  18610. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18611. get: function () {
  18612. return this._shadowsEnabled;
  18613. },
  18614. set: function (value) {
  18615. if (this._shadowsEnabled === value) {
  18616. return;
  18617. }
  18618. this._shadowsEnabled = value;
  18619. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18625. get: function () {
  18626. return this._lightsEnabled;
  18627. },
  18628. set: function (value) {
  18629. if (this._lightsEnabled === value) {
  18630. return;
  18631. }
  18632. this._lightsEnabled = value;
  18633. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18639. /** The default material used on meshes when no material is affected */
  18640. get: function () {
  18641. if (!this._defaultMaterial) {
  18642. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18643. }
  18644. return this._defaultMaterial;
  18645. },
  18646. /** The default material used on meshes when no material is affected */
  18647. set: function (value) {
  18648. this._defaultMaterial = value;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18654. get: function () {
  18655. return this._texturesEnabled;
  18656. },
  18657. set: function (value) {
  18658. if (this._texturesEnabled === value) {
  18659. return;
  18660. }
  18661. this._texturesEnabled = value;
  18662. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18668. get: function () {
  18669. return this._skeletonsEnabled;
  18670. },
  18671. set: function (value) {
  18672. if (this._skeletonsEnabled === value) {
  18673. return;
  18674. }
  18675. this._skeletonsEnabled = value;
  18676. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18682. get: function () {
  18683. if (!this._postProcessRenderPipelineManager) {
  18684. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18685. }
  18686. return this._postProcessRenderPipelineManager;
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18692. get: function () {
  18693. if (!this._mainSoundTrack) {
  18694. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18695. }
  18696. return this._mainSoundTrack;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18702. get: function () {
  18703. return this._alternateRendering;
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18709. get: function () {
  18710. return this._frustumPlanes;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(Scene.prototype, "debugLayer", {
  18716. // Properties
  18717. get: function () {
  18718. if (!this._debugLayer) {
  18719. this._debugLayer = new BABYLON.DebugLayer(this);
  18720. }
  18721. return this._debugLayer;
  18722. },
  18723. enumerable: true,
  18724. configurable: true
  18725. });
  18726. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18727. get: function () {
  18728. return this._workerCollisions;
  18729. },
  18730. set: function (enabled) {
  18731. if (!BABYLON.CollisionCoordinatorLegacy) {
  18732. return;
  18733. }
  18734. enabled = (enabled && !!Worker);
  18735. this._workerCollisions = enabled;
  18736. if (this.collisionCoordinator) {
  18737. this.collisionCoordinator.destroy();
  18738. }
  18739. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18740. this.collisionCoordinator.init(this);
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18746. get: function () {
  18747. return this._selectionOctree;
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18753. /**
  18754. * The mesh that is currently under the pointer.
  18755. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18756. */
  18757. get: function () {
  18758. return this._pointerOverMesh;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. Object.defineProperty(Scene.prototype, "pointerX", {
  18764. /**
  18765. * Current on-screen X position of the pointer
  18766. * @return {number} X position of the pointer
  18767. */
  18768. get: function () {
  18769. return this._pointerX;
  18770. },
  18771. enumerable: true,
  18772. configurable: true
  18773. });
  18774. Object.defineProperty(Scene.prototype, "pointerY", {
  18775. /**
  18776. * Current on-screen Y position of the pointer
  18777. * @return {number} Y position of the pointer
  18778. */
  18779. get: function () {
  18780. return this._pointerY;
  18781. },
  18782. enumerable: true,
  18783. configurable: true
  18784. });
  18785. Scene.prototype.getCachedMaterial = function () {
  18786. return this._cachedMaterial;
  18787. };
  18788. Scene.prototype.getCachedEffect = function () {
  18789. return this._cachedEffect;
  18790. };
  18791. Scene.prototype.getCachedVisibility = function () {
  18792. return this._cachedVisibility;
  18793. };
  18794. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18795. if (visibility === void 0) { visibility = 1; }
  18796. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18797. };
  18798. Scene.prototype.getBoundingBoxRenderer = function () {
  18799. if (!this._boundingBoxRenderer) {
  18800. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18801. }
  18802. return this._boundingBoxRenderer;
  18803. };
  18804. Scene.prototype.getOutlineRenderer = function () {
  18805. return this._outlineRenderer;
  18806. };
  18807. Scene.prototype.getEngine = function () {
  18808. return this._engine;
  18809. };
  18810. Scene.prototype.getTotalVertices = function () {
  18811. return this._totalVertices.current;
  18812. };
  18813. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18814. get: function () {
  18815. return this._totalVertices;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Scene.prototype.getActiveIndices = function () {
  18821. return this._activeIndices.current;
  18822. };
  18823. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18824. get: function () {
  18825. return this._activeIndices;
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. Scene.prototype.getActiveParticles = function () {
  18831. return this._activeParticles.current;
  18832. };
  18833. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18834. get: function () {
  18835. return this._activeParticles;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Scene.prototype.getActiveBones = function () {
  18841. return this._activeBones.current;
  18842. };
  18843. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18844. get: function () {
  18845. return this._activeBones;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. // Stats
  18851. Scene.prototype.getInterFramePerfCounter = function () {
  18852. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18853. return 0;
  18854. };
  18855. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18856. get: function () {
  18857. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18858. return null;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. Scene.prototype.getLastFrameDuration = function () {
  18864. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18865. return 0;
  18866. };
  18867. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18868. get: function () {
  18869. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18870. return null;
  18871. },
  18872. enumerable: true,
  18873. configurable: true
  18874. });
  18875. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18876. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18877. return 0;
  18878. };
  18879. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18880. get: function () {
  18881. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18882. return null;
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Scene.prototype.getActiveMeshes = function () {
  18888. return this._activeMeshes;
  18889. };
  18890. Scene.prototype.getRenderTargetsDuration = function () {
  18891. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18892. return 0;
  18893. };
  18894. Scene.prototype.getRenderDuration = function () {
  18895. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18896. return 0;
  18897. };
  18898. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18899. get: function () {
  18900. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18901. return null;
  18902. },
  18903. enumerable: true,
  18904. configurable: true
  18905. });
  18906. Scene.prototype.getParticlesDuration = function () {
  18907. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18908. return 0;
  18909. };
  18910. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18911. get: function () {
  18912. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18913. return null;
  18914. },
  18915. enumerable: true,
  18916. configurable: true
  18917. });
  18918. Scene.prototype.getSpritesDuration = function () {
  18919. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18920. return 0;
  18921. };
  18922. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18923. get: function () {
  18924. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18925. return null;
  18926. },
  18927. enumerable: true,
  18928. configurable: true
  18929. });
  18930. Scene.prototype.getAnimationRatio = function () {
  18931. return this._animationRatio;
  18932. };
  18933. Scene.prototype.getRenderId = function () {
  18934. return this._renderId;
  18935. };
  18936. Scene.prototype.incrementRenderId = function () {
  18937. this._renderId++;
  18938. };
  18939. Scene.prototype._updatePointerPosition = function (evt) {
  18940. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18941. if (!canvasRect) {
  18942. return;
  18943. }
  18944. this._pointerX = evt.clientX - canvasRect.left;
  18945. this._pointerY = evt.clientY - canvasRect.top;
  18946. this._unTranslatedPointerX = this._pointerX;
  18947. this._unTranslatedPointerY = this._pointerY;
  18948. };
  18949. Scene.prototype._createUbo = function () {
  18950. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18951. this._sceneUbo.addUniform("viewProjection", 16);
  18952. this._sceneUbo.addUniform("view", 16);
  18953. };
  18954. Scene.prototype._createAlternateUbo = function () {
  18955. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18956. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18957. this._alternateSceneUbo.addUniform("view", 16);
  18958. };
  18959. // Pointers handling
  18960. /**
  18961. * Use this method to simulate a pointer move on a mesh
  18962. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18963. */
  18964. Scene.prototype.simulatePointerMove = function (pickResult) {
  18965. var evt = new PointerEvent("pointermove");
  18966. return this._processPointerMove(pickResult, evt);
  18967. };
  18968. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18969. var canvas = this._engine.getRenderingCanvas();
  18970. if (!canvas) {
  18971. return this;
  18972. }
  18973. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18974. this.setPointerOverSprite(null);
  18975. this.setPointerOverMesh(pickResult.pickedMesh);
  18976. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18977. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18978. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18979. }
  18980. else {
  18981. canvas.style.cursor = this.hoverCursor;
  18982. }
  18983. }
  18984. else {
  18985. canvas.style.cursor = this.defaultCursor;
  18986. }
  18987. }
  18988. else {
  18989. this.setPointerOverMesh(null);
  18990. // Sprites
  18991. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18992. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18993. this.setPointerOverSprite(pickResult.pickedSprite);
  18994. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18995. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18996. }
  18997. else {
  18998. canvas.style.cursor = this.hoverCursor;
  18999. }
  19000. }
  19001. else {
  19002. this.setPointerOverSprite(null);
  19003. // Restore pointer
  19004. canvas.style.cursor = this.defaultCursor;
  19005. }
  19006. }
  19007. if (pickResult) {
  19008. if (this.onPointerMove) {
  19009. this.onPointerMove(evt, pickResult);
  19010. }
  19011. if (this.onPointerObservable.hasObservers()) {
  19012. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19013. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19014. this.onPointerObservable.notifyObservers(pi, type);
  19015. }
  19016. }
  19017. return this;
  19018. };
  19019. /**
  19020. * Use this method to simulate a pointer down on a mesh
  19021. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19022. */
  19023. Scene.prototype.simulatePointerDown = function (pickResult) {
  19024. var evt = new PointerEvent("pointerdown");
  19025. return this._processPointerDown(pickResult, evt);
  19026. };
  19027. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19028. var _this = this;
  19029. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19030. this._pickedDownMesh = pickResult.pickedMesh;
  19031. var actionManager = pickResult.pickedMesh.actionManager;
  19032. if (actionManager) {
  19033. if (actionManager.hasPickTriggers) {
  19034. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19035. switch (evt.button) {
  19036. case 0:
  19037. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19038. break;
  19039. case 1:
  19040. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19041. break;
  19042. case 2:
  19043. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19044. break;
  19045. }
  19046. }
  19047. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19048. window.setTimeout(function () {
  19049. 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);
  19050. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19051. if (_this._totalPointersPressed !== 0 &&
  19052. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19053. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19054. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19055. _this._startingPointerTime = 0;
  19056. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19057. }
  19058. }
  19059. }, Scene.LongPressDelay);
  19060. }
  19061. }
  19062. }
  19063. if (pickResult) {
  19064. if (this.onPointerDown) {
  19065. this.onPointerDown(evt, pickResult);
  19066. }
  19067. if (this.onPointerObservable.hasObservers()) {
  19068. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19069. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19070. this.onPointerObservable.notifyObservers(pi, type);
  19071. }
  19072. }
  19073. return this;
  19074. };
  19075. /**
  19076. * Use this method to simulate a pointer up on a mesh
  19077. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19078. */
  19079. Scene.prototype.simulatePointerUp = function (pickResult) {
  19080. var evt = new PointerEvent("pointerup");
  19081. var clickInfo = new ClickInfo();
  19082. clickInfo.singleClick = true;
  19083. clickInfo.ignore = true;
  19084. return this._processPointerUp(pickResult, evt, clickInfo);
  19085. };
  19086. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19087. if (pickResult && pickResult && pickResult.pickedMesh) {
  19088. this._pickedUpMesh = pickResult.pickedMesh;
  19089. if (this._pickedDownMesh === this._pickedUpMesh) {
  19090. if (this.onPointerPick) {
  19091. this.onPointerPick(evt, pickResult);
  19092. }
  19093. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19094. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19095. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19096. this.onPointerObservable.notifyObservers(pi, type);
  19097. }
  19098. }
  19099. if (pickResult.pickedMesh.actionManager) {
  19100. if (clickInfo.ignore) {
  19101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19102. }
  19103. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19105. }
  19106. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19107. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19108. }
  19109. }
  19110. }
  19111. if (this._pickedDownMesh &&
  19112. this._pickedDownMesh.actionManager &&
  19113. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19114. this._pickedDownMesh !== this._pickedUpMesh) {
  19115. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19116. }
  19117. if (this.onPointerUp) {
  19118. this.onPointerUp(evt, pickResult);
  19119. }
  19120. if (this.onPointerObservable.hasObservers()) {
  19121. if (!clickInfo.ignore) {
  19122. if (!clickInfo.hasSwiped) {
  19123. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19124. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19125. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19126. this.onPointerObservable.notifyObservers(pi, type);
  19127. }
  19128. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19129. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19130. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19131. this.onPointerObservable.notifyObservers(pi, type);
  19132. }
  19133. }
  19134. }
  19135. else {
  19136. var type = BABYLON.PointerEventTypes.POINTERUP;
  19137. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19138. this.onPointerObservable.notifyObservers(pi, type);
  19139. }
  19140. }
  19141. return this;
  19142. };
  19143. /**
  19144. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19145. * @param attachUp defines if you want to attach events to pointerup
  19146. * @param attachDown defines if you want to attach events to pointerdown
  19147. * @param attachMove defines if you want to attach events to pointermove
  19148. */
  19149. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19150. var _this = this;
  19151. if (attachUp === void 0) { attachUp = true; }
  19152. if (attachDown === void 0) { attachDown = true; }
  19153. if (attachMove === void 0) { attachMove = true; }
  19154. this._initActionManager = function (act, clickInfo) {
  19155. if (!_this._meshPickProceed) {
  19156. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19157. _this._currentPickResult = pickResult;
  19158. if (pickResult) {
  19159. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19160. }
  19161. _this._meshPickProceed = true;
  19162. }
  19163. return act;
  19164. };
  19165. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19166. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19167. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19168. btn !== _this._previousButtonPressed) {
  19169. _this._doubleClickOccured = false;
  19170. clickInfo.singleClick = true;
  19171. clickInfo.ignore = false;
  19172. cb(clickInfo, _this._currentPickResult);
  19173. }
  19174. };
  19175. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19176. var clickInfo = new ClickInfo();
  19177. _this._currentPickResult = null;
  19178. var act = null;
  19179. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19180. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19181. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19182. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19183. act = _this._initActionManager(act, clickInfo);
  19184. if (act)
  19185. checkPicking = act.hasPickTriggers;
  19186. }
  19187. if (checkPicking) {
  19188. var btn = evt.button;
  19189. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19190. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19191. if (!clickInfo.hasSwiped) {
  19192. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19193. if (!checkSingleClickImmediately) {
  19194. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19195. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19196. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19197. act = _this._initActionManager(act, clickInfo);
  19198. if (act)
  19199. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19200. }
  19201. }
  19202. if (checkSingleClickImmediately) {
  19203. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19204. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19205. btn !== _this._previousButtonPressed) {
  19206. clickInfo.singleClick = true;
  19207. cb(clickInfo, _this._currentPickResult);
  19208. }
  19209. }
  19210. else {
  19211. // wait that no double click has been raised during the double click delay
  19212. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19213. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19214. }
  19215. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19216. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19217. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19218. act = _this._initActionManager(act, clickInfo);
  19219. if (act)
  19220. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19221. }
  19222. if (checkDoubleClick) {
  19223. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19224. if (btn === _this._previousButtonPressed &&
  19225. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19226. !_this._doubleClickOccured) {
  19227. // pointer has not moved for 2 clicks, it's a double click
  19228. if (!clickInfo.hasSwiped &&
  19229. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19230. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19231. _this._previousStartingPointerTime = 0;
  19232. _this._doubleClickOccured = true;
  19233. clickInfo.doubleClick = true;
  19234. clickInfo.ignore = false;
  19235. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19236. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19237. }
  19238. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19239. cb(clickInfo, _this._currentPickResult);
  19240. }
  19241. else {
  19242. _this._doubleClickOccured = false;
  19243. _this._previousStartingPointerTime = _this._startingPointerTime;
  19244. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19245. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19246. _this._previousButtonPressed = btn;
  19247. if (Scene.ExclusiveDoubleClickMode) {
  19248. if (_this._previousDelayedSimpleClickTimeout) {
  19249. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19250. }
  19251. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19252. cb(clickInfo, _this._previousPickResult);
  19253. }
  19254. else {
  19255. cb(clickInfo, _this._currentPickResult);
  19256. }
  19257. }
  19258. }
  19259. else {
  19260. _this._doubleClickOccured = false;
  19261. _this._previousStartingPointerTime = _this._startingPointerTime;
  19262. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19263. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19264. _this._previousButtonPressed = btn;
  19265. }
  19266. }
  19267. }
  19268. }
  19269. clickInfo.ignore = true;
  19270. cb(clickInfo, _this._currentPickResult);
  19271. };
  19272. this._spritePredicate = function (sprite) {
  19273. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19274. };
  19275. this._onPointerMove = function (evt) {
  19276. _this._updatePointerPosition(evt);
  19277. // PreObservable support
  19278. if (_this.onPrePointerObservable.hasObservers()) {
  19279. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19280. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19281. _this.onPrePointerObservable.notifyObservers(pi, type);
  19282. if (pi.skipOnPointerObservable) {
  19283. return;
  19284. }
  19285. }
  19286. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19287. return;
  19288. }
  19289. if (!_this.pointerMovePredicate) {
  19290. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19291. }
  19292. // Meshes
  19293. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19294. _this._processPointerMove(pickResult, evt);
  19295. };
  19296. this._onPointerDown = function (evt) {
  19297. _this._totalPointersPressed++;
  19298. _this._pickedDownMesh = null;
  19299. _this._meshPickProceed = false;
  19300. _this._updatePointerPosition(evt);
  19301. if (_this.preventDefaultOnPointerDown && canvas) {
  19302. evt.preventDefault();
  19303. canvas.focus();
  19304. }
  19305. // PreObservable support
  19306. if (_this.onPrePointerObservable.hasObservers()) {
  19307. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19308. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19309. _this.onPrePointerObservable.notifyObservers(pi, type);
  19310. if (pi.skipOnPointerObservable) {
  19311. return;
  19312. }
  19313. }
  19314. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19315. return;
  19316. }
  19317. _this._startingPointerPosition.x = _this._pointerX;
  19318. _this._startingPointerPosition.y = _this._pointerY;
  19319. _this._startingPointerTime = new Date().getTime();
  19320. if (!_this.pointerDownPredicate) {
  19321. _this.pointerDownPredicate = function (mesh) {
  19322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19323. };
  19324. }
  19325. // Meshes
  19326. _this._pickedDownMesh = null;
  19327. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19328. _this._processPointerDown(pickResult, evt);
  19329. // Sprites
  19330. _this._pickedDownSprite = null;
  19331. if (_this.spriteManagers.length > 0) {
  19332. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19333. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19334. if (pickResult.pickedSprite.actionManager) {
  19335. _this._pickedDownSprite = pickResult.pickedSprite;
  19336. switch (evt.button) {
  19337. case 0:
  19338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19339. break;
  19340. case 1:
  19341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19342. break;
  19343. case 2:
  19344. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19345. break;
  19346. }
  19347. if (pickResult.pickedSprite.actionManager) {
  19348. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19349. }
  19350. }
  19351. }
  19352. }
  19353. };
  19354. this._onPointerUp = function (evt) {
  19355. if (_this._totalPointersPressed === 0) {
  19356. return; // So we need to test it the pointer down was pressed before.
  19357. }
  19358. _this._totalPointersPressed--;
  19359. _this._pickedUpMesh = null;
  19360. _this._meshPickProceed = false;
  19361. _this._updatePointerPosition(evt);
  19362. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19363. // PreObservable support
  19364. if (_this.onPrePointerObservable.hasObservers()) {
  19365. if (!clickInfo.ignore) {
  19366. if (!clickInfo.hasSwiped) {
  19367. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19368. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19369. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19370. _this.onPrePointerObservable.notifyObservers(pi, type);
  19371. if (pi.skipOnPointerObservable) {
  19372. return;
  19373. }
  19374. }
  19375. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19376. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19377. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19378. _this.onPrePointerObservable.notifyObservers(pi, type);
  19379. if (pi.skipOnPointerObservable) {
  19380. return;
  19381. }
  19382. }
  19383. }
  19384. }
  19385. else {
  19386. var type = BABYLON.PointerEventTypes.POINTERUP;
  19387. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19388. _this.onPrePointerObservable.notifyObservers(pi, type);
  19389. if (pi.skipOnPointerObservable) {
  19390. return;
  19391. }
  19392. }
  19393. }
  19394. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19395. return;
  19396. }
  19397. if (!_this.pointerUpPredicate) {
  19398. _this.pointerUpPredicate = function (mesh) {
  19399. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19400. };
  19401. }
  19402. // Meshes
  19403. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19404. _this._initActionManager(null, clickInfo);
  19405. }
  19406. if (!pickResult) {
  19407. pickResult = _this._currentPickResult;
  19408. }
  19409. _this._processPointerUp(pickResult, evt, clickInfo);
  19410. // Sprites
  19411. if (_this.spriteManagers.length > 0) {
  19412. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19413. if (spritePickResult) {
  19414. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19415. if (spritePickResult.pickedSprite.actionManager) {
  19416. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19417. if (spritePickResult.pickedSprite.actionManager) {
  19418. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19419. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19420. }
  19421. }
  19422. }
  19423. }
  19424. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19425. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19426. }
  19427. }
  19428. }
  19429. _this._previousPickResult = _this._currentPickResult;
  19430. });
  19431. };
  19432. this._onKeyDown = function (evt) {
  19433. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19434. if (_this.onPreKeyboardObservable.hasObservers()) {
  19435. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19436. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19437. if (pi.skipOnPointerObservable) {
  19438. return;
  19439. }
  19440. }
  19441. if (_this.onKeyboardObservable.hasObservers()) {
  19442. var pi = new BABYLON.KeyboardInfo(type, evt);
  19443. _this.onKeyboardObservable.notifyObservers(pi, type);
  19444. }
  19445. if (_this.actionManager) {
  19446. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19447. }
  19448. };
  19449. this._onKeyUp = function (evt) {
  19450. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19451. if (_this.onPreKeyboardObservable.hasObservers()) {
  19452. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19453. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19454. if (pi.skipOnPointerObservable) {
  19455. return;
  19456. }
  19457. }
  19458. if (_this.onKeyboardObservable.hasObservers()) {
  19459. var pi = new BABYLON.KeyboardInfo(type, evt);
  19460. _this.onKeyboardObservable.notifyObservers(pi, type);
  19461. }
  19462. if (_this.actionManager) {
  19463. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19464. }
  19465. };
  19466. var engine = this.getEngine();
  19467. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19468. if (!canvas) {
  19469. return;
  19470. }
  19471. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19472. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19473. });
  19474. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19475. if (!canvas) {
  19476. return;
  19477. }
  19478. canvas.removeEventListener("keydown", _this._onKeyDown);
  19479. canvas.removeEventListener("keyup", _this._onKeyUp);
  19480. });
  19481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19482. var canvas = this._engine.getRenderingCanvas();
  19483. if (!canvas) {
  19484. return;
  19485. }
  19486. if (attachMove) {
  19487. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19488. // Wheel
  19489. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19490. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19491. }
  19492. if (attachDown) {
  19493. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19494. }
  19495. if (attachUp) {
  19496. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19497. }
  19498. canvas.tabIndex = 1;
  19499. };
  19500. Scene.prototype.detachControl = function () {
  19501. var engine = this.getEngine();
  19502. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19503. var canvas = engine.getRenderingCanvas();
  19504. if (!canvas) {
  19505. return;
  19506. }
  19507. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19508. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19509. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19510. if (this._onCanvasBlurObserver) {
  19511. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19512. }
  19513. if (this._onCanvasFocusObserver) {
  19514. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19515. }
  19516. // Wheel
  19517. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19518. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19519. // Keyboard
  19520. canvas.removeEventListener("keydown", this._onKeyDown);
  19521. canvas.removeEventListener("keyup", this._onKeyUp);
  19522. // Observables
  19523. this.onKeyboardObservable.clear();
  19524. this.onPreKeyboardObservable.clear();
  19525. this.onPointerObservable.clear();
  19526. this.onPrePointerObservable.clear();
  19527. };
  19528. // Ready
  19529. Scene.prototype.isReady = function () {
  19530. if (this._isDisposed) {
  19531. return false;
  19532. }
  19533. if (this._pendingData.length > 0) {
  19534. return false;
  19535. }
  19536. var index;
  19537. // Geometries
  19538. for (index = 0; index < this._geometries.length; index++) {
  19539. var geometry = this._geometries[index];
  19540. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19541. return false;
  19542. }
  19543. }
  19544. // Meshes
  19545. for (index = 0; index < this.meshes.length; index++) {
  19546. var mesh = this.meshes[index];
  19547. if (!mesh.isEnabled()) {
  19548. continue;
  19549. }
  19550. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19551. continue;
  19552. }
  19553. if (!mesh.isReady()) {
  19554. return false;
  19555. }
  19556. var mat = mesh.material;
  19557. if (mat) {
  19558. if (!mat.isReady(mesh)) {
  19559. return false;
  19560. }
  19561. }
  19562. }
  19563. return true;
  19564. };
  19565. Scene.prototype.resetCachedMaterial = function () {
  19566. this._cachedMaterial = null;
  19567. this._cachedEffect = null;
  19568. this._cachedVisibility = null;
  19569. };
  19570. Scene.prototype.registerBeforeRender = function (func) {
  19571. this.onBeforeRenderObservable.add(func);
  19572. };
  19573. Scene.prototype.unregisterBeforeRender = function (func) {
  19574. this.onBeforeRenderObservable.removeCallback(func);
  19575. };
  19576. Scene.prototype.registerAfterRender = function (func) {
  19577. this.onAfterRenderObservable.add(func);
  19578. };
  19579. Scene.prototype.unregisterAfterRender = function (func) {
  19580. this.onAfterRenderObservable.removeCallback(func);
  19581. };
  19582. Scene.prototype._addPendingData = function (data) {
  19583. this._pendingData.push(data);
  19584. };
  19585. Scene.prototype._removePendingData = function (data) {
  19586. var wasLoading = this.isLoading;
  19587. var index = this._pendingData.indexOf(data);
  19588. if (index !== -1) {
  19589. this._pendingData.splice(index, 1);
  19590. }
  19591. if (wasLoading && !this.isLoading) {
  19592. this.onDataLoadedObservable.notifyObservers(this);
  19593. }
  19594. };
  19595. Scene.prototype.getWaitingItemsCount = function () {
  19596. return this._pendingData.length;
  19597. };
  19598. Object.defineProperty(Scene.prototype, "isLoading", {
  19599. get: function () {
  19600. return this._pendingData.length > 0;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. /**
  19606. * Registers a function to be executed when the scene is ready.
  19607. * @param {Function} func - the function to be executed.
  19608. */
  19609. Scene.prototype.executeWhenReady = function (func) {
  19610. var _this = this;
  19611. this.onReadyObservable.add(func);
  19612. if (this._executeWhenReadyTimeoutId !== -1) {
  19613. return;
  19614. }
  19615. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19616. _this._checkIsReady();
  19617. }, 150);
  19618. };
  19619. Scene.prototype._checkIsReady = function () {
  19620. var _this = this;
  19621. if (this.isReady()) {
  19622. this.onReadyObservable.notifyObservers(this);
  19623. this.onReadyObservable.clear();
  19624. this._executeWhenReadyTimeoutId = -1;
  19625. return;
  19626. }
  19627. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19628. _this._checkIsReady();
  19629. }, 150);
  19630. };
  19631. // Animations
  19632. /**
  19633. * Will start the animation sequence of a given target
  19634. * @param target - the target
  19635. * @param {number} from - from which frame should animation start
  19636. * @param {number} to - till which frame should animation run.
  19637. * @param {boolean} [loop] - should the animation loop
  19638. * @param {number} [speedRatio] - the speed in which to run the animation
  19639. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19640. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19641. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19642. * See BABYLON.Animatable
  19643. */
  19644. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19645. if (speedRatio === void 0) { speedRatio = 1.0; }
  19646. if (from > to && speedRatio > 0) {
  19647. speedRatio *= -1;
  19648. }
  19649. this.stopAnimation(target);
  19650. if (!animatable) {
  19651. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19652. }
  19653. // Local animations
  19654. if (target.animations) {
  19655. animatable.appendAnimations(target, target.animations);
  19656. }
  19657. // Children animations
  19658. if (target.getAnimatables) {
  19659. var animatables = target.getAnimatables();
  19660. for (var index = 0; index < animatables.length; index++) {
  19661. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19662. }
  19663. }
  19664. animatable.reset();
  19665. return animatable;
  19666. };
  19667. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19668. if (speedRatio === undefined) {
  19669. speedRatio = 1.0;
  19670. }
  19671. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19672. return animatable;
  19673. };
  19674. Scene.prototype.getAnimatableByTarget = function (target) {
  19675. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19676. if (this._activeAnimatables[index].target === target) {
  19677. return this._activeAnimatables[index];
  19678. }
  19679. }
  19680. return null;
  19681. };
  19682. Object.defineProperty(Scene.prototype, "Animatables", {
  19683. get: function () {
  19684. return this._activeAnimatables;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. /**
  19690. * Will stop the animation of the given target
  19691. * @param target - the target
  19692. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19693. * @see beginAnimation
  19694. */
  19695. Scene.prototype.stopAnimation = function (target, animationName) {
  19696. var animatable = this.getAnimatableByTarget(target);
  19697. if (animatable) {
  19698. animatable.stop(animationName);
  19699. }
  19700. };
  19701. /**
  19702. * Stops and removes all animations that have been applied to the scene
  19703. */
  19704. Scene.prototype.stopAllAnimations = function () {
  19705. if (this._activeAnimatables) {
  19706. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19707. this._activeAnimatables[i].stop();
  19708. }
  19709. this._activeAnimatables = [];
  19710. }
  19711. };
  19712. Scene.prototype._animate = function () {
  19713. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19714. return;
  19715. }
  19716. // Getting time
  19717. var now = BABYLON.Tools.Now;
  19718. if (!this._animationTimeLast) {
  19719. if (this._pendingData.length > 0) {
  19720. return;
  19721. }
  19722. this._animationTimeLast = now;
  19723. }
  19724. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19725. this._animationTime += deltaTime;
  19726. this._animationTimeLast = now;
  19727. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19728. this._activeAnimatables[index]._animate(this._animationTime);
  19729. }
  19730. };
  19731. // Matrix
  19732. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19733. this._useAlternateCameraConfiguration = active;
  19734. };
  19735. Scene.prototype.getViewMatrix = function () {
  19736. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19737. };
  19738. Scene.prototype.getProjectionMatrix = function () {
  19739. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19740. };
  19741. Scene.prototype.getTransformMatrix = function () {
  19742. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19743. };
  19744. Scene.prototype.setTransformMatrix = function (view, projection) {
  19745. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19746. return;
  19747. }
  19748. this._viewUpdateFlag = view.updateFlag;
  19749. this._projectionUpdateFlag = projection.updateFlag;
  19750. this._viewMatrix = view;
  19751. this._projectionMatrix = projection;
  19752. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19753. // Update frustum
  19754. if (!this._frustumPlanes) {
  19755. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19756. }
  19757. else {
  19758. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19759. }
  19760. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19761. var otherCamera = this.activeCamera._alternateCamera;
  19762. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19763. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19764. }
  19765. if (this._sceneUbo.useUbo) {
  19766. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19767. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19768. this._sceneUbo.update();
  19769. }
  19770. };
  19771. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19772. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19773. return;
  19774. }
  19775. this._alternateViewUpdateFlag = view.updateFlag;
  19776. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19777. this._alternateViewMatrix = view;
  19778. this._alternateProjectionMatrix = projection;
  19779. if (!this._alternateTransformMatrix) {
  19780. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19781. }
  19782. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19783. if (!this._alternateSceneUbo) {
  19784. this._createAlternateUbo();
  19785. }
  19786. if (this._alternateSceneUbo.useUbo) {
  19787. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19788. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19789. this._alternateSceneUbo.update();
  19790. }
  19791. };
  19792. Scene.prototype.getSceneUniformBuffer = function () {
  19793. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19794. };
  19795. // Methods
  19796. Scene.prototype.getUniqueId = function () {
  19797. var result = Scene._uniqueIdCounter;
  19798. Scene._uniqueIdCounter++;
  19799. return result;
  19800. };
  19801. Scene.prototype.addMesh = function (newMesh) {
  19802. this.meshes.push(newMesh);
  19803. //notify the collision coordinator
  19804. if (this.collisionCoordinator) {
  19805. this.collisionCoordinator.onMeshAdded(newMesh);
  19806. }
  19807. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19808. };
  19809. Scene.prototype.removeMesh = function (toRemove) {
  19810. var index = this.meshes.indexOf(toRemove);
  19811. if (index !== -1) {
  19812. // Remove from the scene if mesh found
  19813. this.meshes.splice(index, 1);
  19814. }
  19815. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19816. return index;
  19817. };
  19818. Scene.prototype.addTransformNode = function (newTransformNode) {
  19819. this.transformNodes.push(newTransformNode);
  19820. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19821. };
  19822. Scene.prototype.removeTransformNode = function (toRemove) {
  19823. var index = this.transformNodes.indexOf(toRemove);
  19824. if (index !== -1) {
  19825. // Remove from the scene if found
  19826. this.transformNodes.splice(index, 1);
  19827. }
  19828. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19829. return index;
  19830. };
  19831. Scene.prototype.removeSkeleton = function (toRemove) {
  19832. var index = this.skeletons.indexOf(toRemove);
  19833. if (index !== -1) {
  19834. // Remove from the scene if found
  19835. this.skeletons.splice(index, 1);
  19836. }
  19837. return index;
  19838. };
  19839. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19840. var index = this.morphTargetManagers.indexOf(toRemove);
  19841. if (index !== -1) {
  19842. // Remove from the scene if found
  19843. this.morphTargetManagers.splice(index, 1);
  19844. }
  19845. return index;
  19846. };
  19847. Scene.prototype.removeLight = function (toRemove) {
  19848. var index = this.lights.indexOf(toRemove);
  19849. if (index !== -1) {
  19850. // Remove from the scene if mesh found
  19851. this.lights.splice(index, 1);
  19852. this.sortLightsByPriority();
  19853. }
  19854. this.onLightRemovedObservable.notifyObservers(toRemove);
  19855. return index;
  19856. };
  19857. Scene.prototype.removeCamera = function (toRemove) {
  19858. var index = this.cameras.indexOf(toRemove);
  19859. if (index !== -1) {
  19860. // Remove from the scene if mesh found
  19861. this.cameras.splice(index, 1);
  19862. }
  19863. // Remove from activeCameras
  19864. var index2 = this.activeCameras.indexOf(toRemove);
  19865. if (index2 !== -1) {
  19866. // Remove from the scene if mesh found
  19867. this.activeCameras.splice(index2, 1);
  19868. }
  19869. // Reset the activeCamera
  19870. if (this.activeCamera === toRemove) {
  19871. if (this.cameras.length > 0) {
  19872. this.activeCamera = this.cameras[0];
  19873. }
  19874. else {
  19875. this.activeCamera = null;
  19876. }
  19877. }
  19878. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19879. return index;
  19880. };
  19881. Scene.prototype.addLight = function (newLight) {
  19882. this.lights.push(newLight);
  19883. this.sortLightsByPriority();
  19884. this.onNewLightAddedObservable.notifyObservers(newLight);
  19885. };
  19886. Scene.prototype.sortLightsByPriority = function () {
  19887. if (this.requireLightSorting) {
  19888. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19889. }
  19890. };
  19891. Scene.prototype.addCamera = function (newCamera) {
  19892. this.cameras.push(newCamera);
  19893. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19894. };
  19895. /**
  19896. * Switch active camera
  19897. * @param {Camera} newCamera - new active camera
  19898. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19899. */
  19900. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19901. if (attachControl === void 0) { attachControl = true; }
  19902. var canvas = this._engine.getRenderingCanvas();
  19903. if (!canvas) {
  19904. return;
  19905. }
  19906. if (this.activeCamera) {
  19907. this.activeCamera.detachControl(canvas);
  19908. }
  19909. this.activeCamera = newCamera;
  19910. if (attachControl) {
  19911. newCamera.attachControl(canvas);
  19912. }
  19913. };
  19914. /**
  19915. * sets the active camera of the scene using its ID
  19916. * @param {string} id - the camera's ID
  19917. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19918. * @see activeCamera
  19919. */
  19920. Scene.prototype.setActiveCameraByID = function (id) {
  19921. var camera = this.getCameraByID(id);
  19922. if (camera) {
  19923. this.activeCamera = camera;
  19924. return camera;
  19925. }
  19926. return null;
  19927. };
  19928. /**
  19929. * sets the active camera of the scene using its name
  19930. * @param {string} name - the camera's name
  19931. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19932. * @see activeCamera
  19933. */
  19934. Scene.prototype.setActiveCameraByName = function (name) {
  19935. var camera = this.getCameraByName(name);
  19936. if (camera) {
  19937. this.activeCamera = camera;
  19938. return camera;
  19939. }
  19940. return null;
  19941. };
  19942. /**
  19943. * get a material using its id
  19944. * @param {string} the material's ID
  19945. * @return {BABYLON.Material|null} the material or null if none found.
  19946. */
  19947. Scene.prototype.getMaterialByID = function (id) {
  19948. for (var index = 0; index < this.materials.length; index++) {
  19949. if (this.materials[index].id === id) {
  19950. return this.materials[index];
  19951. }
  19952. }
  19953. return null;
  19954. };
  19955. /**
  19956. * get a material using its name
  19957. * @param {string} the material's name
  19958. * @return {BABYLON.Material|null} the material or null if none found.
  19959. */
  19960. Scene.prototype.getMaterialByName = function (name) {
  19961. for (var index = 0; index < this.materials.length; index++) {
  19962. if (this.materials[index].name === name) {
  19963. return this.materials[index];
  19964. }
  19965. }
  19966. return null;
  19967. };
  19968. Scene.prototype.getLensFlareSystemByName = function (name) {
  19969. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19970. if (this.lensFlareSystems[index].name === name) {
  19971. return this.lensFlareSystems[index];
  19972. }
  19973. }
  19974. return null;
  19975. };
  19976. Scene.prototype.getLensFlareSystemByID = function (id) {
  19977. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19978. if (this.lensFlareSystems[index].id === id) {
  19979. return this.lensFlareSystems[index];
  19980. }
  19981. }
  19982. return null;
  19983. };
  19984. Scene.prototype.getCameraByID = function (id) {
  19985. for (var index = 0; index < this.cameras.length; index++) {
  19986. if (this.cameras[index].id === id) {
  19987. return this.cameras[index];
  19988. }
  19989. }
  19990. return null;
  19991. };
  19992. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19993. for (var index = 0; index < this.cameras.length; index++) {
  19994. if (this.cameras[index].uniqueId === uniqueId) {
  19995. return this.cameras[index];
  19996. }
  19997. }
  19998. return null;
  19999. };
  20000. /**
  20001. * get a camera using its name
  20002. * @param {string} the camera's name
  20003. * @return {BABYLON.Camera|null} the camera or null if none found.
  20004. */
  20005. Scene.prototype.getCameraByName = function (name) {
  20006. for (var index = 0; index < this.cameras.length; index++) {
  20007. if (this.cameras[index].name === name) {
  20008. return this.cameras[index];
  20009. }
  20010. }
  20011. return null;
  20012. };
  20013. /**
  20014. * get a bone using its id
  20015. * @param {string} the bone's id
  20016. * @return {BABYLON.Bone|null} the bone or null if not found
  20017. */
  20018. Scene.prototype.getBoneByID = function (id) {
  20019. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20020. var skeleton = this.skeletons[skeletonIndex];
  20021. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20022. if (skeleton.bones[boneIndex].id === id) {
  20023. return skeleton.bones[boneIndex];
  20024. }
  20025. }
  20026. }
  20027. return null;
  20028. };
  20029. /**
  20030. * get a bone using its id
  20031. * @param {string} the bone's name
  20032. * @return {BABYLON.Bone|null} the bone or null if not found
  20033. */
  20034. Scene.prototype.getBoneByName = function (name) {
  20035. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20036. var skeleton = this.skeletons[skeletonIndex];
  20037. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20038. if (skeleton.bones[boneIndex].name === name) {
  20039. return skeleton.bones[boneIndex];
  20040. }
  20041. }
  20042. }
  20043. return null;
  20044. };
  20045. /**
  20046. * get a light node using its name
  20047. * @param {string} the light's name
  20048. * @return {BABYLON.Light|null} the light or null if none found.
  20049. */
  20050. Scene.prototype.getLightByName = function (name) {
  20051. for (var index = 0; index < this.lights.length; index++) {
  20052. if (this.lights[index].name === name) {
  20053. return this.lights[index];
  20054. }
  20055. }
  20056. return null;
  20057. };
  20058. /**
  20059. * get a light node using its ID
  20060. * @param {string} the light's id
  20061. * @return {BABYLON.Light|null} the light or null if none found.
  20062. */
  20063. Scene.prototype.getLightByID = function (id) {
  20064. for (var index = 0; index < this.lights.length; index++) {
  20065. if (this.lights[index].id === id) {
  20066. return this.lights[index];
  20067. }
  20068. }
  20069. return null;
  20070. };
  20071. /**
  20072. * get a light node using its scene-generated unique ID
  20073. * @param {number} the light's unique id
  20074. * @return {BABYLON.Light|null} the light or null if none found.
  20075. */
  20076. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20077. for (var index = 0; index < this.lights.length; index++) {
  20078. if (this.lights[index].uniqueId === uniqueId) {
  20079. return this.lights[index];
  20080. }
  20081. }
  20082. return null;
  20083. };
  20084. /**
  20085. * get a particle system by id
  20086. * @param id {number} the particle system id
  20087. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20088. */
  20089. Scene.prototype.getParticleSystemByID = function (id) {
  20090. for (var index = 0; index < this.particleSystems.length; index++) {
  20091. if (this.particleSystems[index].id === id) {
  20092. return this.particleSystems[index];
  20093. }
  20094. }
  20095. return null;
  20096. };
  20097. /**
  20098. * get a geometry using its ID
  20099. * @param {string} the geometry's id
  20100. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20101. */
  20102. Scene.prototype.getGeometryByID = function (id) {
  20103. for (var index = 0; index < this._geometries.length; index++) {
  20104. if (this._geometries[index].id === id) {
  20105. return this._geometries[index];
  20106. }
  20107. }
  20108. return null;
  20109. };
  20110. /**
  20111. * add a new geometry to this scene.
  20112. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20113. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20114. * @return {boolean} was the geometry added or not
  20115. */
  20116. Scene.prototype.pushGeometry = function (geometry, force) {
  20117. if (!force && this.getGeometryByID(geometry.id)) {
  20118. return false;
  20119. }
  20120. this._geometries.push(geometry);
  20121. //notify the collision coordinator
  20122. if (this.collisionCoordinator) {
  20123. this.collisionCoordinator.onGeometryAdded(geometry);
  20124. }
  20125. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20126. return true;
  20127. };
  20128. /**
  20129. * Removes an existing geometry
  20130. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20131. * @return {boolean} was the geometry removed or not
  20132. */
  20133. Scene.prototype.removeGeometry = function (geometry) {
  20134. var index = this._geometries.indexOf(geometry);
  20135. if (index > -1) {
  20136. this._geometries.splice(index, 1);
  20137. //notify the collision coordinator
  20138. if (this.collisionCoordinator) {
  20139. this.collisionCoordinator.onGeometryDeleted(geometry);
  20140. }
  20141. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20142. return true;
  20143. }
  20144. return false;
  20145. };
  20146. Scene.prototype.getGeometries = function () {
  20147. return this._geometries;
  20148. };
  20149. /**
  20150. * Get the first added mesh found of a given ID
  20151. * @param {string} id - the id to search for
  20152. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20153. */
  20154. Scene.prototype.getMeshByID = function (id) {
  20155. for (var index = 0; index < this.meshes.length; index++) {
  20156. if (this.meshes[index].id === id) {
  20157. return this.meshes[index];
  20158. }
  20159. }
  20160. return null;
  20161. };
  20162. Scene.prototype.getMeshesByID = function (id) {
  20163. return this.meshes.filter(function (m) {
  20164. return m.id === id;
  20165. });
  20166. };
  20167. /**
  20168. * Get the first added transform node found of a given ID
  20169. * @param {string} id - the id to search for
  20170. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20171. */
  20172. Scene.prototype.getTransformNodeByID = function (id) {
  20173. for (var index = 0; index < this.transformNodes.length; index++) {
  20174. if (this.transformNodes[index].id === id) {
  20175. return this.transformNodes[index];
  20176. }
  20177. }
  20178. return null;
  20179. };
  20180. Scene.prototype.getTransformNodesByID = function (id) {
  20181. return this.transformNodes.filter(function (m) {
  20182. return m.id === id;
  20183. });
  20184. };
  20185. /**
  20186. * Get a mesh with its auto-generated unique id
  20187. * @param {number} uniqueId - the unique id to search for
  20188. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20189. */
  20190. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20191. for (var index = 0; index < this.meshes.length; index++) {
  20192. if (this.meshes[index].uniqueId === uniqueId) {
  20193. return this.meshes[index];
  20194. }
  20195. }
  20196. return null;
  20197. };
  20198. /**
  20199. * Get a the last added mesh found of a given ID
  20200. * @param {string} id - the id to search for
  20201. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20202. */
  20203. Scene.prototype.getLastMeshByID = function (id) {
  20204. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20205. if (this.meshes[index].id === id) {
  20206. return this.meshes[index];
  20207. }
  20208. }
  20209. return null;
  20210. };
  20211. /**
  20212. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20213. * @param {string} id - the id to search for
  20214. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20215. */
  20216. Scene.prototype.getLastEntryByID = function (id) {
  20217. var index;
  20218. for (index = this.meshes.length - 1; index >= 0; index--) {
  20219. if (this.meshes[index].id === id) {
  20220. return this.meshes[index];
  20221. }
  20222. }
  20223. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20224. if (this.transformNodes[index].id === id) {
  20225. return this.transformNodes[index];
  20226. }
  20227. }
  20228. for (index = this.cameras.length - 1; index >= 0; index--) {
  20229. if (this.cameras[index].id === id) {
  20230. return this.cameras[index];
  20231. }
  20232. }
  20233. for (index = this.lights.length - 1; index >= 0; index--) {
  20234. if (this.lights[index].id === id) {
  20235. return this.lights[index];
  20236. }
  20237. }
  20238. return null;
  20239. };
  20240. Scene.prototype.getNodeByID = function (id) {
  20241. var mesh = this.getMeshByID(id);
  20242. if (mesh) {
  20243. return mesh;
  20244. }
  20245. var light = this.getLightByID(id);
  20246. if (light) {
  20247. return light;
  20248. }
  20249. var camera = this.getCameraByID(id);
  20250. if (camera) {
  20251. return camera;
  20252. }
  20253. var bone = this.getBoneByID(id);
  20254. return bone;
  20255. };
  20256. Scene.prototype.getNodeByName = function (name) {
  20257. var mesh = this.getMeshByName(name);
  20258. if (mesh) {
  20259. return mesh;
  20260. }
  20261. var light = this.getLightByName(name);
  20262. if (light) {
  20263. return light;
  20264. }
  20265. var camera = this.getCameraByName(name);
  20266. if (camera) {
  20267. return camera;
  20268. }
  20269. var bone = this.getBoneByName(name);
  20270. return bone;
  20271. };
  20272. Scene.prototype.getMeshByName = function (name) {
  20273. for (var index = 0; index < this.meshes.length; index++) {
  20274. if (this.meshes[index].name === name) {
  20275. return this.meshes[index];
  20276. }
  20277. }
  20278. return null;
  20279. };
  20280. Scene.prototype.getTransformNodeByName = function (name) {
  20281. for (var index = 0; index < this.transformNodes.length; index++) {
  20282. if (this.transformNodes[index].name === name) {
  20283. return this.transformNodes[index];
  20284. }
  20285. }
  20286. return null;
  20287. };
  20288. Scene.prototype.getSoundByName = function (name) {
  20289. var index;
  20290. if (BABYLON.AudioEngine) {
  20291. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20292. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20293. return this.mainSoundTrack.soundCollection[index];
  20294. }
  20295. }
  20296. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20297. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20298. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20299. return this.soundTracks[sdIndex].soundCollection[index];
  20300. }
  20301. }
  20302. }
  20303. }
  20304. return null;
  20305. };
  20306. Scene.prototype.getLastSkeletonByID = function (id) {
  20307. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20308. if (this.skeletons[index].id === id) {
  20309. return this.skeletons[index];
  20310. }
  20311. }
  20312. return null;
  20313. };
  20314. Scene.prototype.getSkeletonById = function (id) {
  20315. for (var index = 0; index < this.skeletons.length; index++) {
  20316. if (this.skeletons[index].id === id) {
  20317. return this.skeletons[index];
  20318. }
  20319. }
  20320. return null;
  20321. };
  20322. Scene.prototype.getSkeletonByName = function (name) {
  20323. for (var index = 0; index < this.skeletons.length; index++) {
  20324. if (this.skeletons[index].name === name) {
  20325. return this.skeletons[index];
  20326. }
  20327. }
  20328. return null;
  20329. };
  20330. Scene.prototype.getMorphTargetManagerById = function (id) {
  20331. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20332. if (this.morphTargetManagers[index].uniqueId === id) {
  20333. return this.morphTargetManagers[index];
  20334. }
  20335. }
  20336. return null;
  20337. };
  20338. Scene.prototype.isActiveMesh = function (mesh) {
  20339. return (this._activeMeshes.indexOf(mesh) !== -1);
  20340. };
  20341. /**
  20342. * Return a the first highlight layer of the scene with a given name.
  20343. * @param name The name of the highlight layer to look for.
  20344. * @return The highlight layer if found otherwise null.
  20345. */
  20346. Scene.prototype.getHighlightLayerByName = function (name) {
  20347. for (var index = 0; index < this.highlightLayers.length; index++) {
  20348. if (this.highlightLayers[index].name === name) {
  20349. return this.highlightLayers[index];
  20350. }
  20351. }
  20352. return null;
  20353. };
  20354. Object.defineProperty(Scene.prototype, "uid", {
  20355. /**
  20356. * Return a unique id as a string which can serve as an identifier for the scene
  20357. */
  20358. get: function () {
  20359. if (!this._uid) {
  20360. this._uid = BABYLON.Tools.RandomId();
  20361. }
  20362. return this._uid;
  20363. },
  20364. enumerable: true,
  20365. configurable: true
  20366. });
  20367. /**
  20368. * Add an externaly attached data from its key.
  20369. * This method call will fail and return false, if such key already exists.
  20370. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20371. * @param key the unique key that identifies the data
  20372. * @param data the data object to associate to the key for this Engine instance
  20373. * @return true if no such key were already present and the data was added successfully, false otherwise
  20374. */
  20375. Scene.prototype.addExternalData = function (key, data) {
  20376. if (!this._externalData) {
  20377. this._externalData = new BABYLON.StringDictionary();
  20378. }
  20379. return this._externalData.add(key, data);
  20380. };
  20381. /**
  20382. * Get an externaly attached data from its key
  20383. * @param key the unique key that identifies the data
  20384. * @return the associated data, if present (can be null), or undefined if not present
  20385. */
  20386. Scene.prototype.getExternalData = function (key) {
  20387. if (!this._externalData) {
  20388. return null;
  20389. }
  20390. return this._externalData.get(key);
  20391. };
  20392. /**
  20393. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20394. * @param key the unique key that identifies the data
  20395. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20396. * @return the associated data, can be null if the factory returned null.
  20397. */
  20398. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20399. if (!this._externalData) {
  20400. this._externalData = new BABYLON.StringDictionary();
  20401. }
  20402. return this._externalData.getOrAddWithFactory(key, factory);
  20403. };
  20404. /**
  20405. * Remove an externaly attached data from the Engine instance
  20406. * @param key the unique key that identifies the data
  20407. * @return true if the data was successfully removed, false if it doesn't exist
  20408. */
  20409. Scene.prototype.removeExternalData = function (key) {
  20410. return this._externalData.remove(key);
  20411. };
  20412. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20413. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20414. var material = subMesh.getMaterial();
  20415. if (mesh.showSubMeshesBoundingBox) {
  20416. var boundingInfo = subMesh.getBoundingInfo();
  20417. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20418. }
  20419. if (material) {
  20420. // Render targets
  20421. if (material.getRenderTargetTextures) {
  20422. if (this._processedMaterials.indexOf(material) === -1) {
  20423. this._processedMaterials.push(material);
  20424. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20425. }
  20426. }
  20427. // Dispatch
  20428. this._activeIndices.addCount(subMesh.indexCount, false);
  20429. this._renderingManager.dispatch(subMesh);
  20430. }
  20431. }
  20432. };
  20433. Scene.prototype._isInIntermediateRendering = function () {
  20434. return this._intermediateRendering;
  20435. };
  20436. /**
  20437. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20438. */
  20439. Scene.prototype.freezeActiveMeshes = function () {
  20440. this._evaluateActiveMeshes();
  20441. this._activeMeshesFrozen = true;
  20442. return this;
  20443. };
  20444. /**
  20445. * Use this function to restart evaluating active meshes on every frame
  20446. */
  20447. Scene.prototype.unfreezeActiveMeshes = function () {
  20448. this._activeMeshesFrozen = false;
  20449. return this;
  20450. };
  20451. Scene.prototype._evaluateActiveMeshes = function () {
  20452. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20453. return;
  20454. }
  20455. if (!this.activeCamera) {
  20456. return;
  20457. }
  20458. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20459. this.activeCamera._activeMeshes.reset();
  20460. this._activeMeshes.reset();
  20461. this._renderingManager.reset();
  20462. this._processedMaterials.reset();
  20463. this._activeParticleSystems.reset();
  20464. this._activeSkeletons.reset();
  20465. this._softwareSkinnedMeshes.reset();
  20466. if (this._boundingBoxRenderer) {
  20467. this._boundingBoxRenderer.reset();
  20468. }
  20469. // Meshes
  20470. var meshes;
  20471. var len;
  20472. if (this._selectionOctree) {
  20473. var selection = this._selectionOctree.select(this._frustumPlanes);
  20474. meshes = selection.data;
  20475. len = selection.length;
  20476. }
  20477. else {
  20478. len = this.meshes.length;
  20479. meshes = this.meshes;
  20480. }
  20481. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20482. var mesh = meshes[meshIndex];
  20483. if (mesh.isBlocked) {
  20484. continue;
  20485. }
  20486. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20487. if (!mesh.isReady() || !mesh.isEnabled()) {
  20488. continue;
  20489. }
  20490. mesh.computeWorldMatrix();
  20491. // Intersections
  20492. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20493. this._meshesForIntersections.pushNoDuplicate(mesh);
  20494. }
  20495. // Switch to current LOD
  20496. var meshLOD = mesh.getLOD(this.activeCamera);
  20497. if (!meshLOD) {
  20498. continue;
  20499. }
  20500. mesh._preActivate();
  20501. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20502. this._activeMeshes.push(mesh);
  20503. this.activeCamera._activeMeshes.push(mesh);
  20504. mesh._activate(this._renderId);
  20505. if (meshLOD !== mesh) {
  20506. meshLOD._activate(this._renderId);
  20507. }
  20508. this._activeMesh(mesh, meshLOD);
  20509. }
  20510. }
  20511. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20512. // Particle systems
  20513. if (this.particlesEnabled) {
  20514. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20515. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20516. var particleSystem = this.particleSystems[particleIndex];
  20517. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20518. continue;
  20519. }
  20520. var emitter = particleSystem.emitter;
  20521. if (!emitter.position || emitter.isEnabled()) {
  20522. this._activeParticleSystems.push(particleSystem);
  20523. particleSystem.animate();
  20524. this._renderingManager.dispatchParticles(particleSystem);
  20525. }
  20526. }
  20527. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20528. }
  20529. };
  20530. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20531. if (mesh.skeleton && this.skeletonsEnabled) {
  20532. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20533. mesh.skeleton.prepare();
  20534. }
  20535. if (!mesh.computeBonesUsingShaders) {
  20536. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20537. }
  20538. }
  20539. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20540. var boundingInfo = sourceMesh.getBoundingInfo();
  20541. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20542. }
  20543. if (mesh && mesh.subMeshes) {
  20544. // Submeshes Octrees
  20545. var len;
  20546. var subMeshes;
  20547. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20548. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20549. len = intersections.length;
  20550. subMeshes = intersections.data;
  20551. }
  20552. else {
  20553. subMeshes = mesh.subMeshes;
  20554. len = subMeshes.length;
  20555. }
  20556. for (var subIndex = 0; subIndex < len; subIndex++) {
  20557. var subMesh = subMeshes[subIndex];
  20558. this._evaluateSubMesh(subMesh, mesh);
  20559. }
  20560. }
  20561. };
  20562. Scene.prototype.updateTransformMatrix = function (force) {
  20563. if (!this.activeCamera) {
  20564. return;
  20565. }
  20566. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20567. };
  20568. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20569. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20570. };
  20571. Scene.prototype._renderForCamera = function (camera) {
  20572. if (camera && camera._skipRendering) {
  20573. return;
  20574. }
  20575. var engine = this._engine;
  20576. this.activeCamera = camera;
  20577. if (!this.activeCamera)
  20578. throw new Error("Active camera not set");
  20579. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20580. // Viewport
  20581. engine.setViewport(this.activeCamera.viewport);
  20582. // Camera
  20583. this.resetCachedMaterial();
  20584. this._renderId++;
  20585. this.activeCamera.update();
  20586. this.updateTransformMatrix();
  20587. if (camera._alternateCamera) {
  20588. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20589. this._alternateRendering = true;
  20590. }
  20591. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20592. // Meshes
  20593. this._evaluateActiveMeshes();
  20594. // Software skinning
  20595. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20596. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20597. mesh.applySkeleton(mesh.skeleton);
  20598. }
  20599. // Render targets
  20600. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20601. var needsRestoreFrameBuffer = false;
  20602. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20603. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20604. }
  20605. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20606. this._intermediateRendering = true;
  20607. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20608. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20609. var renderTarget = this._renderTargets.data[renderIndex];
  20610. if (renderTarget._shouldRender()) {
  20611. this._renderId++;
  20612. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20613. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20614. }
  20615. }
  20616. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20617. this._intermediateRendering = false;
  20618. this._renderId++;
  20619. needsRestoreFrameBuffer = true; // Restore back buffer
  20620. }
  20621. // Render HighlightLayer Texture
  20622. var stencilState = this._engine.getStencilBuffer();
  20623. var renderhighlights = false;
  20624. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20625. this._intermediateRendering = true;
  20626. for (var i = 0; i < this.highlightLayers.length; i++) {
  20627. var highlightLayer = this.highlightLayers[i];
  20628. if (highlightLayer.shouldRender() &&
  20629. (!highlightLayer.camera ||
  20630. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20631. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20632. renderhighlights = true;
  20633. var renderTarget = highlightLayer._mainTexture;
  20634. if (renderTarget._shouldRender()) {
  20635. this._renderId++;
  20636. renderTarget.render(false, false);
  20637. needsRestoreFrameBuffer = true;
  20638. }
  20639. }
  20640. }
  20641. this._intermediateRendering = false;
  20642. this._renderId++;
  20643. }
  20644. if (needsRestoreFrameBuffer) {
  20645. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20646. }
  20647. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20648. // Prepare Frame
  20649. this.postProcessManager._prepareFrame();
  20650. // Backgrounds
  20651. var layerIndex;
  20652. var layer;
  20653. if (this.layers.length) {
  20654. engine.setDepthBuffer(false);
  20655. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20656. layer = this.layers[layerIndex];
  20657. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20658. layer.render();
  20659. }
  20660. }
  20661. engine.setDepthBuffer(true);
  20662. }
  20663. // Activate HighlightLayer stencil
  20664. if (renderhighlights) {
  20665. this._engine.setStencilBuffer(true);
  20666. }
  20667. // Render
  20668. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20669. this._renderingManager.render(null, null, true, true);
  20670. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20671. // Restore HighlightLayer stencil
  20672. if (renderhighlights) {
  20673. this._engine.setStencilBuffer(stencilState);
  20674. }
  20675. // Bounding boxes
  20676. if (this._boundingBoxRenderer) {
  20677. this._boundingBoxRenderer.render();
  20678. }
  20679. // Lens flares
  20680. if (this.lensFlaresEnabled) {
  20681. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20682. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20683. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20684. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20685. lensFlareSystem.render();
  20686. }
  20687. }
  20688. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20689. }
  20690. // Foregrounds
  20691. if (this.layers.length) {
  20692. engine.setDepthBuffer(false);
  20693. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20694. layer = this.layers[layerIndex];
  20695. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20696. layer.render();
  20697. }
  20698. }
  20699. engine.setDepthBuffer(true);
  20700. }
  20701. // Highlight Layer
  20702. if (renderhighlights) {
  20703. engine.setDepthBuffer(false);
  20704. for (var i = 0; i < this.highlightLayers.length; i++) {
  20705. if (this.highlightLayers[i].shouldRender()) {
  20706. this.highlightLayers[i].render();
  20707. }
  20708. }
  20709. engine.setDepthBuffer(true);
  20710. }
  20711. // Finalize frame
  20712. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20713. // Reset some special arrays
  20714. this._renderTargets.reset();
  20715. this._alternateRendering = false;
  20716. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20717. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20718. };
  20719. Scene.prototype._processSubCameras = function (camera) {
  20720. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20721. this._renderForCamera(camera);
  20722. return;
  20723. }
  20724. // Update camera
  20725. if (this.activeCamera) {
  20726. this.activeCamera.update();
  20727. }
  20728. // rig cameras
  20729. for (var index = 0; index < camera._rigCameras.length; index++) {
  20730. this._renderForCamera(camera._rigCameras[index]);
  20731. }
  20732. this.activeCamera = camera;
  20733. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20734. };
  20735. Scene.prototype._checkIntersections = function () {
  20736. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20737. var sourceMesh = this._meshesForIntersections.data[index];
  20738. if (!sourceMesh.actionManager) {
  20739. continue;
  20740. }
  20741. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20742. var action = sourceMesh.actionManager.actions[actionIndex];
  20743. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20744. var parameters = action.getTriggerParameter();
  20745. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20746. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20747. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20748. if (areIntersecting && currentIntersectionInProgress === -1) {
  20749. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20750. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20751. sourceMesh._intersectionsInProgress.push(otherMesh);
  20752. }
  20753. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20754. sourceMesh._intersectionsInProgress.push(otherMesh);
  20755. }
  20756. }
  20757. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20758. //They intersected, and now they don't.
  20759. //is this trigger an exit trigger? execute an event.
  20760. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20761. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20762. }
  20763. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20764. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20765. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20766. }
  20767. }
  20768. }
  20769. }
  20770. }
  20771. };
  20772. Scene.prototype.render = function () {
  20773. if (this.isDisposed) {
  20774. return;
  20775. }
  20776. this._activeParticles.fetchNewFrame();
  20777. this._totalVertices.fetchNewFrame();
  20778. this._activeIndices.fetchNewFrame();
  20779. this._activeBones.fetchNewFrame();
  20780. this._meshesForIntersections.reset();
  20781. this.resetCachedMaterial();
  20782. this.onBeforeAnimationsObservable.notifyObservers(this);
  20783. // Actions
  20784. if (this.actionManager) {
  20785. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20786. }
  20787. //Simplification Queue
  20788. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20789. this.simplificationQueue.executeNext();
  20790. }
  20791. if (this._engine.isDeterministicLockStep()) {
  20792. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20793. var defaultFPS = (60.0 / 1000.0);
  20794. var defaultFrameTime = 1000 / 60; // frame time in MS
  20795. if (this._physicsEngine) {
  20796. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  20797. }
  20798. var stepsTaken = 0;
  20799. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20800. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20801. internalSteps = Math.min(internalSteps, maxSubSteps);
  20802. do {
  20803. this.onBeforeStepObservable.notifyObservers(this);
  20804. // Animations
  20805. this._animationRatio = defaultFrameTime * defaultFPS;
  20806. this._animate();
  20807. this.onAfterAnimationsObservable.notifyObservers(this);
  20808. // Physics
  20809. if (this._physicsEngine) {
  20810. this.onBeforePhysicsObservable.notifyObservers(this);
  20811. this._physicsEngine._step(defaultFrameTime / 1000);
  20812. this.onAfterPhysicsObservable.notifyObservers(this);
  20813. }
  20814. this.onAfterStepObservable.notifyObservers(this);
  20815. this._currentStepId++;
  20816. stepsTaken++;
  20817. deltaTime -= defaultFrameTime;
  20818. } while (deltaTime > 0 && stepsTaken < internalSteps);
  20819. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  20820. }
  20821. else {
  20822. // Animations
  20823. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20824. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20825. this._animate();
  20826. this.onAfterAnimationsObservable.notifyObservers(this);
  20827. // Physics
  20828. if (this._physicsEngine) {
  20829. this.onBeforePhysicsObservable.notifyObservers(this);
  20830. this._physicsEngine._step(deltaTime / 1000.0);
  20831. this.onAfterPhysicsObservable.notifyObservers(this);
  20832. }
  20833. }
  20834. // update gamepad manager
  20835. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20836. this._gamepadManager._checkGamepadsStatus();
  20837. }
  20838. // Before render
  20839. this.onBeforeRenderObservable.notifyObservers(this);
  20840. // Customs render targets
  20841. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20842. var engine = this.getEngine();
  20843. var currentActiveCamera = this.activeCamera;
  20844. if (this.renderTargetsEnabled) {
  20845. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20846. this._intermediateRendering = true;
  20847. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20848. var renderTarget = this.customRenderTargets[customIndex];
  20849. if (renderTarget._shouldRender()) {
  20850. this._renderId++;
  20851. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20852. if (!this.activeCamera)
  20853. throw new Error("Active camera not set");
  20854. // Viewport
  20855. engine.setViewport(this.activeCamera.viewport);
  20856. // Camera
  20857. this.updateTransformMatrix();
  20858. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20859. }
  20860. }
  20861. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20862. this._intermediateRendering = false;
  20863. this._renderId++;
  20864. }
  20865. // Restore back buffer
  20866. if (this.customRenderTargets.length > 0) {
  20867. engine.restoreDefaultFramebuffer();
  20868. }
  20869. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20870. this.activeCamera = currentActiveCamera;
  20871. // Procedural textures
  20872. if (this.proceduralTexturesEnabled) {
  20873. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20874. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20875. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20876. if (proceduralTexture._shouldRender()) {
  20877. proceduralTexture.render();
  20878. }
  20879. }
  20880. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20881. }
  20882. // Clear
  20883. if (this.autoClearDepthAndStencil || this.autoClear) {
  20884. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20885. }
  20886. // Shadows
  20887. if (this.shadowsEnabled) {
  20888. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20889. var light = this.lights[lightIndex];
  20890. var shadowGenerator = light.getShadowGenerator();
  20891. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20892. var shadowMap = (shadowGenerator.getShadowMap());
  20893. if (this.textures.indexOf(shadowMap) !== -1) {
  20894. this._renderTargets.push(shadowMap);
  20895. }
  20896. }
  20897. }
  20898. }
  20899. // Depth renderer
  20900. if (this._depthRenderer) {
  20901. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20902. }
  20903. // Geometry renderer
  20904. if (this._geometryBufferRenderer) {
  20905. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20906. }
  20907. // RenderPipeline
  20908. if (this._postProcessRenderPipelineManager) {
  20909. this._postProcessRenderPipelineManager.update();
  20910. }
  20911. // Multi-cameras?
  20912. if (this.activeCameras.length > 0) {
  20913. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20914. if (cameraIndex > 0) {
  20915. this._engine.clear(null, false, true, true);
  20916. }
  20917. this._processSubCameras(this.activeCameras[cameraIndex]);
  20918. }
  20919. }
  20920. else {
  20921. if (!this.activeCamera) {
  20922. throw new Error("No camera defined");
  20923. }
  20924. this._processSubCameras(this.activeCamera);
  20925. }
  20926. // Intersection checks
  20927. this._checkIntersections();
  20928. // Update the audio listener attached to the camera
  20929. if (BABYLON.AudioEngine) {
  20930. this._updateAudioParameters();
  20931. }
  20932. // After render
  20933. if (this.afterRender) {
  20934. this.afterRender();
  20935. }
  20936. this.onAfterRenderObservable.notifyObservers(this);
  20937. // Cleaning
  20938. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20939. var data = this._toBeDisposed.data[index];
  20940. if (data) {
  20941. data.dispose();
  20942. }
  20943. this._toBeDisposed[index] = null;
  20944. }
  20945. this._toBeDisposed.reset();
  20946. if (this.dumpNextRenderTargets) {
  20947. this.dumpNextRenderTargets = false;
  20948. }
  20949. this._activeBones.addCount(0, true);
  20950. this._activeIndices.addCount(0, true);
  20951. this._activeParticles.addCount(0, true);
  20952. };
  20953. Scene.prototype._updateAudioParameters = function () {
  20954. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20955. return;
  20956. }
  20957. var listeningCamera;
  20958. var audioEngine = BABYLON.Engine.audioEngine;
  20959. if (this.activeCameras.length > 0) {
  20960. listeningCamera = this.activeCameras[0];
  20961. }
  20962. else {
  20963. listeningCamera = this.activeCamera;
  20964. }
  20965. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20966. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20967. // for VR cameras
  20968. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20969. listeningCamera = listeningCamera.rigCameras[0];
  20970. }
  20971. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20972. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20973. cameraDirection.normalize();
  20974. // To avoid some errors on GearVR
  20975. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20976. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20977. }
  20978. var i;
  20979. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20980. var sound = this.mainSoundTrack.soundCollection[i];
  20981. if (sound.useCustomAttenuation) {
  20982. sound.updateDistanceFromListener();
  20983. }
  20984. }
  20985. for (i = 0; i < this.soundTracks.length; i++) {
  20986. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20987. sound = this.soundTracks[i].soundCollection[j];
  20988. if (sound.useCustomAttenuation) {
  20989. sound.updateDistanceFromListener();
  20990. }
  20991. }
  20992. }
  20993. }
  20994. };
  20995. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20996. // Audio
  20997. get: function () {
  20998. return this._audioEnabled;
  20999. },
  21000. set: function (value) {
  21001. this._audioEnabled = value;
  21002. if (BABYLON.AudioEngine) {
  21003. if (this._audioEnabled) {
  21004. this._enableAudio();
  21005. }
  21006. else {
  21007. this._disableAudio();
  21008. }
  21009. }
  21010. },
  21011. enumerable: true,
  21012. configurable: true
  21013. });
  21014. Scene.prototype._disableAudio = function () {
  21015. var i;
  21016. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21017. this.mainSoundTrack.soundCollection[i].pause();
  21018. }
  21019. for (i = 0; i < this.soundTracks.length; i++) {
  21020. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21021. this.soundTracks[i].soundCollection[j].pause();
  21022. }
  21023. }
  21024. };
  21025. Scene.prototype._enableAudio = function () {
  21026. var i;
  21027. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21028. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21029. this.mainSoundTrack.soundCollection[i].play();
  21030. }
  21031. }
  21032. for (i = 0; i < this.soundTracks.length; i++) {
  21033. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21034. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21035. this.soundTracks[i].soundCollection[j].play();
  21036. }
  21037. }
  21038. }
  21039. };
  21040. Object.defineProperty(Scene.prototype, "headphone", {
  21041. get: function () {
  21042. return this._headphone;
  21043. },
  21044. set: function (value) {
  21045. this._headphone = value;
  21046. if (BABYLON.AudioEngine) {
  21047. if (this._headphone) {
  21048. this._switchAudioModeForHeadphones();
  21049. }
  21050. else {
  21051. this._switchAudioModeForNormalSpeakers();
  21052. }
  21053. }
  21054. },
  21055. enumerable: true,
  21056. configurable: true
  21057. });
  21058. Scene.prototype._switchAudioModeForHeadphones = function () {
  21059. this.mainSoundTrack.switchPanningModelToHRTF();
  21060. for (var i = 0; i < this.soundTracks.length; i++) {
  21061. this.soundTracks[i].switchPanningModelToHRTF();
  21062. }
  21063. };
  21064. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21065. this.mainSoundTrack.switchPanningModelToEqualPower();
  21066. for (var i = 0; i < this.soundTracks.length; i++) {
  21067. this.soundTracks[i].switchPanningModelToEqualPower();
  21068. }
  21069. };
  21070. Scene.prototype.enableDepthRenderer = function () {
  21071. if (this._depthRenderer) {
  21072. return this._depthRenderer;
  21073. }
  21074. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21075. return this._depthRenderer;
  21076. };
  21077. Scene.prototype.disableDepthRenderer = function () {
  21078. if (!this._depthRenderer) {
  21079. return;
  21080. }
  21081. this._depthRenderer.dispose();
  21082. this._depthRenderer = null;
  21083. };
  21084. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21085. if (ratio === void 0) { ratio = 1; }
  21086. if (this._geometryBufferRenderer) {
  21087. return this._geometryBufferRenderer;
  21088. }
  21089. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21090. if (!this._geometryBufferRenderer.isSupported) {
  21091. this._geometryBufferRenderer = null;
  21092. }
  21093. return this._geometryBufferRenderer;
  21094. };
  21095. Scene.prototype.disableGeometryBufferRenderer = function () {
  21096. if (!this._geometryBufferRenderer) {
  21097. return;
  21098. }
  21099. this._geometryBufferRenderer.dispose();
  21100. this._geometryBufferRenderer = null;
  21101. };
  21102. Scene.prototype.freezeMaterials = function () {
  21103. for (var i = 0; i < this.materials.length; i++) {
  21104. this.materials[i].freeze();
  21105. }
  21106. };
  21107. Scene.prototype.unfreezeMaterials = function () {
  21108. for (var i = 0; i < this.materials.length; i++) {
  21109. this.materials[i].unfreeze();
  21110. }
  21111. };
  21112. Scene.prototype.dispose = function () {
  21113. this.beforeRender = null;
  21114. this.afterRender = null;
  21115. this.skeletons = [];
  21116. this.morphTargetManagers = [];
  21117. this.importedMeshesFiles = new Array();
  21118. this.stopAllAnimations();
  21119. this.resetCachedMaterial();
  21120. if (this._depthRenderer) {
  21121. this._depthRenderer.dispose();
  21122. }
  21123. if (this._gamepadManager) {
  21124. this._gamepadManager.dispose();
  21125. this._gamepadManager = null;
  21126. }
  21127. // Smart arrays
  21128. if (this.activeCamera) {
  21129. this.activeCamera._activeMeshes.dispose();
  21130. this.activeCamera = null;
  21131. }
  21132. this._activeMeshes.dispose();
  21133. this._renderingManager.dispose();
  21134. this._processedMaterials.dispose();
  21135. this._activeParticleSystems.dispose();
  21136. this._activeSkeletons.dispose();
  21137. this._softwareSkinnedMeshes.dispose();
  21138. this._renderTargets.dispose();
  21139. if (this._boundingBoxRenderer) {
  21140. this._boundingBoxRenderer.dispose();
  21141. }
  21142. this._meshesForIntersections.dispose();
  21143. this._toBeDisposed.dispose();
  21144. // Debug layer
  21145. if (this._debugLayer) {
  21146. this._debugLayer.hide();
  21147. }
  21148. // Events
  21149. this.onDisposeObservable.notifyObservers(this);
  21150. this.onDisposeObservable.clear();
  21151. this.onBeforeRenderObservable.clear();
  21152. this.onAfterRenderObservable.clear();
  21153. this.OnBeforeRenderTargetsRenderObservable.clear();
  21154. this.OnAfterRenderTargetsRenderObservable.clear();
  21155. this.onAfterStepObservable.clear();
  21156. this.onBeforeStepObservable.clear();
  21157. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21158. this.onAfterActiveMeshesEvaluationObservable.clear();
  21159. this.onBeforeParticlesRenderingObservable.clear();
  21160. this.onAfterParticlesRenderingObservable.clear();
  21161. this.onBeforeSpritesRenderingObservable.clear();
  21162. this.onAfterSpritesRenderingObservable.clear();
  21163. this.onBeforeDrawPhaseObservable.clear();
  21164. this.onAfterDrawPhaseObservable.clear();
  21165. this.onBeforePhysicsObservable.clear();
  21166. this.onAfterPhysicsObservable.clear();
  21167. this.onBeforeAnimationsObservable.clear();
  21168. this.onAfterAnimationsObservable.clear();
  21169. this.onDataLoadedObservable.clear();
  21170. this.detachControl();
  21171. // Release sounds & sounds tracks
  21172. if (BABYLON.AudioEngine) {
  21173. this.disposeSounds();
  21174. }
  21175. // VR Helper
  21176. if (this.VRHelper) {
  21177. this.VRHelper.dispose();
  21178. }
  21179. // Detach cameras
  21180. var canvas = this._engine.getRenderingCanvas();
  21181. if (canvas) {
  21182. var index;
  21183. for (index = 0; index < this.cameras.length; index++) {
  21184. this.cameras[index].detachControl(canvas);
  21185. }
  21186. }
  21187. // Release lights
  21188. while (this.lights.length) {
  21189. this.lights[0].dispose();
  21190. }
  21191. // Release meshes
  21192. while (this.meshes.length) {
  21193. this.meshes[0].dispose(true);
  21194. }
  21195. while (this.transformNodes.length) {
  21196. this.removeTransformNode(this.transformNodes[0]);
  21197. }
  21198. // Release cameras
  21199. while (this.cameras.length) {
  21200. this.cameras[0].dispose();
  21201. }
  21202. // Release materials
  21203. if (this.defaultMaterial) {
  21204. this.defaultMaterial.dispose();
  21205. }
  21206. while (this.multiMaterials.length) {
  21207. this.multiMaterials[0].dispose();
  21208. }
  21209. while (this.materials.length) {
  21210. this.materials[0].dispose();
  21211. }
  21212. // Release particles
  21213. while (this.particleSystems.length) {
  21214. this.particleSystems[0].dispose();
  21215. }
  21216. // Release sprites
  21217. while (this.spriteManagers.length) {
  21218. this.spriteManagers[0].dispose();
  21219. }
  21220. // Release postProcesses
  21221. while (this.postProcesses.length) {
  21222. this.postProcesses[0].dispose();
  21223. }
  21224. // Release layers
  21225. while (this.layers.length) {
  21226. this.layers[0].dispose();
  21227. }
  21228. while (this.highlightLayers.length) {
  21229. this.highlightLayers[0].dispose();
  21230. }
  21231. // Release textures
  21232. while (this.textures.length) {
  21233. this.textures[0].dispose();
  21234. }
  21235. // Release UBO
  21236. this._sceneUbo.dispose();
  21237. if (this._alternateSceneUbo) {
  21238. this._alternateSceneUbo.dispose();
  21239. }
  21240. // Post-processes
  21241. this.postProcessManager.dispose();
  21242. if (this._postProcessRenderPipelineManager) {
  21243. this._postProcessRenderPipelineManager.dispose();
  21244. }
  21245. // Physics
  21246. if (this._physicsEngine) {
  21247. this.disablePhysicsEngine();
  21248. }
  21249. // Remove from engine
  21250. index = this._engine.scenes.indexOf(this);
  21251. if (index > -1) {
  21252. this._engine.scenes.splice(index, 1);
  21253. }
  21254. this._engine.wipeCaches(true);
  21255. this._isDisposed = true;
  21256. };
  21257. Object.defineProperty(Scene.prototype, "isDisposed", {
  21258. get: function () {
  21259. return this._isDisposed;
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. // Release sounds & sounds tracks
  21265. Scene.prototype.disposeSounds = function () {
  21266. if (!this._mainSoundTrack) {
  21267. return;
  21268. }
  21269. this.mainSoundTrack.dispose();
  21270. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21271. this.soundTracks[scIndex].dispose();
  21272. }
  21273. };
  21274. // Octrees
  21275. Scene.prototype.getWorldExtends = function () {
  21276. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21277. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21278. for (var index = 0; index < this.meshes.length; index++) {
  21279. var mesh = this.meshes[index];
  21280. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21281. continue;
  21282. }
  21283. mesh.computeWorldMatrix(true);
  21284. var boundingInfo = mesh.getBoundingInfo();
  21285. var minBox = boundingInfo.boundingBox.minimumWorld;
  21286. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21287. BABYLON.Tools.CheckExtends(minBox, min, max);
  21288. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21289. }
  21290. return {
  21291. min: min,
  21292. max: max
  21293. };
  21294. };
  21295. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21296. if (maxCapacity === void 0) { maxCapacity = 64; }
  21297. if (maxDepth === void 0) { maxDepth = 2; }
  21298. if (!this._selectionOctree) {
  21299. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21300. }
  21301. var worldExtends = this.getWorldExtends();
  21302. // Update octree
  21303. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21304. return this._selectionOctree;
  21305. };
  21306. // Picking
  21307. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21308. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21309. var result = BABYLON.Ray.Zero();
  21310. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21311. return result;
  21312. };
  21313. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21314. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21315. var engine = this._engine;
  21316. if (!camera) {
  21317. if (!this.activeCamera)
  21318. throw new Error("Active camera not set");
  21319. camera = this.activeCamera;
  21320. }
  21321. var cameraViewport = camera.viewport;
  21322. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21323. // Moving coordinates to local viewport world
  21324. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21325. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21326. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21327. return this;
  21328. };
  21329. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21330. var result = BABYLON.Ray.Zero();
  21331. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21332. return result;
  21333. };
  21334. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21335. if (!BABYLON.PickingInfo) {
  21336. return this;
  21337. }
  21338. var engine = this._engine;
  21339. if (!camera) {
  21340. if (!this.activeCamera)
  21341. throw new Error("Active camera not set");
  21342. camera = this.activeCamera;
  21343. }
  21344. var cameraViewport = camera.viewport;
  21345. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21346. var identity = BABYLON.Matrix.Identity();
  21347. // Moving coordinates to local viewport world
  21348. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21349. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21350. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21351. return this;
  21352. };
  21353. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21354. if (!BABYLON.PickingInfo) {
  21355. return null;
  21356. }
  21357. var pickingInfo = null;
  21358. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21359. var mesh = this.meshes[meshIndex];
  21360. if (predicate) {
  21361. if (!predicate(mesh)) {
  21362. continue;
  21363. }
  21364. }
  21365. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21366. continue;
  21367. }
  21368. var world = mesh.getWorldMatrix();
  21369. var ray = rayFunction(world);
  21370. var result = mesh.intersects(ray, fastCheck);
  21371. if (!result || !result.hit)
  21372. continue;
  21373. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21374. continue;
  21375. pickingInfo = result;
  21376. if (fastCheck) {
  21377. break;
  21378. }
  21379. }
  21380. return pickingInfo || new BABYLON.PickingInfo();
  21381. };
  21382. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21383. if (!BABYLON.PickingInfo) {
  21384. return null;
  21385. }
  21386. var pickingInfos = new Array();
  21387. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21388. var mesh = this.meshes[meshIndex];
  21389. if (predicate) {
  21390. if (!predicate(mesh)) {
  21391. continue;
  21392. }
  21393. }
  21394. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21395. continue;
  21396. }
  21397. var world = mesh.getWorldMatrix();
  21398. var ray = rayFunction(world);
  21399. var result = mesh.intersects(ray, false);
  21400. if (!result || !result.hit)
  21401. continue;
  21402. pickingInfos.push(result);
  21403. }
  21404. return pickingInfos;
  21405. };
  21406. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21407. if (!BABYLON.PickingInfo) {
  21408. return null;
  21409. }
  21410. var pickingInfo = null;
  21411. if (!camera) {
  21412. if (!this.activeCamera) {
  21413. return null;
  21414. }
  21415. camera = this.activeCamera;
  21416. }
  21417. if (this.spriteManagers.length > 0) {
  21418. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21419. var spriteManager = this.spriteManagers[spriteIndex];
  21420. if (!spriteManager.isPickable) {
  21421. continue;
  21422. }
  21423. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21424. if (!result || !result.hit)
  21425. continue;
  21426. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21427. continue;
  21428. pickingInfo = result;
  21429. if (fastCheck) {
  21430. break;
  21431. }
  21432. }
  21433. }
  21434. return pickingInfo || new BABYLON.PickingInfo();
  21435. };
  21436. /** Launch a ray to try to pick a mesh in the scene
  21437. * @param x position on screen
  21438. * @param y position on screen
  21439. * @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
  21440. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21441. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21442. */
  21443. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21444. var _this = this;
  21445. if (!BABYLON.PickingInfo) {
  21446. return null;
  21447. }
  21448. return this._internalPick(function (world) {
  21449. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21450. return _this._tempPickingRay;
  21451. }, predicate, fastCheck);
  21452. };
  21453. /** Launch a ray to try to pick a sprite in the scene
  21454. * @param x position on screen
  21455. * @param y position on screen
  21456. * @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
  21457. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21458. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21459. */
  21460. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21461. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21462. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21463. };
  21464. /** Use the given ray to pick a mesh in the scene
  21465. * @param ray The ray to use to pick meshes
  21466. * @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
  21467. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21468. */
  21469. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21470. var _this = this;
  21471. return this._internalPick(function (world) {
  21472. if (!_this._pickWithRayInverseMatrix) {
  21473. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21474. }
  21475. world.invertToRef(_this._pickWithRayInverseMatrix);
  21476. if (!_this._cachedRayForTransform) {
  21477. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21478. }
  21479. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21480. return _this._cachedRayForTransform;
  21481. }, predicate, fastCheck);
  21482. };
  21483. /**
  21484. * Launch a ray to try to pick a mesh in the scene
  21485. * @param x X position on screen
  21486. * @param y Y position on screen
  21487. * @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
  21488. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21489. */
  21490. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21491. var _this = this;
  21492. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21493. };
  21494. /**
  21495. * Launch a ray to try to pick a mesh in the scene
  21496. * @param ray Ray to use
  21497. * @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
  21498. */
  21499. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21500. var _this = this;
  21501. return this._internalMultiPick(function (world) {
  21502. if (!_this._pickWithRayInverseMatrix) {
  21503. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21504. }
  21505. world.invertToRef(_this._pickWithRayInverseMatrix);
  21506. if (!_this._cachedRayForTransform) {
  21507. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21508. }
  21509. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21510. return _this._cachedRayForTransform;
  21511. }, predicate);
  21512. };
  21513. Scene.prototype.setPointerOverMesh = function (mesh) {
  21514. if (this._pointerOverMesh === mesh) {
  21515. return;
  21516. }
  21517. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21518. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21519. }
  21520. this._pointerOverMesh = mesh;
  21521. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21522. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21523. }
  21524. };
  21525. Scene.prototype.getPointerOverMesh = function () {
  21526. return this._pointerOverMesh;
  21527. };
  21528. Scene.prototype.setPointerOverSprite = function (sprite) {
  21529. if (this._pointerOverSprite === sprite) {
  21530. return;
  21531. }
  21532. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21533. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21534. }
  21535. this._pointerOverSprite = sprite;
  21536. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21537. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21538. }
  21539. };
  21540. Scene.prototype.getPointerOverSprite = function () {
  21541. return this._pointerOverSprite;
  21542. };
  21543. // Physics
  21544. Scene.prototype.getPhysicsEngine = function () {
  21545. return this._physicsEngine;
  21546. };
  21547. /**
  21548. * Enables physics to the current scene
  21549. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21550. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21551. * @return {boolean} was the physics engine initialized
  21552. */
  21553. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21554. if (gravity === void 0) { gravity = null; }
  21555. if (this._physicsEngine) {
  21556. return true;
  21557. }
  21558. try {
  21559. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21560. return true;
  21561. }
  21562. catch (e) {
  21563. BABYLON.Tools.Error(e.message);
  21564. return false;
  21565. }
  21566. };
  21567. Scene.prototype.disablePhysicsEngine = function () {
  21568. if (!this._physicsEngine) {
  21569. return;
  21570. }
  21571. this._physicsEngine.dispose();
  21572. this._physicsEngine = null;
  21573. };
  21574. Scene.prototype.isPhysicsEnabled = function () {
  21575. return this._physicsEngine !== undefined;
  21576. };
  21577. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21578. var mesh = compound.parts[0].mesh;
  21579. if (mesh.physicsImpostor) {
  21580. mesh.physicsImpostor.dispose();
  21581. mesh.physicsImpostor = null;
  21582. }
  21583. };
  21584. // Misc.
  21585. Scene.prototype._rebuildGeometries = function () {
  21586. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21587. var geometry = _a[_i];
  21588. geometry._rebuild();
  21589. }
  21590. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21591. var mesh = _c[_b];
  21592. mesh._rebuild();
  21593. }
  21594. if (this.postProcessManager) {
  21595. this.postProcessManager._rebuild();
  21596. }
  21597. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21598. var layer = _e[_d];
  21599. layer._rebuild();
  21600. }
  21601. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21602. var highlightLayer = _g[_f];
  21603. highlightLayer._rebuild();
  21604. }
  21605. if (this._boundingBoxRenderer) {
  21606. this._boundingBoxRenderer._rebuild();
  21607. }
  21608. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21609. var system = _j[_h];
  21610. system.rebuild();
  21611. }
  21612. if (this._postProcessRenderPipelineManager) {
  21613. this._postProcessRenderPipelineManager._rebuild();
  21614. }
  21615. };
  21616. Scene.prototype._rebuildTextures = function () {
  21617. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21618. var texture = _a[_i];
  21619. texture._rebuild();
  21620. }
  21621. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21622. };
  21623. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21624. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21625. if (replace === void 0) { replace = false; }
  21626. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21627. // Dispose existing camera or light in replace mode.
  21628. if (replace) {
  21629. if (this.activeCamera) {
  21630. this.activeCamera.dispose();
  21631. this.activeCamera = null;
  21632. }
  21633. if (this.lights) {
  21634. for (var i = 0; i < this.lights.length; i++) {
  21635. this.lights[i].dispose();
  21636. }
  21637. }
  21638. }
  21639. // Light
  21640. if (this.lights.length === 0) {
  21641. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21642. }
  21643. // Camera
  21644. if (!this.activeCamera) {
  21645. var worldExtends = this.getWorldExtends();
  21646. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21647. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21648. var camera;
  21649. var radius = worldSize.length() * 1.5;
  21650. if (createArcRotateCamera) {
  21651. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21652. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21653. arcRotateCamera.wheelPrecision = 100 / radius;
  21654. camera = arcRotateCamera;
  21655. }
  21656. else {
  21657. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21658. freeCamera.setTarget(worldCenter);
  21659. camera = freeCamera;
  21660. }
  21661. camera.minZ = radius * 0.01;
  21662. camera.maxZ = radius * 100;
  21663. camera.speed = radius * 0.2;
  21664. this.activeCamera = camera;
  21665. var canvas = this.getEngine().getRenderingCanvas();
  21666. if (attachCameraControls && canvas) {
  21667. camera.attachControl(canvas);
  21668. }
  21669. }
  21670. };
  21671. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21672. if (pbr === void 0) { pbr = false; }
  21673. if (scale === void 0) { scale = 1000; }
  21674. if (blur === void 0) { blur = 0; }
  21675. if (environmentTexture) {
  21676. this.environmentTexture = environmentTexture;
  21677. }
  21678. if (!this.environmentTexture) {
  21679. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21680. return null;
  21681. }
  21682. // Skybox
  21683. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21684. if (pbr) {
  21685. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21686. hdrSkyboxMaterial.backFaceCulling = false;
  21687. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21688. if (hdrSkyboxMaterial.reflectionTexture) {
  21689. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21690. }
  21691. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21692. hdrSkyboxMaterial.disableLighting = true;
  21693. hdrSkyboxMaterial.twoSidedLighting = true;
  21694. hdrSkybox.infiniteDistance = true;
  21695. hdrSkybox.material = hdrSkyboxMaterial;
  21696. }
  21697. else {
  21698. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21699. skyboxMaterial.backFaceCulling = false;
  21700. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21701. if (skyboxMaterial.reflectionTexture) {
  21702. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21703. }
  21704. skyboxMaterial.disableLighting = true;
  21705. hdrSkybox.infiniteDistance = true;
  21706. hdrSkybox.material = skyboxMaterial;
  21707. }
  21708. return hdrSkybox;
  21709. };
  21710. Scene.prototype.createDefaultEnvironment = function (options) {
  21711. if (BABYLON.EnvironmentHelper) {
  21712. return new BABYLON.EnvironmentHelper(options, this);
  21713. }
  21714. return null;
  21715. };
  21716. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21717. if (webVROptions === void 0) { webVROptions = {}; }
  21718. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21719. };
  21720. // Tags
  21721. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21722. if (tagsQuery === undefined) {
  21723. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21724. return list;
  21725. }
  21726. var listByTags = [];
  21727. forEach = forEach || (function (item) { return; });
  21728. for (var i in list) {
  21729. var item = list[i];
  21730. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21731. listByTags.push(item);
  21732. forEach(item);
  21733. }
  21734. }
  21735. return listByTags;
  21736. };
  21737. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21738. return this._getByTags(this.meshes, tagsQuery, forEach);
  21739. };
  21740. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21741. return this._getByTags(this.cameras, tagsQuery, forEach);
  21742. };
  21743. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21744. return this._getByTags(this.lights, tagsQuery, forEach);
  21745. };
  21746. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21747. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21748. };
  21749. /**
  21750. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21751. * This allowed control for front to back rendering or reversly depending of the special needs.
  21752. *
  21753. * @param renderingGroupId The rendering group id corresponding to its index
  21754. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21755. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21756. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21757. */
  21758. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21759. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21760. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21761. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21762. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21763. };
  21764. /**
  21765. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21766. *
  21767. * @param renderingGroupId The rendering group id corresponding to its index
  21768. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21769. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21770. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21771. */
  21772. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21773. if (depth === void 0) { depth = true; }
  21774. if (stencil === void 0) { stencil = true; }
  21775. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21776. };
  21777. /**
  21778. * Will flag all materials as dirty to trigger new shader compilation
  21779. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21780. */
  21781. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21782. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21783. var material = _a[_i];
  21784. if (predicate && !predicate(material)) {
  21785. continue;
  21786. }
  21787. material.markAsDirty(flag);
  21788. }
  21789. };
  21790. // Statics
  21791. Scene._FOGMODE_NONE = 0;
  21792. Scene._FOGMODE_EXP = 1;
  21793. Scene._FOGMODE_EXP2 = 2;
  21794. Scene._FOGMODE_LINEAR = 3;
  21795. Scene._uniqueIdCounter = 0;
  21796. Scene.MinDeltaTime = 1.0;
  21797. Scene.MaxDeltaTime = 1000.0;
  21798. /** The distance in pixel that you have to move to prevent some events */
  21799. Scene.DragMovementThreshold = 10; // in pixels
  21800. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21801. Scene.LongPressDelay = 500; // in milliseconds
  21802. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21803. Scene.DoubleClickDelay = 300; // in milliseconds
  21804. /** If you need to check double click without raising a single click at first click, enable this flag */
  21805. Scene.ExclusiveDoubleClickMode = false;
  21806. return Scene;
  21807. }());
  21808. BABYLON.Scene = Scene;
  21809. })(BABYLON || (BABYLON = {}));
  21810. //# sourceMappingURL=babylon.scene.js.map
  21811. var BABYLON;
  21812. (function (BABYLON) {
  21813. var Buffer = /** @class */ (function () {
  21814. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21815. if (instanced === void 0) { instanced = false; }
  21816. if (engine instanceof BABYLON.Mesh) {
  21817. this._engine = engine.getScene().getEngine();
  21818. }
  21819. else {
  21820. this._engine = engine;
  21821. }
  21822. this._updatable = updatable;
  21823. this._data = data;
  21824. this._strideSize = stride;
  21825. if (!postponeInternalCreation) {
  21826. this.create();
  21827. }
  21828. this._instanced = instanced;
  21829. this._instanceDivisor = instanced ? 1 : 0;
  21830. }
  21831. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21832. // a lot of these parameters are ignored as they are overriden by the buffer
  21833. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21834. };
  21835. // Properties
  21836. Buffer.prototype.isUpdatable = function () {
  21837. return this._updatable;
  21838. };
  21839. Buffer.prototype.getData = function () {
  21840. return this._data;
  21841. };
  21842. Buffer.prototype.getBuffer = function () {
  21843. return this._buffer;
  21844. };
  21845. Buffer.prototype.getStrideSize = function () {
  21846. return this._strideSize;
  21847. };
  21848. Buffer.prototype.getIsInstanced = function () {
  21849. return this._instanced;
  21850. };
  21851. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21852. get: function () {
  21853. return this._instanceDivisor;
  21854. },
  21855. set: function (value) {
  21856. this._instanceDivisor = value;
  21857. if (value == 0) {
  21858. this._instanced = false;
  21859. }
  21860. else {
  21861. this._instanced = true;
  21862. }
  21863. },
  21864. enumerable: true,
  21865. configurable: true
  21866. });
  21867. // Methods
  21868. Buffer.prototype.create = function (data) {
  21869. if (data === void 0) { data = null; }
  21870. if (!data && this._buffer) {
  21871. return; // nothing to do
  21872. }
  21873. data = data || this._data;
  21874. if (!data) {
  21875. return;
  21876. }
  21877. if (!this._buffer) {
  21878. if (this._updatable) {
  21879. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21880. this._data = data;
  21881. }
  21882. else {
  21883. this._buffer = this._engine.createVertexBuffer(data);
  21884. }
  21885. }
  21886. else if (this._updatable) {
  21887. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21888. this._data = data;
  21889. }
  21890. };
  21891. Buffer.prototype._rebuild = function () {
  21892. this._buffer = null;
  21893. this.create(this._data);
  21894. };
  21895. Buffer.prototype.update = function (data) {
  21896. this.create(data);
  21897. };
  21898. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21899. if (!this._buffer) {
  21900. return;
  21901. }
  21902. if (this._updatable) {
  21903. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21904. this._data = null;
  21905. }
  21906. };
  21907. Buffer.prototype.dispose = function () {
  21908. if (!this._buffer) {
  21909. return;
  21910. }
  21911. if (this._engine._releaseBuffer(this._buffer)) {
  21912. this._buffer = null;
  21913. }
  21914. };
  21915. return Buffer;
  21916. }());
  21917. BABYLON.Buffer = Buffer;
  21918. })(BABYLON || (BABYLON = {}));
  21919. //# sourceMappingURL=babylon.buffer.js.map
  21920. var BABYLON;
  21921. (function (BABYLON) {
  21922. var VertexBuffer = /** @class */ (function () {
  21923. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21924. if (!stride) {
  21925. // Deduce stride from kind
  21926. switch (kind) {
  21927. case VertexBuffer.PositionKind:
  21928. stride = 3;
  21929. break;
  21930. case VertexBuffer.NormalKind:
  21931. stride = 3;
  21932. break;
  21933. case VertexBuffer.UVKind:
  21934. case VertexBuffer.UV2Kind:
  21935. case VertexBuffer.UV3Kind:
  21936. case VertexBuffer.UV4Kind:
  21937. case VertexBuffer.UV5Kind:
  21938. case VertexBuffer.UV6Kind:
  21939. stride = 2;
  21940. break;
  21941. case VertexBuffer.TangentKind:
  21942. case VertexBuffer.ColorKind:
  21943. stride = 4;
  21944. break;
  21945. case VertexBuffer.MatricesIndicesKind:
  21946. case VertexBuffer.MatricesIndicesExtraKind:
  21947. stride = 4;
  21948. break;
  21949. case VertexBuffer.MatricesWeightsKind:
  21950. case VertexBuffer.MatricesWeightsExtraKind:
  21951. default:
  21952. stride = 4;
  21953. break;
  21954. }
  21955. }
  21956. if (data instanceof BABYLON.Buffer) {
  21957. if (!stride) {
  21958. stride = data.getStrideSize();
  21959. }
  21960. this._buffer = data;
  21961. this._ownsBuffer = false;
  21962. }
  21963. else {
  21964. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21965. this._ownsBuffer = true;
  21966. }
  21967. this._stride = stride;
  21968. this._offset = offset ? offset : 0;
  21969. this._size = size ? size : stride;
  21970. this._kind = kind;
  21971. }
  21972. VertexBuffer.prototype._rebuild = function () {
  21973. if (!this._buffer) {
  21974. return;
  21975. }
  21976. this._buffer._rebuild();
  21977. };
  21978. /**
  21979. * Returns the kind of the VertexBuffer (string).
  21980. */
  21981. VertexBuffer.prototype.getKind = function () {
  21982. return this._kind;
  21983. };
  21984. // Properties
  21985. /**
  21986. * Boolean : is the VertexBuffer updatable ?
  21987. */
  21988. VertexBuffer.prototype.isUpdatable = function () {
  21989. return this._buffer.isUpdatable();
  21990. };
  21991. /**
  21992. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21993. */
  21994. VertexBuffer.prototype.getData = function () {
  21995. return this._buffer.getData();
  21996. };
  21997. /**
  21998. * Returns the WebGLBuffer associated to the VertexBuffer.
  21999. */
  22000. VertexBuffer.prototype.getBuffer = function () {
  22001. return this._buffer.getBuffer();
  22002. };
  22003. /**
  22004. * Returns the stride of the VertexBuffer (integer).
  22005. */
  22006. VertexBuffer.prototype.getStrideSize = function () {
  22007. return this._stride;
  22008. };
  22009. /**
  22010. * Returns the offset (integer).
  22011. */
  22012. VertexBuffer.prototype.getOffset = function () {
  22013. return this._offset;
  22014. };
  22015. /**
  22016. * Returns the VertexBuffer total size (integer).
  22017. */
  22018. VertexBuffer.prototype.getSize = function () {
  22019. return this._size;
  22020. };
  22021. /**
  22022. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22023. */
  22024. VertexBuffer.prototype.getIsInstanced = function () {
  22025. return this._buffer.getIsInstanced();
  22026. };
  22027. /**
  22028. * Returns the instancing divisor, zero for non-instanced (integer).
  22029. */
  22030. VertexBuffer.prototype.getInstanceDivisor = function () {
  22031. return this._buffer.instanceDivisor;
  22032. };
  22033. // Methods
  22034. /**
  22035. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22036. * Returns the created WebGLBuffer.
  22037. */
  22038. VertexBuffer.prototype.create = function (data) {
  22039. return this._buffer.create(data);
  22040. };
  22041. /**
  22042. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22043. * Returns the updated WebGLBuffer.
  22044. */
  22045. VertexBuffer.prototype.update = function (data) {
  22046. return this._buffer.update(data);
  22047. };
  22048. /**
  22049. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22050. * Returns the directly updated WebGLBuffer.
  22051. */
  22052. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22053. return this._buffer.updateDirectly(data, offset);
  22054. };
  22055. /**
  22056. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22057. */
  22058. VertexBuffer.prototype.dispose = function () {
  22059. if (this._ownsBuffer) {
  22060. this._buffer.dispose();
  22061. }
  22062. };
  22063. Object.defineProperty(VertexBuffer, "PositionKind", {
  22064. get: function () {
  22065. return VertexBuffer._PositionKind;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(VertexBuffer, "NormalKind", {
  22071. get: function () {
  22072. return VertexBuffer._NormalKind;
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. Object.defineProperty(VertexBuffer, "TangentKind", {
  22078. get: function () {
  22079. return VertexBuffer._TangentKind;
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Object.defineProperty(VertexBuffer, "UVKind", {
  22085. get: function () {
  22086. return VertexBuffer._UVKind;
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22092. get: function () {
  22093. return VertexBuffer._UV2Kind;
  22094. },
  22095. enumerable: true,
  22096. configurable: true
  22097. });
  22098. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22099. get: function () {
  22100. return VertexBuffer._UV3Kind;
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22106. get: function () {
  22107. return VertexBuffer._UV4Kind;
  22108. },
  22109. enumerable: true,
  22110. configurable: true
  22111. });
  22112. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22113. get: function () {
  22114. return VertexBuffer._UV5Kind;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22120. get: function () {
  22121. return VertexBuffer._UV6Kind;
  22122. },
  22123. enumerable: true,
  22124. configurable: true
  22125. });
  22126. Object.defineProperty(VertexBuffer, "ColorKind", {
  22127. get: function () {
  22128. return VertexBuffer._ColorKind;
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22134. get: function () {
  22135. return VertexBuffer._MatricesIndicesKind;
  22136. },
  22137. enumerable: true,
  22138. configurable: true
  22139. });
  22140. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22141. get: function () {
  22142. return VertexBuffer._MatricesWeightsKind;
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22148. get: function () {
  22149. return VertexBuffer._MatricesIndicesExtraKind;
  22150. },
  22151. enumerable: true,
  22152. configurable: true
  22153. });
  22154. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22155. get: function () {
  22156. return VertexBuffer._MatricesWeightsExtraKind;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. // Enums
  22162. VertexBuffer._PositionKind = "position";
  22163. VertexBuffer._NormalKind = "normal";
  22164. VertexBuffer._TangentKind = "tangent";
  22165. VertexBuffer._UVKind = "uv";
  22166. VertexBuffer._UV2Kind = "uv2";
  22167. VertexBuffer._UV3Kind = "uv3";
  22168. VertexBuffer._UV4Kind = "uv4";
  22169. VertexBuffer._UV5Kind = "uv5";
  22170. VertexBuffer._UV6Kind = "uv6";
  22171. VertexBuffer._ColorKind = "color";
  22172. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22173. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22174. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22175. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22176. return VertexBuffer;
  22177. }());
  22178. BABYLON.VertexBuffer = VertexBuffer;
  22179. })(BABYLON || (BABYLON = {}));
  22180. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22181. var BABYLON;
  22182. (function (BABYLON) {
  22183. var InternalTexture = /** @class */ (function () {
  22184. function InternalTexture(engine, dataSource) {
  22185. this.onLoadedObservable = new BABYLON.Observable();
  22186. // Private
  22187. this._initialSlot = -1;
  22188. this._designatedSlot = -1;
  22189. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22190. this._references = 1;
  22191. this._engine = engine;
  22192. this._dataSource = dataSource;
  22193. this._webGLTexture = engine._createTexture();
  22194. }
  22195. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22196. get: function () {
  22197. return this._dataSource;
  22198. },
  22199. enumerable: true,
  22200. configurable: true
  22201. });
  22202. InternalTexture.prototype.incrementReferences = function () {
  22203. this._references++;
  22204. };
  22205. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22206. if (depth === void 0) { depth = 1; }
  22207. this.width = width;
  22208. this.height = height;
  22209. this.depth = depth;
  22210. this.baseWidth = width;
  22211. this.baseHeight = height;
  22212. this.baseDepth = depth;
  22213. this._size = width * height * depth;
  22214. };
  22215. InternalTexture.prototype._rebuild = function () {
  22216. var _this = this;
  22217. var proxy;
  22218. this.isReady = false;
  22219. this._cachedCoordinatesMode = null;
  22220. this._cachedWrapU = null;
  22221. this._cachedWrapV = null;
  22222. this._cachedAnisotropicFilteringLevel = null;
  22223. switch (this._dataSource) {
  22224. case InternalTexture.DATASOURCE_TEMP:
  22225. return;
  22226. case InternalTexture.DATASOURCE_URL:
  22227. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22228. _this.isReady = true;
  22229. }, null, this._buffer, undefined, this.format);
  22230. proxy._swapAndDie(this);
  22231. return;
  22232. case InternalTexture.DATASOURCE_RAW:
  22233. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22234. proxy._swapAndDie(this);
  22235. this.isReady = true;
  22236. return;
  22237. case InternalTexture.DATASOURCE_RAW3D:
  22238. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22239. proxy._swapAndDie(this);
  22240. this.isReady = true;
  22241. return;
  22242. case InternalTexture.DATASOURCE_DYNAMIC:
  22243. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22244. proxy._swapAndDie(this);
  22245. // The engine will make sure to update content so no need to flag it as isReady = true
  22246. return;
  22247. case InternalTexture.DATASOURCE_RENDERTARGET:
  22248. var options = new BABYLON.RenderTargetCreationOptions();
  22249. options.generateDepthBuffer = this._generateDepthBuffer;
  22250. options.generateMipMaps = this.generateMipMaps;
  22251. options.generateStencilBuffer = this._generateStencilBuffer;
  22252. options.samplingMode = this.samplingMode;
  22253. options.type = this.type;
  22254. if (this.isCube) {
  22255. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22256. }
  22257. else {
  22258. var size = {
  22259. width: this.width,
  22260. height: this.height
  22261. };
  22262. proxy = this._engine.createRenderTargetTexture(size, options);
  22263. }
  22264. proxy._swapAndDie(this);
  22265. this.isReady = true;
  22266. return;
  22267. case InternalTexture.DATASOURCE_CUBE:
  22268. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22269. _this.isReady = true;
  22270. }, null, this.format, this._extension);
  22271. proxy._swapAndDie(this);
  22272. return;
  22273. case InternalTexture.DATASOURCE_CUBERAW:
  22274. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22275. proxy._swapAndDie(this);
  22276. this.isReady = true;
  22277. return;
  22278. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22279. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22280. if (proxy) {
  22281. proxy._swapAndDie(_this);
  22282. }
  22283. _this.isReady = true;
  22284. }, null, this.format, this._extension);
  22285. return;
  22286. }
  22287. };
  22288. InternalTexture.prototype._swapAndDie = function (target) {
  22289. target._webGLTexture = this._webGLTexture;
  22290. if (this._framebuffer) {
  22291. target._framebuffer = this._framebuffer;
  22292. }
  22293. if (this._depthStencilBuffer) {
  22294. target._depthStencilBuffer = this._depthStencilBuffer;
  22295. }
  22296. if (this._lodTextureHigh) {
  22297. if (target._lodTextureHigh) {
  22298. target._lodTextureHigh.dispose();
  22299. }
  22300. target._lodTextureHigh = this._lodTextureHigh;
  22301. }
  22302. if (this._lodTextureMid) {
  22303. if (target._lodTextureMid) {
  22304. target._lodTextureMid.dispose();
  22305. }
  22306. target._lodTextureMid = this._lodTextureMid;
  22307. }
  22308. if (this._lodTextureLow) {
  22309. if (target._lodTextureLow) {
  22310. target._lodTextureLow.dispose();
  22311. }
  22312. target._lodTextureLow = this._lodTextureLow;
  22313. }
  22314. var cache = this._engine.getLoadedTexturesCache();
  22315. var index = cache.indexOf(this);
  22316. if (index !== -1) {
  22317. cache.splice(index, 1);
  22318. }
  22319. };
  22320. InternalTexture.prototype.dispose = function () {
  22321. if (!this._webGLTexture) {
  22322. return;
  22323. }
  22324. this._references--;
  22325. if (this._references === 0) {
  22326. this._engine._releaseTexture(this);
  22327. this._webGLTexture = null;
  22328. }
  22329. };
  22330. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22331. InternalTexture.DATASOURCE_URL = 1;
  22332. InternalTexture.DATASOURCE_TEMP = 2;
  22333. InternalTexture.DATASOURCE_RAW = 3;
  22334. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22335. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22336. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22337. InternalTexture.DATASOURCE_CUBE = 7;
  22338. InternalTexture.DATASOURCE_CUBERAW = 8;
  22339. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22340. InternalTexture.DATASOURCE_RAW3D = 10;
  22341. return InternalTexture;
  22342. }());
  22343. BABYLON.InternalTexture = InternalTexture;
  22344. })(BABYLON || (BABYLON = {}));
  22345. //# sourceMappingURL=babylon.internalTexture.js.map
  22346. var BABYLON;
  22347. (function (BABYLON) {
  22348. var BaseTexture = /** @class */ (function () {
  22349. function BaseTexture(scene) {
  22350. this._hasAlpha = false;
  22351. this.getAlphaFromRGB = false;
  22352. this.level = 1;
  22353. this.coordinatesIndex = 0;
  22354. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22355. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22356. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22357. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22358. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22359. this.isCube = false;
  22360. this.is3D = false;
  22361. this.gammaSpace = true;
  22362. this.invertZ = false;
  22363. this.lodLevelInAlpha = false;
  22364. this.lodGenerationOffset = 0.0;
  22365. this.lodGenerationScale = 0.8;
  22366. this.isRenderTarget = false;
  22367. this.animations = new Array();
  22368. /**
  22369. * An event triggered when the texture is disposed.
  22370. * @type {BABYLON.Observable}
  22371. */
  22372. this.onDisposeObservable = new BABYLON.Observable();
  22373. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22374. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22375. if (this._scene) {
  22376. this._scene.textures.push(this);
  22377. }
  22378. this._uid = null;
  22379. }
  22380. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22381. get: function () {
  22382. return this._hasAlpha;
  22383. },
  22384. set: function (value) {
  22385. if (this._hasAlpha === value) {
  22386. return;
  22387. }
  22388. this._hasAlpha = value;
  22389. if (this._scene) {
  22390. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22391. }
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22397. get: function () {
  22398. return this._coordinatesMode;
  22399. },
  22400. set: function (value) {
  22401. if (this._coordinatesMode === value) {
  22402. return;
  22403. }
  22404. this._coordinatesMode = value;
  22405. if (this._scene) {
  22406. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22407. }
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. Object.defineProperty(BaseTexture.prototype, "uid", {
  22413. get: function () {
  22414. if (!this._uid) {
  22415. this._uid = BABYLON.Tools.RandomId();
  22416. }
  22417. return this._uid;
  22418. },
  22419. enumerable: true,
  22420. configurable: true
  22421. });
  22422. BaseTexture.prototype.toString = function () {
  22423. return this.name;
  22424. };
  22425. BaseTexture.prototype.getClassName = function () {
  22426. return "BaseTexture";
  22427. };
  22428. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22429. set: function (callback) {
  22430. if (this._onDisposeObserver) {
  22431. this.onDisposeObservable.remove(this._onDisposeObserver);
  22432. }
  22433. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22439. get: function () {
  22440. return true;
  22441. },
  22442. enumerable: true,
  22443. configurable: true
  22444. });
  22445. BaseTexture.prototype.getScene = function () {
  22446. return this._scene;
  22447. };
  22448. BaseTexture.prototype.getTextureMatrix = function () {
  22449. return BABYLON.Matrix.IdentityReadOnly;
  22450. };
  22451. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22452. return BABYLON.Matrix.IdentityReadOnly;
  22453. };
  22454. BaseTexture.prototype.getInternalTexture = function () {
  22455. return this._texture;
  22456. };
  22457. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22458. return !this.isBlocking || this.isReady();
  22459. };
  22460. BaseTexture.prototype.isReady = function () {
  22461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22462. this.delayLoad();
  22463. return false;
  22464. }
  22465. if (this._texture) {
  22466. return this._texture.isReady;
  22467. }
  22468. return false;
  22469. };
  22470. BaseTexture.prototype.getSize = function () {
  22471. if (this._texture && this._texture.width) {
  22472. return new BABYLON.Size(this._texture.width, this._texture.height);
  22473. }
  22474. if (this._texture && this._texture._size) {
  22475. return new BABYLON.Size(this._texture._size, this._texture._size);
  22476. }
  22477. return BABYLON.Size.Zero();
  22478. };
  22479. BaseTexture.prototype.getBaseSize = function () {
  22480. if (!this.isReady() || !this._texture)
  22481. return BABYLON.Size.Zero();
  22482. if (this._texture._size) {
  22483. return new BABYLON.Size(this._texture._size, this._texture._size);
  22484. }
  22485. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22486. };
  22487. BaseTexture.prototype.scale = function (ratio) {
  22488. };
  22489. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22490. get: function () {
  22491. return false;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22497. if (!this._scene) {
  22498. return null;
  22499. }
  22500. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22501. for (var index = 0; index < texturesCache.length; index++) {
  22502. var texturesCacheEntry = texturesCache[index];
  22503. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22504. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22505. texturesCacheEntry.incrementReferences();
  22506. return texturesCacheEntry;
  22507. }
  22508. }
  22509. }
  22510. return null;
  22511. };
  22512. BaseTexture.prototype._rebuild = function () {
  22513. };
  22514. BaseTexture.prototype.delayLoad = function () {
  22515. };
  22516. BaseTexture.prototype.clone = function () {
  22517. return null;
  22518. };
  22519. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22520. get: function () {
  22521. if (!this._texture) {
  22522. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22523. }
  22524. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22530. get: function () {
  22531. if (!this._texture) {
  22532. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22533. }
  22534. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. BaseTexture.prototype.readPixels = function (faceIndex) {
  22540. if (faceIndex === void 0) { faceIndex = 0; }
  22541. if (!this._texture) {
  22542. return null;
  22543. }
  22544. var size = this.getSize();
  22545. var scene = this.getScene();
  22546. if (!scene) {
  22547. return null;
  22548. }
  22549. var engine = scene.getEngine();
  22550. if (this._texture.isCube) {
  22551. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22552. }
  22553. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22554. };
  22555. BaseTexture.prototype.releaseInternalTexture = function () {
  22556. if (this._texture) {
  22557. this._texture.dispose();
  22558. this._texture = null;
  22559. }
  22560. };
  22561. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22562. get: function () {
  22563. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22564. return null;
  22565. }
  22566. if (!this._texture._sphericalPolynomial) {
  22567. this._texture._sphericalPolynomial =
  22568. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22569. }
  22570. return this._texture._sphericalPolynomial;
  22571. },
  22572. set: function (value) {
  22573. if (this._texture) {
  22574. this._texture._sphericalPolynomial = value;
  22575. }
  22576. },
  22577. enumerable: true,
  22578. configurable: true
  22579. });
  22580. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22581. get: function () {
  22582. if (this._texture) {
  22583. return this._texture._lodTextureHigh;
  22584. }
  22585. return null;
  22586. },
  22587. enumerable: true,
  22588. configurable: true
  22589. });
  22590. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22591. get: function () {
  22592. if (this._texture) {
  22593. return this._texture._lodTextureMid;
  22594. }
  22595. return null;
  22596. },
  22597. enumerable: true,
  22598. configurable: true
  22599. });
  22600. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22601. get: function () {
  22602. if (this._texture) {
  22603. return this._texture._lodTextureLow;
  22604. }
  22605. return null;
  22606. },
  22607. enumerable: true,
  22608. configurable: true
  22609. });
  22610. BaseTexture.prototype.dispose = function () {
  22611. if (!this._scene) {
  22612. return;
  22613. }
  22614. // Animations
  22615. this._scene.stopAnimation(this);
  22616. // Remove from scene
  22617. this._scene._removePendingData(this);
  22618. var index = this._scene.textures.indexOf(this);
  22619. if (index >= 0) {
  22620. this._scene.textures.splice(index, 1);
  22621. }
  22622. if (this._texture === undefined) {
  22623. return;
  22624. }
  22625. // Release
  22626. this.releaseInternalTexture();
  22627. // Callback
  22628. this.onDisposeObservable.notifyObservers(this);
  22629. this.onDisposeObservable.clear();
  22630. };
  22631. BaseTexture.prototype.serialize = function () {
  22632. if (!this.name) {
  22633. return null;
  22634. }
  22635. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22636. // Animations
  22637. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22638. return serializationObject;
  22639. };
  22640. BaseTexture.WhenAllReady = function (textures, callback) {
  22641. var numRemaining = textures.length;
  22642. if (numRemaining === 0) {
  22643. callback();
  22644. return;
  22645. }
  22646. var _loop_1 = function () {
  22647. texture = textures[i];
  22648. if (texture.isReady()) {
  22649. if (--numRemaining === 0) {
  22650. callback();
  22651. }
  22652. }
  22653. else {
  22654. onLoadObservable = texture.onLoadObservable;
  22655. var onLoadCallback_1 = function () {
  22656. onLoadObservable.removeCallback(onLoadCallback_1);
  22657. if (--numRemaining === 0) {
  22658. callback();
  22659. }
  22660. };
  22661. onLoadObservable.add(onLoadCallback_1);
  22662. }
  22663. };
  22664. var texture, onLoadObservable;
  22665. for (var i = 0; i < textures.length; i++) {
  22666. _loop_1();
  22667. }
  22668. };
  22669. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22670. __decorate([
  22671. BABYLON.serialize()
  22672. ], BaseTexture.prototype, "name", void 0);
  22673. __decorate([
  22674. BABYLON.serialize("hasAlpha")
  22675. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22676. __decorate([
  22677. BABYLON.serialize()
  22678. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22679. __decorate([
  22680. BABYLON.serialize()
  22681. ], BaseTexture.prototype, "level", void 0);
  22682. __decorate([
  22683. BABYLON.serialize()
  22684. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22685. __decorate([
  22686. BABYLON.serialize("coordinatesMode")
  22687. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22688. __decorate([
  22689. BABYLON.serialize()
  22690. ], BaseTexture.prototype, "wrapU", void 0);
  22691. __decorate([
  22692. BABYLON.serialize()
  22693. ], BaseTexture.prototype, "wrapV", void 0);
  22694. __decorate([
  22695. BABYLON.serialize()
  22696. ], BaseTexture.prototype, "wrapR", void 0);
  22697. __decorate([
  22698. BABYLON.serialize()
  22699. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22700. __decorate([
  22701. BABYLON.serialize()
  22702. ], BaseTexture.prototype, "isCube", void 0);
  22703. __decorate([
  22704. BABYLON.serialize()
  22705. ], BaseTexture.prototype, "is3D", void 0);
  22706. __decorate([
  22707. BABYLON.serialize()
  22708. ], BaseTexture.prototype, "gammaSpace", void 0);
  22709. __decorate([
  22710. BABYLON.serialize()
  22711. ], BaseTexture.prototype, "invertZ", void 0);
  22712. __decorate([
  22713. BABYLON.serialize()
  22714. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22715. __decorate([
  22716. BABYLON.serialize()
  22717. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22718. __decorate([
  22719. BABYLON.serialize()
  22720. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22721. __decorate([
  22722. BABYLON.serialize()
  22723. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22724. return BaseTexture;
  22725. }());
  22726. BABYLON.BaseTexture = BaseTexture;
  22727. })(BABYLON || (BABYLON = {}));
  22728. //# sourceMappingURL=babylon.baseTexture.js.map
  22729. var BABYLON;
  22730. (function (BABYLON) {
  22731. var Texture = /** @class */ (function (_super) {
  22732. __extends(Texture, _super);
  22733. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22734. if (noMipmap === void 0) { noMipmap = false; }
  22735. if (invertY === void 0) { invertY = true; }
  22736. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22737. if (onLoad === void 0) { onLoad = null; }
  22738. if (onError === void 0) { onError = null; }
  22739. if (buffer === void 0) { buffer = null; }
  22740. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22741. var _this = _super.call(this, scene) || this;
  22742. _this.uOffset = 0;
  22743. _this.vOffset = 0;
  22744. _this.uScale = 1.0;
  22745. _this.vScale = 1.0;
  22746. _this.uAng = 0;
  22747. _this.vAng = 0;
  22748. _this.wAng = 0;
  22749. _this._isBlocking = true;
  22750. _this.name = url || "";
  22751. _this.url = url;
  22752. _this._noMipmap = noMipmap;
  22753. _this._invertY = invertY;
  22754. _this._samplingMode = samplingMode;
  22755. _this._buffer = buffer;
  22756. _this._deleteBuffer = deleteBuffer;
  22757. if (format) {
  22758. _this._format = format;
  22759. }
  22760. scene = _this.getScene();
  22761. if (!scene) {
  22762. return _this;
  22763. }
  22764. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22765. var load = function () {
  22766. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22767. _this.onLoadObservable.notifyObservers(_this);
  22768. }
  22769. if (onLoad) {
  22770. onLoad();
  22771. }
  22772. if (!_this.isBlocking && scene) {
  22773. scene.resetCachedMaterial();
  22774. }
  22775. };
  22776. if (!_this.url) {
  22777. _this._delayedOnLoad = load;
  22778. _this._delayedOnError = onError;
  22779. return _this;
  22780. }
  22781. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22782. if (!_this._texture) {
  22783. if (!scene.useDelayedTextureLoading) {
  22784. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22785. if (deleteBuffer) {
  22786. delete _this._buffer;
  22787. }
  22788. }
  22789. else {
  22790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22791. _this._delayedOnLoad = load;
  22792. _this._delayedOnError = onError;
  22793. }
  22794. }
  22795. else {
  22796. if (_this._texture.isReady) {
  22797. BABYLON.Tools.SetImmediate(function () { return load(); });
  22798. }
  22799. else {
  22800. _this._texture.onLoadedObservable.add(load);
  22801. }
  22802. }
  22803. return _this;
  22804. }
  22805. Object.defineProperty(Texture.prototype, "noMipmap", {
  22806. get: function () {
  22807. return this._noMipmap;
  22808. },
  22809. enumerable: true,
  22810. configurable: true
  22811. });
  22812. Object.defineProperty(Texture.prototype, "isBlocking", {
  22813. get: function () {
  22814. return this._isBlocking;
  22815. },
  22816. set: function (value) {
  22817. this._isBlocking = value;
  22818. },
  22819. enumerable: true,
  22820. configurable: true
  22821. });
  22822. Object.defineProperty(Texture.prototype, "samplingMode", {
  22823. get: function () {
  22824. return this._samplingMode;
  22825. },
  22826. enumerable: true,
  22827. configurable: true
  22828. });
  22829. Texture.prototype.updateURL = function (url) {
  22830. this.url = url;
  22831. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22832. this.delayLoad();
  22833. };
  22834. Texture.prototype.delayLoad = function () {
  22835. var _this = this;
  22836. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22837. return;
  22838. }
  22839. var scene = this.getScene();
  22840. if (!scene) {
  22841. return;
  22842. }
  22843. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22844. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22845. if (!this._texture) {
  22846. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22847. if (this._deleteBuffer) {
  22848. delete this._buffer;
  22849. }
  22850. }
  22851. else {
  22852. if (this._texture.isReady) {
  22853. BABYLON.Tools.SetImmediate(function () {
  22854. if (!_this._delayedOnLoad) {
  22855. return;
  22856. }
  22857. _this._delayedOnLoad();
  22858. });
  22859. }
  22860. else {
  22861. if (this._delayedOnLoad) {
  22862. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22863. }
  22864. }
  22865. }
  22866. };
  22867. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22868. if (!this._texture) {
  22869. return;
  22870. }
  22871. var scene = this.getScene();
  22872. if (!scene) {
  22873. return;
  22874. }
  22875. this._samplingMode = samplingMode;
  22876. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22877. };
  22878. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22879. x *= this.uScale;
  22880. y *= this.vScale;
  22881. x -= 0.5 * this.uScale;
  22882. y -= 0.5 * this.vScale;
  22883. z -= 0.5;
  22884. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22885. t.x += 0.5 * this.uScale + this.uOffset;
  22886. t.y += 0.5 * this.vScale + this.vOffset;
  22887. t.z += 0.5;
  22888. };
  22889. Texture.prototype.getTextureMatrix = function () {
  22890. var _this = this;
  22891. if (this.uOffset === this._cachedUOffset &&
  22892. this.vOffset === this._cachedVOffset &&
  22893. this.uScale === this._cachedUScale &&
  22894. this.vScale === this._cachedVScale &&
  22895. this.uAng === this._cachedUAng &&
  22896. this.vAng === this._cachedVAng &&
  22897. this.wAng === this._cachedWAng) {
  22898. return this._cachedTextureMatrix;
  22899. }
  22900. this._cachedUOffset = this.uOffset;
  22901. this._cachedVOffset = this.vOffset;
  22902. this._cachedUScale = this.uScale;
  22903. this._cachedVScale = this.vScale;
  22904. this._cachedUAng = this.uAng;
  22905. this._cachedVAng = this.vAng;
  22906. this._cachedWAng = this.wAng;
  22907. if (!this._cachedTextureMatrix) {
  22908. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22909. this._rowGenerationMatrix = new BABYLON.Matrix();
  22910. this._t0 = BABYLON.Vector3.Zero();
  22911. this._t1 = BABYLON.Vector3.Zero();
  22912. this._t2 = BABYLON.Vector3.Zero();
  22913. }
  22914. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22915. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22916. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22917. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22918. this._t1.subtractInPlace(this._t0);
  22919. this._t2.subtractInPlace(this._t0);
  22920. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22921. this._cachedTextureMatrix.m[0] = this._t1.x;
  22922. this._cachedTextureMatrix.m[1] = this._t1.y;
  22923. this._cachedTextureMatrix.m[2] = this._t1.z;
  22924. this._cachedTextureMatrix.m[4] = this._t2.x;
  22925. this._cachedTextureMatrix.m[5] = this._t2.y;
  22926. this._cachedTextureMatrix.m[6] = this._t2.z;
  22927. this._cachedTextureMatrix.m[8] = this._t0.x;
  22928. this._cachedTextureMatrix.m[9] = this._t0.y;
  22929. this._cachedTextureMatrix.m[10] = this._t0.z;
  22930. var scene = this.getScene();
  22931. if (!scene) {
  22932. return this._cachedTextureMatrix;
  22933. }
  22934. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22935. return mat.hasTexture(_this);
  22936. });
  22937. return this._cachedTextureMatrix;
  22938. };
  22939. Texture.prototype.getReflectionTextureMatrix = function () {
  22940. var _this = this;
  22941. var scene = this.getScene();
  22942. if (!scene) {
  22943. return this._cachedTextureMatrix;
  22944. }
  22945. if (this.uOffset === this._cachedUOffset &&
  22946. this.vOffset === this._cachedVOffset &&
  22947. this.uScale === this._cachedUScale &&
  22948. this.vScale === this._cachedVScale &&
  22949. this.coordinatesMode === this._cachedCoordinatesMode) {
  22950. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22951. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22952. return this._cachedTextureMatrix;
  22953. }
  22954. }
  22955. else {
  22956. return this._cachedTextureMatrix;
  22957. }
  22958. }
  22959. if (!this._cachedTextureMatrix) {
  22960. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22961. }
  22962. if (!this._projectionModeMatrix) {
  22963. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22964. }
  22965. this._cachedUOffset = this.uOffset;
  22966. this._cachedVOffset = this.vOffset;
  22967. this._cachedUScale = this.uScale;
  22968. this._cachedVScale = this.vScale;
  22969. this._cachedCoordinatesMode = this.coordinatesMode;
  22970. switch (this.coordinatesMode) {
  22971. case Texture.PLANAR_MODE:
  22972. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22973. this._cachedTextureMatrix[0] = this.uScale;
  22974. this._cachedTextureMatrix[5] = this.vScale;
  22975. this._cachedTextureMatrix[12] = this.uOffset;
  22976. this._cachedTextureMatrix[13] = this.vOffset;
  22977. break;
  22978. case Texture.PROJECTION_MODE:
  22979. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22980. this._projectionModeMatrix.m[0] = 0.5;
  22981. this._projectionModeMatrix.m[5] = -0.5;
  22982. this._projectionModeMatrix.m[10] = 0.0;
  22983. this._projectionModeMatrix.m[12] = 0.5;
  22984. this._projectionModeMatrix.m[13] = 0.5;
  22985. this._projectionModeMatrix.m[14] = 1.0;
  22986. this._projectionModeMatrix.m[15] = 1.0;
  22987. var projectionMatrix = scene.getProjectionMatrix();
  22988. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22989. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22990. break;
  22991. default:
  22992. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22993. break;
  22994. }
  22995. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22996. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22997. });
  22998. return this._cachedTextureMatrix;
  22999. };
  23000. Texture.prototype.clone = function () {
  23001. var _this = this;
  23002. return BABYLON.SerializationHelper.Clone(function () {
  23003. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23004. }, this);
  23005. };
  23006. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23007. get: function () {
  23008. if (!this._onLoadObservable) {
  23009. this._onLoadObservable = new BABYLON.Observable();
  23010. }
  23011. return this._onLoadObservable;
  23012. },
  23013. enumerable: true,
  23014. configurable: true
  23015. });
  23016. Texture.prototype.serialize = function () {
  23017. var serializationObject = _super.prototype.serialize.call(this);
  23018. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23019. serializationObject.base64String = this._buffer;
  23020. serializationObject.name = serializationObject.name.replace("data:", "");
  23021. }
  23022. return serializationObject;
  23023. };
  23024. Texture.prototype.getClassName = function () {
  23025. return "Texture";
  23026. };
  23027. Texture.prototype.dispose = function () {
  23028. _super.prototype.dispose.call(this);
  23029. if (this.onLoadObservable) {
  23030. this.onLoadObservable.clear();
  23031. this._onLoadObservable = null;
  23032. }
  23033. this._delayedOnLoad = null;
  23034. this._delayedOnError = null;
  23035. };
  23036. // Statics
  23037. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23038. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23039. if (onLoad === void 0) { onLoad = null; }
  23040. if (onError === void 0) { onError = null; }
  23041. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23042. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23043. };
  23044. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23045. if (parsedTexture.customType) {
  23046. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23047. // Update Sampling Mode
  23048. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23049. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23050. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23051. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23052. }
  23053. }
  23054. return parsedCustomTexture;
  23055. }
  23056. if (parsedTexture.isCube) {
  23057. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23058. }
  23059. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23060. return null;
  23061. }
  23062. var texture = BABYLON.SerializationHelper.Parse(function () {
  23063. var generateMipMaps = true;
  23064. if (parsedTexture.noMipmap) {
  23065. generateMipMaps = false;
  23066. }
  23067. if (parsedTexture.mirrorPlane) {
  23068. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23069. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23070. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23071. return mirrorTexture;
  23072. }
  23073. else if (parsedTexture.isRenderTarget) {
  23074. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23075. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23076. return renderTargetTexture;
  23077. }
  23078. else {
  23079. var texture;
  23080. if (parsedTexture.base64String) {
  23081. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23082. }
  23083. else {
  23084. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23085. }
  23086. return texture;
  23087. }
  23088. }, parsedTexture, scene);
  23089. // Update Sampling Mode
  23090. if (parsedTexture.samplingMode) {
  23091. var sampling = parsedTexture.samplingMode;
  23092. if (texture._samplingMode !== sampling) {
  23093. texture.updateSamplingMode(sampling);
  23094. }
  23095. }
  23096. // Animations
  23097. if (parsedTexture.animations) {
  23098. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23099. var parsedAnimation = parsedTexture.animations[animationIndex];
  23100. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23101. }
  23102. }
  23103. return texture;
  23104. };
  23105. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23106. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23107. if (noMipmap === void 0) { noMipmap = false; }
  23108. if (invertY === void 0) { invertY = true; }
  23109. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23110. if (onLoad === void 0) { onLoad = null; }
  23111. if (onError === void 0) { onError = null; }
  23112. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23113. if (name.substr(0, 5) !== "data:") {
  23114. name = "data:" + name;
  23115. }
  23116. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23117. };
  23118. // Constants
  23119. Texture.NEAREST_SAMPLINGMODE = 1;
  23120. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23121. Texture.BILINEAR_SAMPLINGMODE = 2;
  23122. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23123. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23124. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23125. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23126. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23127. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23128. Texture.NEAREST_LINEAR = 7;
  23129. Texture.NEAREST_NEAREST = 8;
  23130. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23131. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23132. Texture.LINEAR_LINEAR = 11;
  23133. Texture.LINEAR_NEAREST = 12;
  23134. Texture.EXPLICIT_MODE = 0;
  23135. Texture.SPHERICAL_MODE = 1;
  23136. Texture.PLANAR_MODE = 2;
  23137. Texture.CUBIC_MODE = 3;
  23138. Texture.PROJECTION_MODE = 4;
  23139. Texture.SKYBOX_MODE = 5;
  23140. Texture.INVCUBIC_MODE = 6;
  23141. Texture.EQUIRECTANGULAR_MODE = 7;
  23142. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23143. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23144. Texture.CLAMP_ADDRESSMODE = 0;
  23145. Texture.WRAP_ADDRESSMODE = 1;
  23146. Texture.MIRROR_ADDRESSMODE = 2;
  23147. __decorate([
  23148. BABYLON.serialize()
  23149. ], Texture.prototype, "url", void 0);
  23150. __decorate([
  23151. BABYLON.serialize()
  23152. ], Texture.prototype, "uOffset", void 0);
  23153. __decorate([
  23154. BABYLON.serialize()
  23155. ], Texture.prototype, "vOffset", void 0);
  23156. __decorate([
  23157. BABYLON.serialize()
  23158. ], Texture.prototype, "uScale", void 0);
  23159. __decorate([
  23160. BABYLON.serialize()
  23161. ], Texture.prototype, "vScale", void 0);
  23162. __decorate([
  23163. BABYLON.serialize()
  23164. ], Texture.prototype, "uAng", void 0);
  23165. __decorate([
  23166. BABYLON.serialize()
  23167. ], Texture.prototype, "vAng", void 0);
  23168. __decorate([
  23169. BABYLON.serialize()
  23170. ], Texture.prototype, "wAng", void 0);
  23171. __decorate([
  23172. BABYLON.serialize()
  23173. ], Texture.prototype, "isBlocking", null);
  23174. return Texture;
  23175. }(BABYLON.BaseTexture));
  23176. BABYLON.Texture = Texture;
  23177. })(BABYLON || (BABYLON = {}));
  23178. //# sourceMappingURL=babylon.texture.js.map
  23179. var BABYLON;
  23180. (function (BABYLON) {
  23181. var _InstancesBatch = /** @class */ (function () {
  23182. function _InstancesBatch() {
  23183. this.mustReturn = false;
  23184. this.visibleInstances = new Array();
  23185. this.renderSelf = new Array();
  23186. }
  23187. return _InstancesBatch;
  23188. }());
  23189. BABYLON._InstancesBatch = _InstancesBatch;
  23190. var Mesh = /** @class */ (function (_super) {
  23191. __extends(Mesh, _super);
  23192. /**
  23193. * @constructor
  23194. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23195. * @param {Scene} scene The scene to add this mesh to.
  23196. * @param {Node} parent The parent of this mesh, if it has one
  23197. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23198. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23199. * When false, achieved by calling a clone(), also passing False.
  23200. * This will make creation of children, recursive.
  23201. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23202. */
  23203. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23204. if (scene === void 0) { scene = null; }
  23205. if (parent === void 0) { parent = null; }
  23206. if (source === void 0) { source = null; }
  23207. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23208. var _this = _super.call(this, name, scene) || this;
  23209. // Events
  23210. /**
  23211. * An event triggered before rendering the mesh
  23212. * @type {BABYLON.Observable}
  23213. */
  23214. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23215. /**
  23216. * An event triggered after rendering the mesh
  23217. * @type {BABYLON.Observable}
  23218. */
  23219. _this.onAfterRenderObservable = new BABYLON.Observable();
  23220. /**
  23221. * An event triggered before drawing the mesh
  23222. * @type {BABYLON.Observable}
  23223. */
  23224. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23225. // Members
  23226. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23227. _this.instances = new Array();
  23228. _this._LODLevels = new Array();
  23229. _this._visibleInstances = {};
  23230. _this._renderIdForInstances = new Array();
  23231. _this._batchCache = new _InstancesBatch();
  23232. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23233. // Use by builder only to know what orientation were the mesh build in.
  23234. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23235. _this.overrideMaterialSideOrientation = null;
  23236. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23237. // Will be used to save a source mesh reference, If any
  23238. _this._source = null;
  23239. scene = _this.getScene();
  23240. if (source) {
  23241. // Source mesh
  23242. _this._source = source;
  23243. // Geometry
  23244. if (source._geometry) {
  23245. source._geometry.applyToMesh(_this);
  23246. }
  23247. // Deep copy
  23248. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23249. // Tags
  23250. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23251. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23252. }
  23253. _this.metadata = source.metadata;
  23254. // Parent
  23255. _this.parent = source.parent;
  23256. // Pivot
  23257. _this.setPivotMatrix(source.getPivotMatrix());
  23258. _this.id = name + "." + source.id;
  23259. // Material
  23260. _this.material = source.material;
  23261. var index;
  23262. if (!doNotCloneChildren) {
  23263. // Children
  23264. var directDescendants = source.getDescendants(true);
  23265. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23266. var child = directDescendants[index_1];
  23267. if (child.clone) {
  23268. child.clone(name + "." + child.name, _this);
  23269. }
  23270. }
  23271. }
  23272. // Physics clone
  23273. var physicsEngine = _this.getScene().getPhysicsEngine();
  23274. if (clonePhysicsImpostor && physicsEngine) {
  23275. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23276. if (impostor) {
  23277. _this.physicsImpostor = impostor.clone(_this);
  23278. }
  23279. }
  23280. // Particles
  23281. for (index = 0; index < scene.particleSystems.length; index++) {
  23282. var system = scene.particleSystems[index];
  23283. if (system.emitter === source) {
  23284. system.clone(system.name, _this);
  23285. }
  23286. }
  23287. _this.computeWorldMatrix(true);
  23288. }
  23289. // Parent
  23290. if (parent !== null) {
  23291. _this.parent = parent;
  23292. }
  23293. return _this;
  23294. }
  23295. Object.defineProperty(Mesh, "FRONTSIDE", {
  23296. /**
  23297. * Mesh side orientation : usually the external or front surface
  23298. */
  23299. get: function () {
  23300. return Mesh._FRONTSIDE;
  23301. },
  23302. enumerable: true,
  23303. configurable: true
  23304. });
  23305. Object.defineProperty(Mesh, "BACKSIDE", {
  23306. /**
  23307. * Mesh side orientation : usually the internal or back surface
  23308. */
  23309. get: function () {
  23310. return Mesh._BACKSIDE;
  23311. },
  23312. enumerable: true,
  23313. configurable: true
  23314. });
  23315. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23316. /**
  23317. * Mesh side orientation : both internal and external or front and back surfaces
  23318. */
  23319. get: function () {
  23320. return Mesh._DOUBLESIDE;
  23321. },
  23322. enumerable: true,
  23323. configurable: true
  23324. });
  23325. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23326. /**
  23327. * Mesh side orientation : by default, `FRONTSIDE`
  23328. */
  23329. get: function () {
  23330. return Mesh._DEFAULTSIDE;
  23331. },
  23332. enumerable: true,
  23333. configurable: true
  23334. });
  23335. Object.defineProperty(Mesh, "NO_CAP", {
  23336. /**
  23337. * Mesh cap setting : no cap
  23338. */
  23339. get: function () {
  23340. return Mesh._NO_CAP;
  23341. },
  23342. enumerable: true,
  23343. configurable: true
  23344. });
  23345. Object.defineProperty(Mesh, "CAP_START", {
  23346. /**
  23347. * Mesh cap setting : one cap at the beginning of the mesh
  23348. */
  23349. get: function () {
  23350. return Mesh._CAP_START;
  23351. },
  23352. enumerable: true,
  23353. configurable: true
  23354. });
  23355. Object.defineProperty(Mesh, "CAP_END", {
  23356. /**
  23357. * Mesh cap setting : one cap at the end of the mesh
  23358. */
  23359. get: function () {
  23360. return Mesh._CAP_END;
  23361. },
  23362. enumerable: true,
  23363. configurable: true
  23364. });
  23365. Object.defineProperty(Mesh, "CAP_ALL", {
  23366. /**
  23367. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23368. */
  23369. get: function () {
  23370. return Mesh._CAP_ALL;
  23371. },
  23372. enumerable: true,
  23373. configurable: true
  23374. });
  23375. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23376. set: function (callback) {
  23377. if (this._onBeforeDrawObserver) {
  23378. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23379. }
  23380. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23381. },
  23382. enumerable: true,
  23383. configurable: true
  23384. });
  23385. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23386. get: function () {
  23387. return this._morphTargetManager;
  23388. },
  23389. set: function (value) {
  23390. if (this._morphTargetManager === value) {
  23391. return;
  23392. }
  23393. this._morphTargetManager = value;
  23394. this._syncGeometryWithMorphTargetManager();
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. Object.defineProperty(Mesh.prototype, "source", {
  23400. get: function () {
  23401. return this._source;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23407. get: function () {
  23408. return this._unIndexed;
  23409. },
  23410. set: function (value) {
  23411. if (this._unIndexed !== value) {
  23412. this._unIndexed = value;
  23413. this._markSubMeshesAsAttributesDirty();
  23414. }
  23415. },
  23416. enumerable: true,
  23417. configurable: true
  23418. });
  23419. // Methods
  23420. /**
  23421. * Returns the string "Mesh".
  23422. */
  23423. Mesh.prototype.getClassName = function () {
  23424. return "Mesh";
  23425. };
  23426. /**
  23427. * Returns a string.
  23428. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23429. */
  23430. Mesh.prototype.toString = function (fullDetails) {
  23431. var ret = _super.prototype.toString.call(this, fullDetails);
  23432. ret += ", n vertices: " + this.getTotalVertices();
  23433. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23434. if (this.animations) {
  23435. for (var i = 0; i < this.animations.length; i++) {
  23436. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23437. }
  23438. }
  23439. if (fullDetails) {
  23440. if (this._geometry) {
  23441. var ib = this.getIndices();
  23442. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23443. if (vb && ib) {
  23444. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23445. }
  23446. }
  23447. else {
  23448. ret += ", flat shading: UNKNOWN";
  23449. }
  23450. }
  23451. return ret;
  23452. };
  23453. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23454. /**
  23455. * True if the mesh has some Levels Of Details (LOD).
  23456. * Returns a boolean.
  23457. */
  23458. get: function () {
  23459. return this._LODLevels.length > 0;
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Mesh.prototype._sortLODLevels = function () {
  23465. this._LODLevels.sort(function (a, b) {
  23466. if (a.distance < b.distance) {
  23467. return 1;
  23468. }
  23469. if (a.distance > b.distance) {
  23470. return -1;
  23471. }
  23472. return 0;
  23473. });
  23474. };
  23475. /**
  23476. * Add a mesh as LOD level triggered at the given distance.
  23477. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23478. * @param {number} distance The distance from the center of the object to show this level
  23479. * @param {Mesh} mesh The mesh to be added as LOD level
  23480. * @return {Mesh} This mesh (for chaining)
  23481. */
  23482. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23483. if (mesh && mesh._masterMesh) {
  23484. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23485. return this;
  23486. }
  23487. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23488. this._LODLevels.push(level);
  23489. if (mesh) {
  23490. mesh._masterMesh = this;
  23491. }
  23492. this._sortLODLevels();
  23493. return this;
  23494. };
  23495. /**
  23496. * Returns the LOD level mesh at the passed distance or null if not found.
  23497. * It is related to the method `addLODLevel(distance, mesh)`.
  23498. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23499. * Returns an object Mesh or `null`.
  23500. */
  23501. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23502. for (var index = 0; index < this._LODLevels.length; index++) {
  23503. var level = this._LODLevels[index];
  23504. if (level.distance === distance) {
  23505. return level.mesh;
  23506. }
  23507. }
  23508. return null;
  23509. };
  23510. /**
  23511. * Remove a mesh from the LOD array
  23512. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23513. * @param {Mesh} mesh The mesh to be removed.
  23514. * @return {Mesh} This mesh (for chaining)
  23515. */
  23516. Mesh.prototype.removeLODLevel = function (mesh) {
  23517. for (var index = 0; index < this._LODLevels.length; index++) {
  23518. if (this._LODLevels[index].mesh === mesh) {
  23519. this._LODLevels.splice(index, 1);
  23520. if (mesh) {
  23521. mesh._masterMesh = null;
  23522. }
  23523. }
  23524. }
  23525. this._sortLODLevels();
  23526. return this;
  23527. };
  23528. /**
  23529. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23530. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23531. */
  23532. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23533. if (!this._LODLevels || this._LODLevels.length === 0) {
  23534. return this;
  23535. }
  23536. var bSphere;
  23537. if (boundingSphere) {
  23538. bSphere = boundingSphere;
  23539. }
  23540. else {
  23541. var boundingInfo = this.getBoundingInfo();
  23542. bSphere = boundingInfo.boundingSphere;
  23543. }
  23544. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23545. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23546. if (this.onLODLevelSelection) {
  23547. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23548. }
  23549. return this;
  23550. }
  23551. for (var index = 0; index < this._LODLevels.length; index++) {
  23552. var level = this._LODLevels[index];
  23553. if (level.distance < distanceToCamera) {
  23554. if (level.mesh) {
  23555. level.mesh._preActivate();
  23556. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23557. }
  23558. if (this.onLODLevelSelection) {
  23559. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23560. }
  23561. return level.mesh;
  23562. }
  23563. }
  23564. if (this.onLODLevelSelection) {
  23565. this.onLODLevelSelection(distanceToCamera, this, this);
  23566. }
  23567. return this;
  23568. };
  23569. Object.defineProperty(Mesh.prototype, "geometry", {
  23570. /**
  23571. * Returns the mesh internal Geometry object.
  23572. */
  23573. get: function () {
  23574. return this._geometry;
  23575. },
  23576. enumerable: true,
  23577. configurable: true
  23578. });
  23579. /**
  23580. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23581. */
  23582. Mesh.prototype.getTotalVertices = function () {
  23583. if (!this._geometry) {
  23584. return 0;
  23585. }
  23586. return this._geometry.getTotalVertices();
  23587. };
  23588. /**
  23589. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23590. * 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.
  23591. * You can force the copy with forceCopy === true
  23592. * Returns null if the mesh has no geometry or no vertex buffer.
  23593. * Possible `kind` values :
  23594. * - BABYLON.VertexBuffer.PositionKind
  23595. * - BABYLON.VertexBuffer.UVKind
  23596. * - BABYLON.VertexBuffer.UV2Kind
  23597. * - BABYLON.VertexBuffer.UV3Kind
  23598. * - BABYLON.VertexBuffer.UV4Kind
  23599. * - BABYLON.VertexBuffer.UV5Kind
  23600. * - BABYLON.VertexBuffer.UV6Kind
  23601. * - BABYLON.VertexBuffer.ColorKind
  23602. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23603. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23604. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23605. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23606. */
  23607. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23608. if (!this._geometry) {
  23609. return null;
  23610. }
  23611. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23612. };
  23613. /**
  23614. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23615. * Returns `null` if the mesh has no geometry.
  23616. * Possible `kind` values :
  23617. * - BABYLON.VertexBuffer.PositionKind
  23618. * - BABYLON.VertexBuffer.UVKind
  23619. * - BABYLON.VertexBuffer.UV2Kind
  23620. * - BABYLON.VertexBuffer.UV3Kind
  23621. * - BABYLON.VertexBuffer.UV4Kind
  23622. * - BABYLON.VertexBuffer.UV5Kind
  23623. * - BABYLON.VertexBuffer.UV6Kind
  23624. * - BABYLON.VertexBuffer.ColorKind
  23625. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23626. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23627. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23628. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23629. */
  23630. Mesh.prototype.getVertexBuffer = function (kind) {
  23631. if (!this._geometry) {
  23632. return null;
  23633. }
  23634. return this._geometry.getVertexBuffer(kind);
  23635. };
  23636. /**
  23637. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23638. * Possible `kind` values :
  23639. * - BABYLON.VertexBuffer.PositionKind
  23640. * - BABYLON.VertexBuffer.UVKind
  23641. * - BABYLON.VertexBuffer.UV2Kind
  23642. * - BABYLON.VertexBuffer.UV3Kind
  23643. * - BABYLON.VertexBuffer.UV4Kind
  23644. * - BABYLON.VertexBuffer.UV5Kind
  23645. * - BABYLON.VertexBuffer.UV6Kind
  23646. * - BABYLON.VertexBuffer.ColorKind
  23647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23651. */
  23652. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23653. if (!this._geometry) {
  23654. if (this._delayInfo) {
  23655. return this._delayInfo.indexOf(kind) !== -1;
  23656. }
  23657. return false;
  23658. }
  23659. return this._geometry.isVerticesDataPresent(kind);
  23660. };
  23661. /**
  23662. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23663. * Possible `kind` values :
  23664. * - BABYLON.VertexBuffer.PositionKind
  23665. * - BABYLON.VertexBuffer.UVKind
  23666. * - BABYLON.VertexBuffer.UV2Kind
  23667. * - BABYLON.VertexBuffer.UV3Kind
  23668. * - BABYLON.VertexBuffer.UV4Kind
  23669. * - BABYLON.VertexBuffer.UV5Kind
  23670. * - BABYLON.VertexBuffer.UV6Kind
  23671. * - BABYLON.VertexBuffer.ColorKind
  23672. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23673. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23674. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23675. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23676. */
  23677. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23678. if (!this._geometry) {
  23679. if (this._delayInfo) {
  23680. return this._delayInfo.indexOf(kind) !== -1;
  23681. }
  23682. return false;
  23683. }
  23684. return this._geometry.isVertexBufferUpdatable(kind);
  23685. };
  23686. /**
  23687. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23688. * Possible `kind` values :
  23689. * - BABYLON.VertexBuffer.PositionKind
  23690. * - BABYLON.VertexBuffer.UVKind
  23691. * - BABYLON.VertexBuffer.UV2Kind
  23692. * - BABYLON.VertexBuffer.UV3Kind
  23693. * - BABYLON.VertexBuffer.UV4Kind
  23694. * - BABYLON.VertexBuffer.UV5Kind
  23695. * - BABYLON.VertexBuffer.UV6Kind
  23696. * - BABYLON.VertexBuffer.ColorKind
  23697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23701. */
  23702. Mesh.prototype.getVerticesDataKinds = function () {
  23703. if (!this._geometry) {
  23704. var result = new Array();
  23705. if (this._delayInfo) {
  23706. this._delayInfo.forEach(function (kind, index, array) {
  23707. result.push(kind);
  23708. });
  23709. }
  23710. return result;
  23711. }
  23712. return this._geometry.getVerticesDataKinds();
  23713. };
  23714. /**
  23715. * Returns a positive integer : the total number of indices in this mesh geometry.
  23716. * Returns zero if the mesh has no geometry.
  23717. */
  23718. Mesh.prototype.getTotalIndices = function () {
  23719. if (!this._geometry) {
  23720. return 0;
  23721. }
  23722. return this._geometry.getTotalIndices();
  23723. };
  23724. /**
  23725. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23726. * 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.
  23727. * Returns an empty array if the mesh has no geometry.
  23728. */
  23729. Mesh.prototype.getIndices = function (copyWhenShared) {
  23730. if (!this._geometry) {
  23731. return [];
  23732. }
  23733. return this._geometry.getIndices(copyWhenShared);
  23734. };
  23735. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23736. get: function () {
  23737. return this._masterMesh !== null && this._masterMesh !== undefined;
  23738. },
  23739. enumerable: true,
  23740. configurable: true
  23741. });
  23742. /**
  23743. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23744. */
  23745. Mesh.prototype.isReady = function () {
  23746. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23747. return false;
  23748. }
  23749. return _super.prototype.isReady.call(this);
  23750. };
  23751. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23752. /**
  23753. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23754. * This property is pertinent only for updatable parametric shapes.
  23755. */
  23756. get: function () {
  23757. return this._areNormalsFrozen;
  23758. },
  23759. enumerable: true,
  23760. configurable: true
  23761. });
  23762. /**
  23763. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23764. * It has no effect at all on other shapes.
  23765. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23766. * Returns the Mesh.
  23767. */
  23768. Mesh.prototype.freezeNormals = function () {
  23769. this._areNormalsFrozen = true;
  23770. return this;
  23771. };
  23772. /**
  23773. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23774. * It has no effect at all on other shapes.
  23775. * It reactivates the mesh normals computation if it was previously frozen.
  23776. * Returns the Mesh.
  23777. */
  23778. Mesh.prototype.unfreezeNormals = function () {
  23779. this._areNormalsFrozen = false;
  23780. return this;
  23781. };
  23782. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23783. /**
  23784. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23785. */
  23786. set: function (count) {
  23787. this._overridenInstanceCount = count;
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. // Methods
  23793. Mesh.prototype._preActivate = function () {
  23794. var sceneRenderId = this.getScene().getRenderId();
  23795. if (this._preActivateId === sceneRenderId) {
  23796. return this;
  23797. }
  23798. this._preActivateId = sceneRenderId;
  23799. this._visibleInstances = null;
  23800. return this;
  23801. };
  23802. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23803. if (this._visibleInstances) {
  23804. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23805. }
  23806. return this;
  23807. };
  23808. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23809. if (!this._visibleInstances) {
  23810. this._visibleInstances = {};
  23811. this._visibleInstances.defaultRenderId = renderId;
  23812. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23813. }
  23814. if (!this._visibleInstances[renderId]) {
  23815. this._visibleInstances[renderId] = new Array();
  23816. }
  23817. this._visibleInstances[renderId].push(instance);
  23818. return this;
  23819. };
  23820. /**
  23821. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23822. * This means the mesh underlying bounding box and sphere are recomputed.
  23823. * Returns the Mesh.
  23824. */
  23825. Mesh.prototype.refreshBoundingInfo = function () {
  23826. return this._refreshBoundingInfo(false);
  23827. };
  23828. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23829. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23830. return this;
  23831. }
  23832. var data = this._getPositionData(applySkeleton);
  23833. if (data) {
  23834. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23835. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23836. }
  23837. if (this.subMeshes) {
  23838. for (var index = 0; index < this.subMeshes.length; index++) {
  23839. this.subMeshes[index].refreshBoundingInfo();
  23840. }
  23841. }
  23842. this._updateBoundingInfo();
  23843. return this;
  23844. };
  23845. Mesh.prototype._getPositionData = function (applySkeleton) {
  23846. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23847. if (data && applySkeleton && this.skeleton) {
  23848. data = data.slice();
  23849. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23850. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23851. if (matricesWeightsData && matricesIndicesData) {
  23852. var needExtras = this.numBoneInfluencers > 4;
  23853. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23854. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23855. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23856. var tempVector = BABYLON.Tmp.Vector3[0];
  23857. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23858. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23859. var matWeightIdx = 0;
  23860. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23861. finalMatrix.reset();
  23862. var inf;
  23863. var weight;
  23864. for (inf = 0; inf < 4; inf++) {
  23865. weight = matricesWeightsData[matWeightIdx + inf];
  23866. if (weight <= 0)
  23867. break;
  23868. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23869. finalMatrix.addToSelf(tempMatrix);
  23870. }
  23871. if (needExtras) {
  23872. for (inf = 0; inf < 4; inf++) {
  23873. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23874. if (weight <= 0)
  23875. break;
  23876. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23877. finalMatrix.addToSelf(tempMatrix);
  23878. }
  23879. }
  23880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23881. tempVector.toArray(data, index);
  23882. }
  23883. }
  23884. }
  23885. return data;
  23886. };
  23887. Mesh.prototype._createGlobalSubMesh = function (force) {
  23888. var totalVertices = this.getTotalVertices();
  23889. if (!totalVertices || !this.getIndices()) {
  23890. return null;
  23891. }
  23892. // Check if we need to recreate the submeshes
  23893. if (this.subMeshes && this.subMeshes.length > 0) {
  23894. var ib = this.getIndices();
  23895. if (!ib) {
  23896. return null;
  23897. }
  23898. var totalIndices = ib.length;
  23899. var needToRecreate = false;
  23900. if (force) {
  23901. needToRecreate = true;
  23902. }
  23903. else {
  23904. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23905. var submesh = _a[_i];
  23906. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23907. needToRecreate = true;
  23908. break;
  23909. }
  23910. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23911. needToRecreate = true;
  23912. break;
  23913. }
  23914. }
  23915. }
  23916. if (!needToRecreate) {
  23917. return this.subMeshes[0];
  23918. }
  23919. }
  23920. this.releaseSubMeshes();
  23921. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23922. };
  23923. Mesh.prototype.subdivide = function (count) {
  23924. if (count < 1) {
  23925. return;
  23926. }
  23927. var totalIndices = this.getTotalIndices();
  23928. var subdivisionSize = (totalIndices / count) | 0;
  23929. var offset = 0;
  23930. // Ensure that subdivisionSize is a multiple of 3
  23931. while (subdivisionSize % 3 !== 0) {
  23932. subdivisionSize++;
  23933. }
  23934. this.releaseSubMeshes();
  23935. for (var index = 0; index < count; index++) {
  23936. if (offset >= totalIndices) {
  23937. break;
  23938. }
  23939. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23940. offset += subdivisionSize;
  23941. }
  23942. this.synchronizeInstances();
  23943. };
  23944. /**
  23945. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23946. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23947. * The `data` are either a numeric array either a Float32Array.
  23948. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23949. * 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).
  23950. * Note that a new underlying VertexBuffer object is created each call.
  23951. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23952. *
  23953. * Possible `kind` values :
  23954. * - BABYLON.VertexBuffer.PositionKind
  23955. * - BABYLON.VertexBuffer.UVKind
  23956. * - BABYLON.VertexBuffer.UV2Kind
  23957. * - BABYLON.VertexBuffer.UV3Kind
  23958. * - BABYLON.VertexBuffer.UV4Kind
  23959. * - BABYLON.VertexBuffer.UV5Kind
  23960. * - BABYLON.VertexBuffer.UV6Kind
  23961. * - BABYLON.VertexBuffer.ColorKind
  23962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23966. *
  23967. * Returns the Mesh.
  23968. */
  23969. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23970. if (updatable === void 0) { updatable = false; }
  23971. if (!this._geometry) {
  23972. var vertexData = new BABYLON.VertexData();
  23973. vertexData.set(data, kind);
  23974. var scene = this.getScene();
  23975. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23976. }
  23977. else {
  23978. this._geometry.setVerticesData(kind, data, updatable, stride);
  23979. }
  23980. return this;
  23981. };
  23982. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23983. if (updatable === void 0) { updatable = true; }
  23984. var vb = this.getVertexBuffer(kind);
  23985. if (!vb || vb.isUpdatable() === updatable) {
  23986. return;
  23987. }
  23988. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23989. };
  23990. /**
  23991. * Sets the mesh VertexBuffer.
  23992. * Returns the Mesh.
  23993. */
  23994. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23995. if (!this._geometry) {
  23996. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23997. }
  23998. this._geometry.setVerticesBuffer(buffer);
  23999. return this;
  24000. };
  24001. /**
  24002. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24003. * If the mesh has no geometry, it is simply returned as it is.
  24004. * The `data` are either a numeric array either a Float32Array.
  24005. * No new underlying VertexBuffer object is created.
  24006. * 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.
  24007. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24008. *
  24009. * Possible `kind` values :
  24010. * - BABYLON.VertexBuffer.PositionKind
  24011. * - BABYLON.VertexBuffer.UVKind
  24012. * - BABYLON.VertexBuffer.UV2Kind
  24013. * - BABYLON.VertexBuffer.UV3Kind
  24014. * - BABYLON.VertexBuffer.UV4Kind
  24015. * - BABYLON.VertexBuffer.UV5Kind
  24016. * - BABYLON.VertexBuffer.UV6Kind
  24017. * - BABYLON.VertexBuffer.ColorKind
  24018. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24019. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24020. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24021. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24022. *
  24023. * Returns the Mesh.
  24024. */
  24025. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24026. if (!this._geometry) {
  24027. return this;
  24028. }
  24029. if (!makeItUnique) {
  24030. this._geometry.updateVerticesData(kind, data, updateExtends);
  24031. }
  24032. else {
  24033. this.makeGeometryUnique();
  24034. this.updateVerticesData(kind, data, updateExtends, false);
  24035. }
  24036. return this;
  24037. };
  24038. /**
  24039. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24040. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24041. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24042. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24043. * Returns the Mesh.
  24044. */
  24045. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24046. if (computeNormals === void 0) { computeNormals = true; }
  24047. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24048. if (!positions) {
  24049. return this;
  24050. }
  24051. positionFunction(positions);
  24052. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24053. if (computeNormals) {
  24054. var indices = this.getIndices();
  24055. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24056. if (!normals) {
  24057. return this;
  24058. }
  24059. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24060. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24061. }
  24062. return this;
  24063. };
  24064. /**
  24065. * Creates a un-shared specific occurence of the geometry for the mesh.
  24066. * Returns the Mesh.
  24067. */
  24068. Mesh.prototype.makeGeometryUnique = function () {
  24069. if (!this._geometry) {
  24070. return this;
  24071. }
  24072. var oldGeometry = this._geometry;
  24073. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24074. oldGeometry.releaseForMesh(this, true);
  24075. geometry.applyToMesh(this);
  24076. return this;
  24077. };
  24078. /**
  24079. * Sets the mesh indices.
  24080. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24081. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24082. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24083. * This method creates a new index buffer each call.
  24084. * Returns the Mesh.
  24085. */
  24086. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24087. if (totalVertices === void 0) { totalVertices = null; }
  24088. if (updatable === void 0) { updatable = false; }
  24089. if (!this._geometry) {
  24090. var vertexData = new BABYLON.VertexData();
  24091. vertexData.indices = indices;
  24092. var scene = this.getScene();
  24093. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24094. }
  24095. else {
  24096. this._geometry.setIndices(indices, totalVertices, updatable);
  24097. }
  24098. return this;
  24099. };
  24100. /**
  24101. * Update the current index buffer
  24102. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24103. * Returns the Mesh.
  24104. */
  24105. Mesh.prototype.updateIndices = function (indices, offset) {
  24106. if (!this._geometry) {
  24107. return this;
  24108. }
  24109. this._geometry.updateIndices(indices, offset);
  24110. return this;
  24111. };
  24112. /**
  24113. * Invert the geometry to move from a right handed system to a left handed one.
  24114. * Returns the Mesh.
  24115. */
  24116. Mesh.prototype.toLeftHanded = function () {
  24117. if (!this._geometry) {
  24118. return this;
  24119. }
  24120. this._geometry.toLeftHanded();
  24121. return this;
  24122. };
  24123. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24124. if (!this._geometry) {
  24125. return this;
  24126. }
  24127. var engine = this.getScene().getEngine();
  24128. // Wireframe
  24129. var indexToBind;
  24130. if (this._unIndexed) {
  24131. indexToBind = null;
  24132. }
  24133. else {
  24134. switch (fillMode) {
  24135. case BABYLON.Material.PointFillMode:
  24136. indexToBind = null;
  24137. break;
  24138. case BABYLON.Material.WireFrameFillMode:
  24139. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24140. break;
  24141. default:
  24142. case BABYLON.Material.TriangleFillMode:
  24143. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24144. break;
  24145. }
  24146. }
  24147. // VBOs
  24148. this._geometry._bind(effect, indexToBind);
  24149. return this;
  24150. };
  24151. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24152. if (alternate === void 0) { alternate = false; }
  24153. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24154. return this;
  24155. }
  24156. this.onBeforeDrawObservable.notifyObservers(this);
  24157. var scene = this.getScene();
  24158. var engine = scene.getEngine();
  24159. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24160. // or triangles as points
  24161. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24162. }
  24163. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24164. // Triangles as wireframe
  24165. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24166. }
  24167. else {
  24168. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24169. }
  24170. if (scene._isAlternateRenderingEnabled && !alternate) {
  24171. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24172. if (!effect || !scene.activeCamera) {
  24173. return this;
  24174. }
  24175. scene._switchToAlternateCameraConfiguration(true);
  24176. this._effectiveMaterial.bindView(effect);
  24177. this._effectiveMaterial.bindViewProjection(effect);
  24178. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24179. this._draw(subMesh, fillMode, instancesCount, true);
  24180. engine.setViewport(scene.activeCamera.viewport);
  24181. scene._switchToAlternateCameraConfiguration(false);
  24182. this._effectiveMaterial.bindView(effect);
  24183. this._effectiveMaterial.bindViewProjection(effect);
  24184. }
  24185. return this;
  24186. };
  24187. /**
  24188. * Registers for this mesh a javascript function called just before the rendering process.
  24189. * This function is passed the current mesh.
  24190. * Return the Mesh.
  24191. */
  24192. Mesh.prototype.registerBeforeRender = function (func) {
  24193. this.onBeforeRenderObservable.add(func);
  24194. return this;
  24195. };
  24196. /**
  24197. * Disposes a previously registered javascript function called before the rendering.
  24198. * This function is passed the current mesh.
  24199. * Returns the Mesh.
  24200. */
  24201. Mesh.prototype.unregisterBeforeRender = function (func) {
  24202. this.onBeforeRenderObservable.removeCallback(func);
  24203. return this;
  24204. };
  24205. /**
  24206. * Registers for this mesh a javascript function called just after the rendering is complete.
  24207. * This function is passed the current mesh.
  24208. * Returns the Mesh.
  24209. */
  24210. Mesh.prototype.registerAfterRender = function (func) {
  24211. this.onAfterRenderObservable.add(func);
  24212. return this;
  24213. };
  24214. /**
  24215. * Disposes a previously registered javascript function called after the rendering.
  24216. * This function is passed the current mesh.
  24217. * Return the Mesh.
  24218. */
  24219. Mesh.prototype.unregisterAfterRender = function (func) {
  24220. this.onAfterRenderObservable.removeCallback(func);
  24221. return this;
  24222. };
  24223. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24224. var scene = this.getScene();
  24225. this._batchCache.mustReturn = false;
  24226. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24227. this._batchCache.visibleInstances[subMeshId] = null;
  24228. if (this._visibleInstances) {
  24229. var currentRenderId = scene.getRenderId();
  24230. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24231. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24232. var selfRenderId = this._renderId;
  24233. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24234. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24235. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24236. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24237. }
  24238. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24239. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24240. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24241. this._batchCache.mustReturn = true;
  24242. return this._batchCache;
  24243. }
  24244. if (currentRenderId !== selfRenderId) {
  24245. this._batchCache.renderSelf[subMeshId] = false;
  24246. }
  24247. }
  24248. this._renderIdForInstances[subMeshId] = currentRenderId;
  24249. }
  24250. return this._batchCache;
  24251. };
  24252. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24253. var visibleInstances = batch.visibleInstances[subMesh._id];
  24254. if (!visibleInstances) {
  24255. return this;
  24256. }
  24257. var matricesCount = visibleInstances.length + 1;
  24258. var bufferSize = matricesCount * 16 * 4;
  24259. var currentInstancesBufferSize = this._instancesBufferSize;
  24260. var instancesBuffer = this._instancesBuffer;
  24261. while (this._instancesBufferSize < bufferSize) {
  24262. this._instancesBufferSize *= 2;
  24263. }
  24264. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24265. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24266. }
  24267. var offset = 0;
  24268. var instancesCount = 0;
  24269. var world = this.getWorldMatrix();
  24270. if (batch.renderSelf[subMesh._id]) {
  24271. world.copyToArray(this._instancesData, offset);
  24272. offset += 16;
  24273. instancesCount++;
  24274. }
  24275. if (visibleInstances) {
  24276. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24277. var instance = visibleInstances[instanceIndex];
  24278. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24279. offset += 16;
  24280. instancesCount++;
  24281. }
  24282. }
  24283. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24284. if (instancesBuffer) {
  24285. instancesBuffer.dispose();
  24286. }
  24287. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24288. this._instancesBuffer = instancesBuffer;
  24289. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24290. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24291. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24292. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24293. }
  24294. else {
  24295. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24296. }
  24297. this._bind(subMesh, effect, fillMode);
  24298. this._draw(subMesh, fillMode, instancesCount);
  24299. engine.unbindInstanceAttributes();
  24300. return this;
  24301. };
  24302. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24303. var scene = this.getScene();
  24304. var engine = scene.getEngine();
  24305. if (hardwareInstancedRendering) {
  24306. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24307. }
  24308. else {
  24309. if (batch.renderSelf[subMesh._id]) {
  24310. // Draw
  24311. if (onBeforeDraw) {
  24312. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24313. }
  24314. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24315. }
  24316. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24317. if (visibleInstancesForSubMesh) {
  24318. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24319. var instance = visibleInstancesForSubMesh[instanceIndex];
  24320. // World
  24321. var world = instance.getWorldMatrix();
  24322. if (onBeforeDraw) {
  24323. onBeforeDraw(true, world, effectiveMaterial);
  24324. }
  24325. // Draw
  24326. this._draw(subMesh, fillMode);
  24327. }
  24328. }
  24329. }
  24330. return this;
  24331. };
  24332. /**
  24333. * Triggers the draw call for the mesh.
  24334. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24335. * Returns the Mesh.
  24336. */
  24337. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24338. this.checkOcclusionQuery();
  24339. if (this._isOccluded) {
  24340. return this;
  24341. }
  24342. var scene = this.getScene();
  24343. // Managing instances
  24344. var batch = this._getInstancesRenderList(subMesh._id);
  24345. if (batch.mustReturn) {
  24346. return this;
  24347. }
  24348. // Checking geometry state
  24349. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24350. return this;
  24351. }
  24352. this.onBeforeRenderObservable.notifyObservers(this);
  24353. var engine = scene.getEngine();
  24354. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24355. // Material
  24356. var material = subMesh.getMaterial();
  24357. if (!material) {
  24358. return this;
  24359. }
  24360. this._effectiveMaterial = material;
  24361. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24362. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24363. return this;
  24364. }
  24365. }
  24366. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24367. return this;
  24368. }
  24369. // Alpha mode
  24370. if (enableAlphaMode) {
  24371. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24372. }
  24373. // Outline - step 1
  24374. var savedDepthWrite = engine.getDepthWrite();
  24375. if (this.renderOutline) {
  24376. engine.setDepthWrite(false);
  24377. scene.getOutlineRenderer().render(subMesh, batch);
  24378. engine.setDepthWrite(savedDepthWrite);
  24379. }
  24380. var effect;
  24381. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24382. effect = subMesh.effect;
  24383. }
  24384. else {
  24385. effect = this._effectiveMaterial.getEffect();
  24386. }
  24387. if (!effect) {
  24388. return this;
  24389. }
  24390. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24391. if (this._effectiveMaterial.forceDepthWrite) {
  24392. engine.setDepthWrite(true);
  24393. }
  24394. // Bind
  24395. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24396. if (!hardwareInstancedRendering) {
  24397. this._bind(subMesh, effect, fillMode);
  24398. }
  24399. var world = this.getWorldMatrix();
  24400. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24401. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24402. }
  24403. else {
  24404. this._effectiveMaterial.bind(world, this);
  24405. }
  24406. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24407. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24408. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24409. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24410. }
  24411. // Draw
  24412. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24413. // Unbind
  24414. this._effectiveMaterial.unbind();
  24415. // Outline - step 2
  24416. if (this.renderOutline && savedDepthWrite) {
  24417. engine.setDepthWrite(true);
  24418. engine.setColorWrite(false);
  24419. scene.getOutlineRenderer().render(subMesh, batch);
  24420. engine.setColorWrite(true);
  24421. }
  24422. // Overlay
  24423. if (this.renderOverlay) {
  24424. var currentMode = engine.getAlphaMode();
  24425. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24426. scene.getOutlineRenderer().render(subMesh, batch, true);
  24427. engine.setAlphaMode(currentMode);
  24428. }
  24429. this.onAfterRenderObservable.notifyObservers(this);
  24430. return this;
  24431. };
  24432. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24433. if (isInstance && effectiveMaterial) {
  24434. effectiveMaterial.bindOnlyWorldMatrix(world);
  24435. }
  24436. };
  24437. /**
  24438. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24439. */
  24440. Mesh.prototype.getEmittedParticleSystems = function () {
  24441. var results = new Array();
  24442. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24443. var particleSystem = this.getScene().particleSystems[index];
  24444. if (particleSystem.emitter === this) {
  24445. results.push(particleSystem);
  24446. }
  24447. }
  24448. return results;
  24449. };
  24450. /**
  24451. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24452. */
  24453. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24454. var results = new Array();
  24455. var descendants = this.getDescendants();
  24456. descendants.push(this);
  24457. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24458. var particleSystem = this.getScene().particleSystems[index];
  24459. var emitter = particleSystem.emitter;
  24460. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24461. results.push(particleSystem);
  24462. }
  24463. }
  24464. return results;
  24465. };
  24466. Mesh.prototype._checkDelayState = function () {
  24467. var scene = this.getScene();
  24468. if (this._geometry) {
  24469. this._geometry.load(scene);
  24470. }
  24471. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24472. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24473. this._queueLoad(scene);
  24474. }
  24475. return this;
  24476. };
  24477. Mesh.prototype._queueLoad = function (scene) {
  24478. var _this = this;
  24479. scene._addPendingData(this);
  24480. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24481. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24482. if (data instanceof ArrayBuffer) {
  24483. _this._delayLoadingFunction(data, _this);
  24484. }
  24485. else {
  24486. _this._delayLoadingFunction(JSON.parse(data), _this);
  24487. }
  24488. _this.instances.forEach(function (instance) {
  24489. instance._syncSubMeshes();
  24490. });
  24491. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24492. scene._removePendingData(_this);
  24493. }, function () { }, scene.database, getBinaryData);
  24494. return this;
  24495. };
  24496. /**
  24497. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24498. */
  24499. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24500. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24501. return false;
  24502. }
  24503. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24504. return false;
  24505. }
  24506. this._checkDelayState();
  24507. return true;
  24508. };
  24509. /**
  24510. * Sets the mesh material by the material or multiMaterial `id` property.
  24511. * The material `id` is a string identifying the material or the multiMaterial.
  24512. * This method returns the Mesh.
  24513. */
  24514. Mesh.prototype.setMaterialByID = function (id) {
  24515. var materials = this.getScene().materials;
  24516. var index;
  24517. for (index = materials.length - 1; index > -1; index--) {
  24518. if (materials[index].id === id) {
  24519. this.material = materials[index];
  24520. return this;
  24521. }
  24522. }
  24523. // Multi
  24524. var multiMaterials = this.getScene().multiMaterials;
  24525. for (index = multiMaterials.length - 1; index > -1; index--) {
  24526. if (multiMaterials[index].id === id) {
  24527. this.material = multiMaterials[index];
  24528. return this;
  24529. }
  24530. }
  24531. return this;
  24532. };
  24533. /**
  24534. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24535. */
  24536. Mesh.prototype.getAnimatables = function () {
  24537. var results = new Array();
  24538. if (this.material) {
  24539. results.push(this.material);
  24540. }
  24541. if (this.skeleton) {
  24542. results.push(this.skeleton);
  24543. }
  24544. return results;
  24545. };
  24546. /**
  24547. * Modifies the mesh geometry according to the passed transformation matrix.
  24548. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24549. * The mesh normals are modified accordingly the same transformation.
  24550. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24551. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24552. * Returns the Mesh.
  24553. */
  24554. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24555. // Position
  24556. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24557. return this;
  24558. }
  24559. var submeshes = this.subMeshes.splice(0);
  24560. this._resetPointsArrayCache();
  24561. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24562. var temp = new Array();
  24563. var index;
  24564. for (index = 0; index < data.length; index += 3) {
  24565. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24566. }
  24567. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24568. // Normals
  24569. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24570. return this;
  24571. }
  24572. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24573. temp = [];
  24574. for (index = 0; index < data.length; index += 3) {
  24575. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24576. }
  24577. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24578. // flip faces?
  24579. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24580. this.flipFaces();
  24581. }
  24582. // Restore submeshes
  24583. this.releaseSubMeshes();
  24584. this.subMeshes = submeshes;
  24585. return this;
  24586. };
  24587. /**
  24588. * Modifies the mesh geometry according to its own current World Matrix.
  24589. * The mesh World Matrix is then reset.
  24590. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24591. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24592. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24593. * Returns the Mesh.
  24594. */
  24595. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24596. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24597. this.scaling.copyFromFloats(1, 1, 1);
  24598. this.position.copyFromFloats(0, 0, 0);
  24599. this.rotation.copyFromFloats(0, 0, 0);
  24600. //only if quaternion is already set
  24601. if (this.rotationQuaternion) {
  24602. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24603. }
  24604. this._worldMatrix = BABYLON.Matrix.Identity();
  24605. return this;
  24606. };
  24607. Object.defineProperty(Mesh.prototype, "_positions", {
  24608. // Cache
  24609. get: function () {
  24610. if (this._geometry) {
  24611. return this._geometry._positions;
  24612. }
  24613. return null;
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Mesh.prototype._resetPointsArrayCache = function () {
  24619. if (this._geometry) {
  24620. this._geometry._resetPointsArrayCache();
  24621. }
  24622. return this;
  24623. };
  24624. Mesh.prototype._generatePointsArray = function () {
  24625. if (this._geometry) {
  24626. return this._geometry._generatePointsArray();
  24627. }
  24628. return false;
  24629. };
  24630. /**
  24631. * Returns a new Mesh object generated from the current mesh properties.
  24632. * This method must not get confused with createInstance().
  24633. * The parameter `name` is a string, the name given to the new mesh.
  24634. * The optional parameter `newParent` can be any Node object (default `null`).
  24635. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24636. * 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.
  24637. */
  24638. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24639. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24640. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24641. };
  24642. /**
  24643. * Disposes the Mesh.
  24644. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24645. * Returns nothing.
  24646. */
  24647. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24648. var _this = this;
  24649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24650. this.morphTargetManager = null;
  24651. if (this._geometry) {
  24652. this._geometry.releaseForMesh(this, true);
  24653. }
  24654. // Sources
  24655. var meshes = this.getScene().meshes;
  24656. meshes.forEach(function (abstractMesh) {
  24657. var mesh = abstractMesh;
  24658. if (mesh._source && mesh._source === _this) {
  24659. mesh._source = null;
  24660. }
  24661. });
  24662. this._source = null;
  24663. // Instances
  24664. if (this._instancesBuffer) {
  24665. this._instancesBuffer.dispose();
  24666. this._instancesBuffer = null;
  24667. }
  24668. while (this.instances.length) {
  24669. this.instances[0].dispose();
  24670. }
  24671. // Highlight layers.
  24672. var highlightLayers = this.getScene().highlightLayers;
  24673. for (var i = 0; i < highlightLayers.length; i++) {
  24674. var highlightLayer = highlightLayers[i];
  24675. if (highlightLayer) {
  24676. highlightLayer.removeMesh(this);
  24677. highlightLayer.removeExcludedMesh(this);
  24678. }
  24679. }
  24680. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24681. };
  24682. /**
  24683. * Modifies the mesh geometry according to a displacement map.
  24684. * 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.
  24685. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24686. * This method returns nothing.
  24687. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24688. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24689. * 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.
  24690. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24691. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24692. *
  24693. * Returns the Mesh.
  24694. */
  24695. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24696. var _this = this;
  24697. var scene = this.getScene();
  24698. var onload = function (img) {
  24699. // Getting height map data
  24700. var canvas = document.createElement("canvas");
  24701. var context = canvas.getContext("2d");
  24702. var heightMapWidth = img.width;
  24703. var heightMapHeight = img.height;
  24704. canvas.width = heightMapWidth;
  24705. canvas.height = heightMapHeight;
  24706. context.drawImage(img, 0, 0);
  24707. // Create VertexData from map data
  24708. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24709. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24710. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24711. //execute success callback, if set
  24712. if (onSuccess) {
  24713. onSuccess(_this);
  24714. }
  24715. };
  24716. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24717. return this;
  24718. };
  24719. /**
  24720. * Modifies the mesh geometry according to a displacementMap buffer.
  24721. * 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.
  24722. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24723. * This method returns nothing.
  24724. * 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.
  24725. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24726. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24727. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24728. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24729. *
  24730. * Returns the Mesh.
  24731. */
  24732. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24733. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24734. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24735. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24736. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24737. return this;
  24738. }
  24739. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24740. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24741. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24742. var position = BABYLON.Vector3.Zero();
  24743. var normal = BABYLON.Vector3.Zero();
  24744. var uv = BABYLON.Vector2.Zero();
  24745. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24746. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24747. for (var index = 0; index < positions.length; index += 3) {
  24748. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24749. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24750. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24751. // Compute height
  24752. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24753. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24754. var pos = (u + v * heightMapWidth) * 4;
  24755. var r = buffer[pos] / 255.0;
  24756. var g = buffer[pos + 1] / 255.0;
  24757. var b = buffer[pos + 2] / 255.0;
  24758. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24759. normal.normalize();
  24760. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24761. position = position.add(normal);
  24762. position.toArray(positions, index);
  24763. }
  24764. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24765. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24766. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24767. return this;
  24768. };
  24769. /**
  24770. * Modify the mesh to get a flat shading rendering.
  24771. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24772. * This method returns the Mesh.
  24773. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24774. */
  24775. Mesh.prototype.convertToFlatShadedMesh = function () {
  24776. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24777. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24778. var kinds = this.getVerticesDataKinds();
  24779. var vbs = {};
  24780. var data = {};
  24781. var newdata = {};
  24782. var updatableNormals = false;
  24783. var kindIndex;
  24784. var kind;
  24785. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24786. kind = kinds[kindIndex];
  24787. var vertexBuffer = this.getVertexBuffer(kind);
  24788. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24789. updatableNormals = vertexBuffer.isUpdatable();
  24790. kinds.splice(kindIndex, 1);
  24791. kindIndex--;
  24792. continue;
  24793. }
  24794. vbs[kind] = vertexBuffer;
  24795. data[kind] = vbs[kind].getData();
  24796. newdata[kind] = [];
  24797. }
  24798. // Save previous submeshes
  24799. var previousSubmeshes = this.subMeshes.slice(0);
  24800. var indices = this.getIndices();
  24801. var totalIndices = this.getTotalIndices();
  24802. // Generating unique vertices per face
  24803. var index;
  24804. for (index = 0; index < totalIndices; index++) {
  24805. var vertexIndex = indices[index];
  24806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24807. kind = kinds[kindIndex];
  24808. var stride = vbs[kind].getStrideSize();
  24809. for (var offset = 0; offset < stride; offset++) {
  24810. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24811. }
  24812. }
  24813. }
  24814. // Updating faces & normal
  24815. var normals = [];
  24816. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24817. for (index = 0; index < totalIndices; index += 3) {
  24818. indices[index] = index;
  24819. indices[index + 1] = index + 1;
  24820. indices[index + 2] = index + 2;
  24821. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24822. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24823. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24824. var p1p2 = p1.subtract(p2);
  24825. var p3p2 = p3.subtract(p2);
  24826. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24827. // Store same normals for every vertex
  24828. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24829. normals.push(normal.x);
  24830. normals.push(normal.y);
  24831. normals.push(normal.z);
  24832. }
  24833. }
  24834. this.setIndices(indices);
  24835. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24836. // Updating vertex buffers
  24837. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24838. kind = kinds[kindIndex];
  24839. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24840. }
  24841. // Updating submeshes
  24842. this.releaseSubMeshes();
  24843. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24844. var previousOne = previousSubmeshes[submeshIndex];
  24845. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24846. }
  24847. this.synchronizeInstances();
  24848. return this;
  24849. };
  24850. /**
  24851. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24852. * In other words, more vertices, no more indices and a single bigger VBO.
  24853. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24854. * Returns the Mesh.
  24855. */
  24856. Mesh.prototype.convertToUnIndexedMesh = function () {
  24857. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24858. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24859. var kinds = this.getVerticesDataKinds();
  24860. var vbs = {};
  24861. var data = {};
  24862. var newdata = {};
  24863. var kindIndex;
  24864. var kind;
  24865. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24866. kind = kinds[kindIndex];
  24867. var vertexBuffer = this.getVertexBuffer(kind);
  24868. vbs[kind] = vertexBuffer;
  24869. data[kind] = vbs[kind].getData();
  24870. newdata[kind] = [];
  24871. }
  24872. // Save previous submeshes
  24873. var previousSubmeshes = this.subMeshes.slice(0);
  24874. var indices = this.getIndices();
  24875. var totalIndices = this.getTotalIndices();
  24876. // Generating unique vertices per face
  24877. var index;
  24878. for (index = 0; index < totalIndices; index++) {
  24879. var vertexIndex = indices[index];
  24880. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24881. kind = kinds[kindIndex];
  24882. var stride = vbs[kind].getStrideSize();
  24883. for (var offset = 0; offset < stride; offset++) {
  24884. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24885. }
  24886. }
  24887. }
  24888. // Updating indices
  24889. for (index = 0; index < totalIndices; index += 3) {
  24890. indices[index] = index;
  24891. indices[index + 1] = index + 1;
  24892. indices[index + 2] = index + 2;
  24893. }
  24894. this.setIndices(indices);
  24895. // Updating vertex buffers
  24896. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24897. kind = kinds[kindIndex];
  24898. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24899. }
  24900. // Updating submeshes
  24901. this.releaseSubMeshes();
  24902. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24903. var previousOne = previousSubmeshes[submeshIndex];
  24904. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24905. }
  24906. this._unIndexed = true;
  24907. this.synchronizeInstances();
  24908. return this;
  24909. };
  24910. /**
  24911. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24912. * This method returns the Mesh.
  24913. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24914. */
  24915. Mesh.prototype.flipFaces = function (flipNormals) {
  24916. if (flipNormals === void 0) { flipNormals = false; }
  24917. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24918. var i;
  24919. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24920. for (i = 0; i < vertex_data.normals.length; i++) {
  24921. vertex_data.normals[i] *= -1;
  24922. }
  24923. }
  24924. if (vertex_data.indices) {
  24925. var temp;
  24926. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24927. // reassign indices
  24928. temp = vertex_data.indices[i + 1];
  24929. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24930. vertex_data.indices[i + 2] = temp;
  24931. }
  24932. }
  24933. vertex_data.applyToMesh(this);
  24934. return this;
  24935. };
  24936. // Instances
  24937. /**
  24938. * Creates a new InstancedMesh object from the mesh model.
  24939. * An instance shares the same properties and the same material than its model.
  24940. * Only these properties of each instance can then be set individually :
  24941. * - position
  24942. * - rotation
  24943. * - rotationQuaternion
  24944. * - setPivotMatrix
  24945. * - scaling
  24946. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24947. * Warning : this method is not supported for Line mesh and LineSystem
  24948. */
  24949. Mesh.prototype.createInstance = function (name) {
  24950. return new BABYLON.InstancedMesh(name, this);
  24951. };
  24952. /**
  24953. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24954. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24955. * This method returns the Mesh.
  24956. */
  24957. Mesh.prototype.synchronizeInstances = function () {
  24958. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24959. var instance = this.instances[instanceIndex];
  24960. instance._syncSubMeshes();
  24961. }
  24962. return this;
  24963. };
  24964. /**
  24965. * Simplify the mesh according to the given array of settings.
  24966. * Function will return immediately and will simplify async. It returns the Mesh.
  24967. * @param settings a collection of simplification settings.
  24968. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24969. * @param type the type of simplification to run.
  24970. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24971. */
  24972. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24973. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24974. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24975. this.getScene().simplificationQueue.addTask({
  24976. settings: settings,
  24977. parallelProcessing: parallelProcessing,
  24978. mesh: this,
  24979. simplificationType: simplificationType,
  24980. successCallback: successCallback
  24981. });
  24982. return this;
  24983. };
  24984. /**
  24985. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24986. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24987. * This should be used together with the simplification to avoid disappearing triangles.
  24988. * Returns the Mesh.
  24989. * @param successCallback an optional success callback to be called after the optimization finished.
  24990. */
  24991. Mesh.prototype.optimizeIndices = function (successCallback) {
  24992. var _this = this;
  24993. var indices = this.getIndices();
  24994. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24995. if (!positions || !indices) {
  24996. return this;
  24997. }
  24998. var vectorPositions = new Array();
  24999. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25000. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25001. }
  25002. var dupes = new Array();
  25003. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25004. var realPos = vectorPositions.length - 1 - iteration;
  25005. var testedPosition = vectorPositions[realPos];
  25006. for (var j = 0; j < realPos; ++j) {
  25007. var againstPosition = vectorPositions[j];
  25008. if (testedPosition.equals(againstPosition)) {
  25009. dupes[realPos] = j;
  25010. break;
  25011. }
  25012. }
  25013. }, function () {
  25014. for (var i = 0; i < indices.length; ++i) {
  25015. indices[i] = dupes[indices[i]] || indices[i];
  25016. }
  25017. //indices are now reordered
  25018. var originalSubMeshes = _this.subMeshes.slice(0);
  25019. _this.setIndices(indices);
  25020. _this.subMeshes = originalSubMeshes;
  25021. if (successCallback) {
  25022. successCallback(_this);
  25023. }
  25024. });
  25025. return this;
  25026. };
  25027. Mesh.prototype.serialize = function (serializationObject) {
  25028. serializationObject.name = this.name;
  25029. serializationObject.id = this.id;
  25030. serializationObject.type = this.getClassName();
  25031. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25032. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25033. }
  25034. serializationObject.position = this.position.asArray();
  25035. if (this.rotationQuaternion) {
  25036. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25037. }
  25038. else if (this.rotation) {
  25039. serializationObject.rotation = this.rotation.asArray();
  25040. }
  25041. serializationObject.scaling = this.scaling.asArray();
  25042. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25043. serializationObject.isEnabled = this.isEnabled();
  25044. serializationObject.isVisible = this.isVisible;
  25045. serializationObject.infiniteDistance = this.infiniteDistance;
  25046. serializationObject.pickable = this.isPickable;
  25047. serializationObject.receiveShadows = this.receiveShadows;
  25048. serializationObject.billboardMode = this.billboardMode;
  25049. serializationObject.visibility = this.visibility;
  25050. serializationObject.checkCollisions = this.checkCollisions;
  25051. serializationObject.isBlocker = this.isBlocker;
  25052. // Parent
  25053. if (this.parent) {
  25054. serializationObject.parentId = this.parent.id;
  25055. }
  25056. // Geometry
  25057. serializationObject.isUnIndexed = this.isUnIndexed;
  25058. var geometry = this._geometry;
  25059. if (geometry) {
  25060. var geometryId = geometry.id;
  25061. serializationObject.geometryId = geometryId;
  25062. // SubMeshes
  25063. serializationObject.subMeshes = [];
  25064. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25065. var subMesh = this.subMeshes[subIndex];
  25066. serializationObject.subMeshes.push({
  25067. materialIndex: subMesh.materialIndex,
  25068. verticesStart: subMesh.verticesStart,
  25069. verticesCount: subMesh.verticesCount,
  25070. indexStart: subMesh.indexStart,
  25071. indexCount: subMesh.indexCount
  25072. });
  25073. }
  25074. }
  25075. // Material
  25076. if (this.material) {
  25077. serializationObject.materialId = this.material.id;
  25078. }
  25079. else {
  25080. this.material = null;
  25081. }
  25082. // Morph targets
  25083. if (this.morphTargetManager) {
  25084. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25085. }
  25086. // Skeleton
  25087. if (this.skeleton) {
  25088. serializationObject.skeletonId = this.skeleton.id;
  25089. }
  25090. // Physics
  25091. //TODO implement correct serialization for physics impostors.
  25092. var impostor = this.getPhysicsImpostor();
  25093. if (impostor) {
  25094. serializationObject.physicsMass = impostor.getParam("mass");
  25095. serializationObject.physicsFriction = impostor.getParam("friction");
  25096. serializationObject.physicsRestitution = impostor.getParam("mass");
  25097. serializationObject.physicsImpostor = impostor.type;
  25098. }
  25099. // Metadata
  25100. if (this.metadata) {
  25101. serializationObject.metadata = this.metadata;
  25102. }
  25103. // Instances
  25104. serializationObject.instances = [];
  25105. for (var index = 0; index < this.instances.length; index++) {
  25106. var instance = this.instances[index];
  25107. var serializationInstance = {
  25108. name: instance.name,
  25109. id: instance.id,
  25110. position: instance.position.asArray(),
  25111. scaling: instance.scaling.asArray()
  25112. };
  25113. if (instance.rotationQuaternion) {
  25114. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25115. }
  25116. else if (instance.rotation) {
  25117. serializationInstance.rotation = instance.rotation.asArray();
  25118. }
  25119. serializationObject.instances.push(serializationInstance);
  25120. // Animations
  25121. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25122. serializationInstance.ranges = instance.serializeAnimationRanges();
  25123. }
  25124. //
  25125. // Animations
  25126. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25127. serializationObject.ranges = this.serializeAnimationRanges();
  25128. // Layer mask
  25129. serializationObject.layerMask = this.layerMask;
  25130. // Alpha
  25131. serializationObject.alphaIndex = this.alphaIndex;
  25132. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25133. // Overlay
  25134. serializationObject.overlayAlpha = this.overlayAlpha;
  25135. serializationObject.overlayColor = this.overlayColor.asArray();
  25136. serializationObject.renderOverlay = this.renderOverlay;
  25137. // Fog
  25138. serializationObject.applyFog = this.applyFog;
  25139. // Action Manager
  25140. if (this.actionManager) {
  25141. serializationObject.actions = this.actionManager.serialize(this.name);
  25142. }
  25143. };
  25144. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25145. if (!this.geometry) {
  25146. return;
  25147. }
  25148. this._markSubMeshesAsAttributesDirty();
  25149. var morphTargetManager = this._morphTargetManager;
  25150. if (morphTargetManager && morphTargetManager.vertexCount) {
  25151. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25152. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25153. this.morphTargetManager = null;
  25154. return;
  25155. }
  25156. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25157. var morphTarget = morphTargetManager.getActiveTarget(index);
  25158. var positions = morphTarget.getPositions();
  25159. if (!positions) {
  25160. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25161. return;
  25162. }
  25163. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25164. var normals = morphTarget.getNormals();
  25165. if (normals) {
  25166. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25167. }
  25168. var tangents = morphTarget.getTangents();
  25169. if (tangents) {
  25170. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25171. }
  25172. }
  25173. }
  25174. else {
  25175. var index = 0;
  25176. // Positions
  25177. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25178. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25179. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25180. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25181. }
  25182. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25183. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25184. }
  25185. index++;
  25186. }
  25187. }
  25188. };
  25189. // Statics
  25190. /**
  25191. * Returns a new Mesh object parsed from the source provided.
  25192. * The parameter `parsedMesh` is the source.
  25193. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25194. */
  25195. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25196. var mesh;
  25197. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25198. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25199. }
  25200. else {
  25201. mesh = new Mesh(parsedMesh.name, scene);
  25202. }
  25203. mesh.id = parsedMesh.id;
  25204. if (BABYLON.Tags) {
  25205. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25206. }
  25207. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25208. if (parsedMesh.metadata !== undefined) {
  25209. mesh.metadata = parsedMesh.metadata;
  25210. }
  25211. if (parsedMesh.rotationQuaternion) {
  25212. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25213. }
  25214. else if (parsedMesh.rotation) {
  25215. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25216. }
  25217. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25218. if (parsedMesh.localMatrix) {
  25219. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25220. }
  25221. else if (parsedMesh.pivotMatrix) {
  25222. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25223. }
  25224. mesh.setEnabled(parsedMesh.isEnabled);
  25225. mesh.isVisible = parsedMesh.isVisible;
  25226. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25227. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25228. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25229. if (parsedMesh.applyFog !== undefined) {
  25230. mesh.applyFog = parsedMesh.applyFog;
  25231. }
  25232. if (parsedMesh.pickable !== undefined) {
  25233. mesh.isPickable = parsedMesh.pickable;
  25234. }
  25235. if (parsedMesh.alphaIndex !== undefined) {
  25236. mesh.alphaIndex = parsedMesh.alphaIndex;
  25237. }
  25238. mesh.receiveShadows = parsedMesh.receiveShadows;
  25239. mesh.billboardMode = parsedMesh.billboardMode;
  25240. if (parsedMesh.visibility !== undefined) {
  25241. mesh.visibility = parsedMesh.visibility;
  25242. }
  25243. mesh.checkCollisions = parsedMesh.checkCollisions;
  25244. if (parsedMesh.isBlocker !== undefined) {
  25245. mesh.isBlocker = parsedMesh.isBlocker;
  25246. }
  25247. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25248. // freezeWorldMatrix
  25249. if (parsedMesh.freezeWorldMatrix) {
  25250. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25251. }
  25252. // Parent
  25253. if (parsedMesh.parentId) {
  25254. mesh._waitingParentId = parsedMesh.parentId;
  25255. }
  25256. // Actions
  25257. if (parsedMesh.actions !== undefined) {
  25258. mesh._waitingActions = parsedMesh.actions;
  25259. }
  25260. // Overlay
  25261. if (parsedMesh.overlayAlpha !== undefined) {
  25262. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25263. }
  25264. if (parsedMesh.overlayColor !== undefined) {
  25265. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25266. }
  25267. if (parsedMesh.renderOverlay !== undefined) {
  25268. mesh.renderOverlay = parsedMesh.renderOverlay;
  25269. }
  25270. // Geometry
  25271. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25272. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25273. if (parsedMesh.delayLoadingFile) {
  25274. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25275. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25276. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25277. if (parsedMesh._binaryInfo) {
  25278. mesh._binaryInfo = parsedMesh._binaryInfo;
  25279. }
  25280. mesh._delayInfo = [];
  25281. if (parsedMesh.hasUVs) {
  25282. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25283. }
  25284. if (parsedMesh.hasUVs2) {
  25285. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25286. }
  25287. if (parsedMesh.hasUVs3) {
  25288. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25289. }
  25290. if (parsedMesh.hasUVs4) {
  25291. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25292. }
  25293. if (parsedMesh.hasUVs5) {
  25294. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25295. }
  25296. if (parsedMesh.hasUVs6) {
  25297. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25298. }
  25299. if (parsedMesh.hasColors) {
  25300. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25301. }
  25302. if (parsedMesh.hasMatricesIndices) {
  25303. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25304. }
  25305. if (parsedMesh.hasMatricesWeights) {
  25306. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25307. }
  25308. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25309. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25310. mesh._checkDelayState();
  25311. }
  25312. }
  25313. else {
  25314. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25315. }
  25316. // Material
  25317. if (parsedMesh.materialId) {
  25318. mesh.setMaterialByID(parsedMesh.materialId);
  25319. }
  25320. else {
  25321. mesh.material = null;
  25322. }
  25323. // Morph targets
  25324. if (parsedMesh.morphTargetManagerId > -1) {
  25325. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25326. }
  25327. // Skeleton
  25328. if (parsedMesh.skeletonId > -1) {
  25329. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25330. if (parsedMesh.numBoneInfluencers) {
  25331. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25332. }
  25333. }
  25334. // Animations
  25335. if (parsedMesh.animations) {
  25336. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25337. var parsedAnimation = parsedMesh.animations[animationIndex];
  25338. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25339. }
  25340. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25341. }
  25342. if (parsedMesh.autoAnimate) {
  25343. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25344. }
  25345. // Layer Mask
  25346. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25347. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25348. }
  25349. else {
  25350. mesh.layerMask = 0x0FFFFFFF;
  25351. }
  25352. // Physics
  25353. if (parsedMesh.physicsImpostor) {
  25354. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25355. mass: parsedMesh.physicsMass,
  25356. friction: parsedMesh.physicsFriction,
  25357. restitution: parsedMesh.physicsRestitution
  25358. }, scene);
  25359. }
  25360. // Instances
  25361. if (parsedMesh.instances) {
  25362. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25363. var parsedInstance = parsedMesh.instances[index];
  25364. var instance = mesh.createInstance(parsedInstance.name);
  25365. if (parsedInstance.id) {
  25366. instance.id = parsedInstance.id;
  25367. }
  25368. if (BABYLON.Tags) {
  25369. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25370. }
  25371. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25372. if (parsedInstance.parentId) {
  25373. instance._waitingParentId = parsedInstance.parentId;
  25374. }
  25375. if (parsedInstance.rotationQuaternion) {
  25376. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25377. }
  25378. else if (parsedInstance.rotation) {
  25379. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25380. }
  25381. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25382. instance.checkCollisions = mesh.checkCollisions;
  25383. if (parsedMesh.animations) {
  25384. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25385. parsedAnimation = parsedMesh.animations[animationIndex];
  25386. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25387. }
  25388. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25389. }
  25390. }
  25391. }
  25392. return mesh;
  25393. };
  25394. /**
  25395. * Creates a ribbon mesh.
  25396. * Please consider using the same method from the MeshBuilder class instead.
  25397. * 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.
  25398. *
  25399. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25400. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25401. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25402. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25403. * 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.
  25404. * 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.
  25405. * 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
  25406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25409. */
  25410. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25411. if (closeArray === void 0) { closeArray = false; }
  25412. if (updatable === void 0) { updatable = false; }
  25413. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25414. pathArray: pathArray,
  25415. closeArray: closeArray,
  25416. closePath: closePath,
  25417. offset: offset,
  25418. updatable: updatable,
  25419. sideOrientation: sideOrientation,
  25420. instance: instance
  25421. }, scene);
  25422. };
  25423. /**
  25424. * Creates a plane polygonal mesh. By default, this is a disc.
  25425. * Please consider using the same method from the MeshBuilder class instead.
  25426. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25427. * 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.
  25428. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25429. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25431. */
  25432. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25433. if (scene === void 0) { scene = null; }
  25434. var options = {
  25435. radius: radius,
  25436. tessellation: tessellation,
  25437. sideOrientation: sideOrientation,
  25438. updatable: updatable
  25439. };
  25440. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25441. };
  25442. /**
  25443. * Creates a box mesh.
  25444. * Please consider using the same method from the MeshBuilder class instead.
  25445. * The parameter `size` sets the size (float) of each box side (default 1).
  25446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25449. */
  25450. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25451. if (scene === void 0) { scene = null; }
  25452. var options = {
  25453. size: size,
  25454. sideOrientation: sideOrientation,
  25455. updatable: updatable
  25456. };
  25457. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25458. };
  25459. /**
  25460. * Creates a sphere mesh.
  25461. * Please consider using the same method from the MeshBuilder class instead.
  25462. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25463. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25467. */
  25468. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25469. var options = {
  25470. segments: segments,
  25471. diameterX: diameter,
  25472. diameterY: diameter,
  25473. diameterZ: diameter,
  25474. sideOrientation: sideOrientation,
  25475. updatable: updatable
  25476. };
  25477. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25478. };
  25479. /**
  25480. * Creates a cylinder or a cone mesh.
  25481. * Please consider using the same method from the MeshBuilder class instead.
  25482. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25483. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25484. * 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.
  25485. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25486. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25490. */
  25491. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25492. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25493. if (scene !== undefined) {
  25494. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25495. updatable = scene;
  25496. }
  25497. scene = subdivisions;
  25498. subdivisions = 1;
  25499. }
  25500. var options = {
  25501. height: height,
  25502. diameterTop: diameterTop,
  25503. diameterBottom: diameterBottom,
  25504. tessellation: tessellation,
  25505. subdivisions: subdivisions,
  25506. sideOrientation: sideOrientation,
  25507. updatable: updatable
  25508. };
  25509. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25510. };
  25511. // Torus (Code from SharpDX.org)
  25512. /**
  25513. * Creates a torus mesh.
  25514. * Please consider using the same method from the MeshBuilder class instead.
  25515. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25516. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25517. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25518. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25519. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25521. */
  25522. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25523. var options = {
  25524. diameter: diameter,
  25525. thickness: thickness,
  25526. tessellation: tessellation,
  25527. sideOrientation: sideOrientation,
  25528. updatable: updatable
  25529. };
  25530. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25531. };
  25532. /**
  25533. * Creates a torus knot mesh.
  25534. * Please consider using the same method from the MeshBuilder class instead.
  25535. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25536. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25537. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25538. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25540. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25542. */
  25543. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25544. var options = {
  25545. radius: radius,
  25546. tube: tube,
  25547. radialSegments: radialSegments,
  25548. tubularSegments: tubularSegments,
  25549. p: p,
  25550. q: q,
  25551. sideOrientation: sideOrientation,
  25552. updatable: updatable
  25553. };
  25554. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25555. };
  25556. /**
  25557. * Creates a line mesh.
  25558. * Please consider using the same method from the MeshBuilder class instead.
  25559. * 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.
  25560. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25561. * The parameter `points` is an array successive Vector3.
  25562. * 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
  25563. * When updating an instance, remember that only point positions can change, not the number of points.
  25564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25565. */
  25566. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25567. if (scene === void 0) { scene = null; }
  25568. if (updatable === void 0) { updatable = false; }
  25569. if (instance === void 0) { instance = null; }
  25570. var options = {
  25571. points: points,
  25572. updatable: updatable,
  25573. instance: instance
  25574. };
  25575. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25576. };
  25577. /**
  25578. * Creates a dashed line mesh.
  25579. * Please consider using the same method from the MeshBuilder class instead.
  25580. * 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.
  25581. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25582. * The parameter `points` is an array successive Vector3.
  25583. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25584. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25585. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25586. * 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
  25587. * When updating an instance, remember that only point positions can change, not the number of points.
  25588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25589. */
  25590. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25591. if (scene === void 0) { scene = null; }
  25592. var options = {
  25593. points: points,
  25594. dashSize: dashSize,
  25595. gapSize: gapSize,
  25596. dashNb: dashNb,
  25597. updatable: updatable,
  25598. instance: instance
  25599. };
  25600. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25601. };
  25602. /**
  25603. * Creates a polygon mesh.
  25604. * Please consider using the same method from the MeshBuilder class instead.
  25605. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25606. * 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.
  25607. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25609. * Remember you can only change the shape positions, not their number when updating a polygon.
  25610. */
  25611. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25612. var options = {
  25613. shape: shape,
  25614. holes: holes,
  25615. updatable: updatable,
  25616. sideOrientation: sideOrientation
  25617. };
  25618. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25619. };
  25620. /**
  25621. * Creates an extruded polygon mesh, with depth in the Y direction.
  25622. * Please consider using the same method from the MeshBuilder class instead.
  25623. */
  25624. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25625. var options = {
  25626. shape: shape,
  25627. holes: holes,
  25628. depth: depth,
  25629. updatable: updatable,
  25630. sideOrientation: sideOrientation
  25631. };
  25632. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25633. };
  25634. /**
  25635. * Creates an extruded shape mesh.
  25636. * 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.
  25637. * Please consider using the same method from the MeshBuilder class instead.
  25638. *
  25639. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25640. * 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
  25641. * extruded along the Z axis.
  25642. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25643. * 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.
  25644. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25645. * 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
  25646. * 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
  25647. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25651. */
  25652. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25653. if (scene === void 0) { scene = null; }
  25654. var options = {
  25655. shape: shape,
  25656. path: path,
  25657. scale: scale,
  25658. rotation: rotation,
  25659. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25660. sideOrientation: sideOrientation,
  25661. instance: instance,
  25662. updatable: updatable
  25663. };
  25664. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25665. };
  25666. /**
  25667. * Creates an custom extruded shape mesh.
  25668. * 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.
  25669. * Please consider using the same method from the MeshBuilder class instead.
  25670. *
  25671. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25672. * 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
  25673. * extruded along the Z axis.
  25674. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25675. * 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
  25676. * and the distance of this point from the begining of the path :
  25677. * ```javascript
  25678. * var rotationFunction = function(i, distance) {
  25679. * // do things
  25680. * return rotationValue; }
  25681. * ```
  25682. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25683. * 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
  25684. * and the distance of this point from the begining of the path :
  25685. * ```javascript
  25686. * var scaleFunction = function(i, distance) {
  25687. * // do things
  25688. * return scaleValue;}
  25689. * ```
  25690. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25691. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25692. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25693. * 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
  25694. * 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
  25695. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25697. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25699. */
  25700. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25701. var options = {
  25702. shape: shape,
  25703. path: path,
  25704. scaleFunction: scaleFunction,
  25705. rotationFunction: rotationFunction,
  25706. ribbonCloseArray: ribbonCloseArray,
  25707. ribbonClosePath: ribbonClosePath,
  25708. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25709. sideOrientation: sideOrientation,
  25710. instance: instance,
  25711. updatable: updatable
  25712. };
  25713. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25714. };
  25715. /**
  25716. * Creates lathe mesh.
  25717. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25718. * Please consider using the same method from the MeshBuilder class instead.
  25719. * 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
  25720. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25721. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25722. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25726. */
  25727. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25728. var options = {
  25729. shape: shape,
  25730. radius: radius,
  25731. tessellation: tessellation,
  25732. sideOrientation: sideOrientation,
  25733. updatable: updatable
  25734. };
  25735. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25736. };
  25737. /**
  25738. * Creates a plane mesh.
  25739. * Please consider using the same method from the MeshBuilder class instead.
  25740. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25744. */
  25745. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25746. var options = {
  25747. size: size,
  25748. width: size,
  25749. height: size,
  25750. sideOrientation: sideOrientation,
  25751. updatable: updatable
  25752. };
  25753. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25754. };
  25755. /**
  25756. * Creates a ground mesh.
  25757. * Please consider using the same method from the MeshBuilder class instead.
  25758. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25759. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25761. */
  25762. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25763. var options = {
  25764. width: width,
  25765. height: height,
  25766. subdivisions: subdivisions,
  25767. updatable: updatable
  25768. };
  25769. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25770. };
  25771. /**
  25772. * Creates a tiled ground mesh.
  25773. * Please consider using the same method from the MeshBuilder class instead.
  25774. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25775. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25776. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25777. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25778. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25779. * numbers of subdivisions on the ground width and height of each tile.
  25780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25781. */
  25782. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25783. var options = {
  25784. xmin: xmin,
  25785. zmin: zmin,
  25786. xmax: xmax,
  25787. zmax: zmax,
  25788. subdivisions: subdivisions,
  25789. precision: precision,
  25790. updatable: updatable
  25791. };
  25792. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25793. };
  25794. /**
  25795. * Creates a ground mesh from a height map.
  25796. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25797. * Please consider using the same method from the MeshBuilder class instead.
  25798. * The parameter `url` sets the URL of the height map image resource.
  25799. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25800. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25801. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25802. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25803. * 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).
  25804. * This function is passed the newly built mesh :
  25805. * ```javascript
  25806. * function(mesh) { // do things
  25807. * return; }
  25808. * ```
  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.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25812. var options = {
  25813. width: width,
  25814. height: height,
  25815. subdivisions: subdivisions,
  25816. minHeight: minHeight,
  25817. maxHeight: maxHeight,
  25818. updatable: updatable,
  25819. onReady: onReady
  25820. };
  25821. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25822. };
  25823. /**
  25824. * Creates a tube mesh.
  25825. * 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.
  25826. * Please consider using the same method from the MeshBuilder class instead.
  25827. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25828. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25829. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25830. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25831. * 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.
  25832. * It must return a radius value (positive float) :
  25833. * ```javascript
  25834. * var radiusFunction = function(i, distance) {
  25835. * // do things
  25836. * return radius; }
  25837. * ```
  25838. * 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
  25839. * 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
  25840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25841. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25843. */
  25844. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25845. var options = {
  25846. path: path,
  25847. radius: radius,
  25848. tessellation: tessellation,
  25849. radiusFunction: radiusFunction,
  25850. arc: 1,
  25851. cap: cap,
  25852. updatable: updatable,
  25853. sideOrientation: sideOrientation,
  25854. instance: instance
  25855. };
  25856. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25857. };
  25858. /**
  25859. * Creates a polyhedron mesh.
  25860. * Please consider using the same method from the MeshBuilder class instead.
  25861. * 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
  25862. * to choose the wanted type.
  25863. * The parameter `size` (positive float, default 1) sets the polygon size.
  25864. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25865. * 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`.
  25866. * 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
  25867. * 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)`).
  25868. * 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
  25869. * 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.
  25870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25873. */
  25874. Mesh.CreatePolyhedron = function (name, options, scene) {
  25875. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25876. };
  25877. /**
  25878. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25879. * Please consider using the same method from the MeshBuilder class instead.
  25880. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25881. * 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`).
  25882. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25883. * 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.
  25884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25887. */
  25888. Mesh.CreateIcoSphere = function (name, options, scene) {
  25889. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25890. };
  25891. /**
  25892. * Creates a decal mesh.
  25893. * Please consider using the same method from the MeshBuilder class instead.
  25894. * 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.
  25895. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25896. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25897. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25898. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25899. */
  25900. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25901. var options = {
  25902. position: position,
  25903. normal: normal,
  25904. size: size,
  25905. angle: angle
  25906. };
  25907. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25908. };
  25909. // Skeletons
  25910. /**
  25911. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25912. */
  25913. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25914. if (!this._sourcePositions) {
  25915. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25916. if (!source) {
  25917. return this._sourcePositions;
  25918. }
  25919. this._sourcePositions = new Float32Array(source);
  25920. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25921. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25922. }
  25923. }
  25924. return this._sourcePositions;
  25925. };
  25926. /**
  25927. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25928. */
  25929. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25930. if (!this._sourceNormals) {
  25931. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25932. if (!source) {
  25933. return this._sourceNormals;
  25934. }
  25935. this._sourceNormals = new Float32Array(source);
  25936. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25937. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25938. }
  25939. }
  25940. return this._sourceNormals;
  25941. };
  25942. /**
  25943. * Updates the vertex buffer by applying transformation from the bones.
  25944. * Returns the Mesh.
  25945. *
  25946. * @param {skeleton} skeleton to apply
  25947. */
  25948. Mesh.prototype.applySkeleton = function (skeleton) {
  25949. if (!this.geometry) {
  25950. return this;
  25951. }
  25952. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25953. return this;
  25954. }
  25955. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25956. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25957. return this;
  25958. }
  25959. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25960. return this;
  25961. }
  25962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25963. return this;
  25964. }
  25965. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25966. return this;
  25967. }
  25968. if (!this._sourcePositions) {
  25969. var submeshes = this.subMeshes.slice();
  25970. this.setPositionsForCPUSkinning();
  25971. this.subMeshes = submeshes;
  25972. }
  25973. if (!this._sourceNormals) {
  25974. this.setNormalsForCPUSkinning();
  25975. }
  25976. // positionsData checks for not being Float32Array will only pass at most once
  25977. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25978. if (!positionsData) {
  25979. return this;
  25980. }
  25981. if (!(positionsData instanceof Float32Array)) {
  25982. positionsData = new Float32Array(positionsData);
  25983. }
  25984. // normalsData checks for not being Float32Array will only pass at most once
  25985. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25986. if (!normalsData) {
  25987. return this;
  25988. }
  25989. if (!(normalsData instanceof Float32Array)) {
  25990. normalsData = new Float32Array(normalsData);
  25991. }
  25992. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25993. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25994. if (!matricesWeightsData || !matricesIndicesData) {
  25995. return this;
  25996. }
  25997. var needExtras = this.numBoneInfluencers > 4;
  25998. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25999. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26000. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26001. var tempVector3 = BABYLON.Vector3.Zero();
  26002. var finalMatrix = new BABYLON.Matrix();
  26003. var tempMatrix = new BABYLON.Matrix();
  26004. var matWeightIdx = 0;
  26005. var inf;
  26006. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26007. var weight;
  26008. for (inf = 0; inf < 4; inf++) {
  26009. weight = matricesWeightsData[matWeightIdx + inf];
  26010. if (weight > 0) {
  26011. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26012. finalMatrix.addToSelf(tempMatrix);
  26013. }
  26014. else
  26015. break;
  26016. }
  26017. if (needExtras) {
  26018. for (inf = 0; inf < 4; inf++) {
  26019. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26020. if (weight > 0) {
  26021. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26022. finalMatrix.addToSelf(tempMatrix);
  26023. }
  26024. else
  26025. break;
  26026. }
  26027. }
  26028. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26029. tempVector3.toArray(positionsData, index);
  26030. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26031. tempVector3.toArray(normalsData, index);
  26032. finalMatrix.reset();
  26033. }
  26034. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26035. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26036. return this;
  26037. };
  26038. // Tools
  26039. /**
  26040. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26041. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26042. */
  26043. Mesh.MinMax = function (meshes) {
  26044. var minVector = null;
  26045. var maxVector = null;
  26046. meshes.forEach(function (mesh, index, array) {
  26047. var boundingInfo = mesh.getBoundingInfo();
  26048. var boundingBox = boundingInfo.boundingBox;
  26049. if (!minVector || !maxVector) {
  26050. minVector = boundingBox.minimumWorld;
  26051. maxVector = boundingBox.maximumWorld;
  26052. }
  26053. else {
  26054. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26055. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26056. }
  26057. });
  26058. if (!minVector || !maxVector) {
  26059. return {
  26060. min: BABYLON.Vector3.Zero(),
  26061. max: BABYLON.Vector3.Zero()
  26062. };
  26063. }
  26064. return {
  26065. min: minVector,
  26066. max: maxVector
  26067. };
  26068. };
  26069. /**
  26070. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26071. */
  26072. Mesh.Center = function (meshesOrMinMaxVector) {
  26073. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26074. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26075. };
  26076. /**
  26077. * Merge the array of meshes into a single mesh for performance reasons.
  26078. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26079. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26080. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26081. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26082. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26083. */
  26084. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26085. if (disposeSource === void 0) { disposeSource = true; }
  26086. var index;
  26087. if (!allow32BitsIndices) {
  26088. var totalVertices = 0;
  26089. // Counting vertices
  26090. for (index = 0; index < meshes.length; index++) {
  26091. if (meshes[index]) {
  26092. totalVertices += meshes[index].getTotalVertices();
  26093. if (totalVertices > 65536) {
  26094. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26095. return null;
  26096. }
  26097. }
  26098. }
  26099. }
  26100. // Merge
  26101. var vertexData = null;
  26102. var otherVertexData;
  26103. var indiceArray = new Array();
  26104. var source = null;
  26105. for (index = 0; index < meshes.length; index++) {
  26106. if (meshes[index]) {
  26107. meshes[index].computeWorldMatrix(true);
  26108. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26109. otherVertexData.transform(meshes[index].getWorldMatrix());
  26110. if (vertexData) {
  26111. vertexData.merge(otherVertexData);
  26112. }
  26113. else {
  26114. vertexData = otherVertexData;
  26115. source = meshes[index];
  26116. }
  26117. if (subdivideWithSubMeshes) {
  26118. indiceArray.push(meshes[index].getTotalIndices());
  26119. }
  26120. }
  26121. }
  26122. source = source;
  26123. if (!meshSubclass) {
  26124. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26125. }
  26126. vertexData.applyToMesh(meshSubclass);
  26127. // Setting properties
  26128. meshSubclass.material = source.material;
  26129. meshSubclass.checkCollisions = source.checkCollisions;
  26130. // Cleaning
  26131. if (disposeSource) {
  26132. for (index = 0; index < meshes.length; index++) {
  26133. if (meshes[index]) {
  26134. meshes[index].dispose();
  26135. }
  26136. }
  26137. }
  26138. // Subdivide
  26139. if (subdivideWithSubMeshes) {
  26140. //-- Suppresions du submesh global
  26141. meshSubclass.releaseSubMeshes();
  26142. index = 0;
  26143. var offset = 0;
  26144. //-- aplique la subdivision en fonction du tableau d'indices
  26145. while (index < indiceArray.length) {
  26146. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26147. offset += indiceArray[index];
  26148. index++;
  26149. }
  26150. }
  26151. return meshSubclass;
  26152. };
  26153. // Consts
  26154. Mesh._FRONTSIDE = 0;
  26155. Mesh._BACKSIDE = 1;
  26156. Mesh._DOUBLESIDE = 2;
  26157. Mesh._DEFAULTSIDE = 0;
  26158. Mesh._NO_CAP = 0;
  26159. Mesh._CAP_START = 1;
  26160. Mesh._CAP_END = 2;
  26161. Mesh._CAP_ALL = 3;
  26162. return Mesh;
  26163. }(BABYLON.AbstractMesh));
  26164. BABYLON.Mesh = Mesh;
  26165. })(BABYLON || (BABYLON = {}));
  26166. //# sourceMappingURL=babylon.mesh.js.map
  26167. var BABYLON;
  26168. (function (BABYLON) {
  26169. var BaseSubMesh = /** @class */ (function () {
  26170. function BaseSubMesh() {
  26171. }
  26172. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26173. get: function () {
  26174. return this._materialEffect;
  26175. },
  26176. enumerable: true,
  26177. configurable: true
  26178. });
  26179. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26180. if (defines === void 0) { defines = null; }
  26181. if (this._materialEffect === effect) {
  26182. if (!effect) {
  26183. this._materialDefines = null;
  26184. }
  26185. return;
  26186. }
  26187. this._materialDefines = defines;
  26188. this._materialEffect = effect;
  26189. };
  26190. return BaseSubMesh;
  26191. }());
  26192. BABYLON.BaseSubMesh = BaseSubMesh;
  26193. var SubMesh = /** @class */ (function (_super) {
  26194. __extends(SubMesh, _super);
  26195. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26196. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26197. var _this = _super.call(this) || this;
  26198. _this.materialIndex = materialIndex;
  26199. _this.verticesStart = verticesStart;
  26200. _this.verticesCount = verticesCount;
  26201. _this.indexStart = indexStart;
  26202. _this.indexCount = indexCount;
  26203. _this._renderId = 0;
  26204. _this._mesh = mesh;
  26205. _this._renderingMesh = renderingMesh || mesh;
  26206. mesh.subMeshes.push(_this);
  26207. _this._trianglePlanes = [];
  26208. _this._id = mesh.subMeshes.length - 1;
  26209. if (createBoundingBox) {
  26210. _this.refreshBoundingInfo();
  26211. mesh.computeWorldMatrix(true);
  26212. }
  26213. return _this;
  26214. }
  26215. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26216. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26217. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26218. };
  26219. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26220. get: function () {
  26221. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. /**
  26227. * Returns the submesh BoudingInfo object.
  26228. */
  26229. SubMesh.prototype.getBoundingInfo = function () {
  26230. if (this.IsGlobal) {
  26231. return this._mesh.getBoundingInfo();
  26232. }
  26233. return this._boundingInfo;
  26234. };
  26235. /**
  26236. * Sets the submesh BoundingInfo.
  26237. * Return the SubMesh.
  26238. */
  26239. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26240. this._boundingInfo = boundingInfo;
  26241. return this;
  26242. };
  26243. /**
  26244. * Returns the mesh of the current submesh.
  26245. */
  26246. SubMesh.prototype.getMesh = function () {
  26247. return this._mesh;
  26248. };
  26249. /**
  26250. * Returns the rendering mesh of the submesh.
  26251. */
  26252. SubMesh.prototype.getRenderingMesh = function () {
  26253. return this._renderingMesh;
  26254. };
  26255. /**
  26256. * Returns the submesh material.
  26257. */
  26258. SubMesh.prototype.getMaterial = function () {
  26259. var rootMaterial = this._renderingMesh.material;
  26260. if (rootMaterial && rootMaterial.getSubMaterial) {
  26261. var multiMaterial = rootMaterial;
  26262. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26263. if (this._currentMaterial !== effectiveMaterial) {
  26264. this._currentMaterial = effectiveMaterial;
  26265. this._materialDefines = null;
  26266. }
  26267. return effectiveMaterial;
  26268. }
  26269. if (!rootMaterial) {
  26270. return this._mesh.getScene().defaultMaterial;
  26271. }
  26272. return rootMaterial;
  26273. };
  26274. // Methods
  26275. /**
  26276. * Sets a new updated BoundingInfo object to the submesh.
  26277. * Returns the SubMesh.
  26278. */
  26279. SubMesh.prototype.refreshBoundingInfo = function () {
  26280. this._lastColliderWorldVertices = null;
  26281. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26282. return this;
  26283. }
  26284. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26285. if (!data) {
  26286. this._boundingInfo = this._mesh.getBoundingInfo();
  26287. return this;
  26288. }
  26289. var indices = this._renderingMesh.getIndices();
  26290. var extend;
  26291. //is this the only submesh?
  26292. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26293. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26294. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26295. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26296. }
  26297. else {
  26298. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26299. }
  26300. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26301. return this;
  26302. };
  26303. SubMesh.prototype._checkCollision = function (collider) {
  26304. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26305. return boundingInfo._checkCollision(collider);
  26306. };
  26307. /**
  26308. * Updates the submesh BoundingInfo.
  26309. * Returns the Submesh.
  26310. */
  26311. SubMesh.prototype.updateBoundingInfo = function (world) {
  26312. var boundingInfo = this.getBoundingInfo();
  26313. if (!boundingInfo) {
  26314. this.refreshBoundingInfo();
  26315. boundingInfo = this.getBoundingInfo();
  26316. }
  26317. boundingInfo.update(world);
  26318. return this;
  26319. };
  26320. /**
  26321. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26322. * Boolean returned.
  26323. */
  26324. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26325. var boundingInfo = this.getBoundingInfo();
  26326. if (!boundingInfo) {
  26327. return false;
  26328. }
  26329. return boundingInfo.isInFrustum(frustumPlanes);
  26330. };
  26331. /**
  26332. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26333. * Boolean returned.
  26334. */
  26335. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26336. var boundingInfo = this.getBoundingInfo();
  26337. if (!boundingInfo) {
  26338. return false;
  26339. }
  26340. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26341. };
  26342. /**
  26343. * Renders the submesh.
  26344. * Returns it.
  26345. */
  26346. SubMesh.prototype.render = function (enableAlphaMode) {
  26347. this._renderingMesh.render(this, enableAlphaMode);
  26348. return this;
  26349. };
  26350. /**
  26351. * Returns a new Index Buffer.
  26352. * Type returned : WebGLBuffer.
  26353. */
  26354. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26355. if (!this._linesIndexBuffer) {
  26356. var linesIndices = [];
  26357. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26358. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26359. }
  26360. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26361. this.linesIndexCount = linesIndices.length;
  26362. }
  26363. return this._linesIndexBuffer;
  26364. };
  26365. /**
  26366. * True is the passed Ray intersects the submesh bounding box.
  26367. * Boolean returned.
  26368. */
  26369. SubMesh.prototype.canIntersects = function (ray) {
  26370. var boundingInfo = this.getBoundingInfo();
  26371. if (!boundingInfo) {
  26372. return false;
  26373. }
  26374. return ray.intersectsBox(boundingInfo.boundingBox);
  26375. };
  26376. /**
  26377. * Returns an object IntersectionInfo.
  26378. */
  26379. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26380. var intersectInfo = null;
  26381. // LineMesh first as it's also a Mesh...
  26382. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26383. var lineMesh = this._mesh;
  26384. // Line test
  26385. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26386. var p0 = positions[indices[index]];
  26387. var p1 = positions[indices[index + 1]];
  26388. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26389. if (length < 0) {
  26390. continue;
  26391. }
  26392. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26393. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26394. if (fastCheck) {
  26395. break;
  26396. }
  26397. }
  26398. }
  26399. }
  26400. else {
  26401. // Triangles test
  26402. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26403. var p0 = positions[indices[index]];
  26404. var p1 = positions[indices[index + 1]];
  26405. var p2 = positions[indices[index + 2]];
  26406. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26407. if (currentIntersectInfo) {
  26408. if (currentIntersectInfo.distance < 0) {
  26409. continue;
  26410. }
  26411. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26412. intersectInfo = currentIntersectInfo;
  26413. intersectInfo.faceId = index / 3;
  26414. if (fastCheck) {
  26415. break;
  26416. }
  26417. }
  26418. }
  26419. }
  26420. }
  26421. return intersectInfo;
  26422. };
  26423. SubMesh.prototype._rebuild = function () {
  26424. if (this._linesIndexBuffer) {
  26425. this._linesIndexBuffer = null;
  26426. }
  26427. };
  26428. // Clone
  26429. /**
  26430. * Creates a new Submesh from the passed Mesh.
  26431. */
  26432. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26433. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26434. if (!this.IsGlobal) {
  26435. var boundingInfo = this.getBoundingInfo();
  26436. if (!boundingInfo) {
  26437. return result;
  26438. }
  26439. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26440. }
  26441. return result;
  26442. };
  26443. // Dispose
  26444. /**
  26445. * Disposes the Submesh.
  26446. * Returns nothing.
  26447. */
  26448. SubMesh.prototype.dispose = function () {
  26449. if (this._linesIndexBuffer) {
  26450. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26451. this._linesIndexBuffer = null;
  26452. }
  26453. // Remove from mesh
  26454. var index = this._mesh.subMeshes.indexOf(this);
  26455. this._mesh.subMeshes.splice(index, 1);
  26456. };
  26457. // Statics
  26458. /**
  26459. * Creates a new Submesh from the passed parameters :
  26460. * - materialIndex (integer) : the index of the main mesh material.
  26461. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26462. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26463. * - mesh (Mesh) : the main mesh to create the submesh from.
  26464. * - renderingMesh (optional Mesh) : rendering mesh.
  26465. */
  26466. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26467. var minVertexIndex = Number.MAX_VALUE;
  26468. var maxVertexIndex = -Number.MAX_VALUE;
  26469. renderingMesh = (renderingMesh || mesh);
  26470. var indices = renderingMesh.getIndices();
  26471. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26472. var vertexIndex = indices[index];
  26473. if (vertexIndex < minVertexIndex)
  26474. minVertexIndex = vertexIndex;
  26475. if (vertexIndex > maxVertexIndex)
  26476. maxVertexIndex = vertexIndex;
  26477. }
  26478. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26479. };
  26480. return SubMesh;
  26481. }(BaseSubMesh));
  26482. BABYLON.SubMesh = SubMesh;
  26483. })(BABYLON || (BABYLON = {}));
  26484. //# sourceMappingURL=babylon.subMesh.js.map
  26485. var BABYLON;
  26486. (function (BABYLON) {
  26487. var EffectFallbacks = /** @class */ (function () {
  26488. function EffectFallbacks() {
  26489. this._defines = {};
  26490. this._currentRank = 32;
  26491. this._maxRank = -1;
  26492. }
  26493. EffectFallbacks.prototype.unBindMesh = function () {
  26494. this._mesh = null;
  26495. };
  26496. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26497. if (!this._defines[rank]) {
  26498. if (rank < this._currentRank) {
  26499. this._currentRank = rank;
  26500. }
  26501. if (rank > this._maxRank) {
  26502. this._maxRank = rank;
  26503. }
  26504. this._defines[rank] = new Array();
  26505. }
  26506. this._defines[rank].push(define);
  26507. };
  26508. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26509. this._mesh = mesh;
  26510. if (rank < this._currentRank) {
  26511. this._currentRank = rank;
  26512. }
  26513. if (rank > this._maxRank) {
  26514. this._maxRank = rank;
  26515. }
  26516. };
  26517. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26518. get: function () {
  26519. return this._currentRank <= this._maxRank;
  26520. },
  26521. enumerable: true,
  26522. configurable: true
  26523. });
  26524. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26525. // First we try to switch to CPU skinning
  26526. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26527. this._mesh.computeBonesUsingShaders = false;
  26528. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26529. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26530. var scene = this._mesh.getScene();
  26531. for (var index = 0; index < scene.meshes.length; index++) {
  26532. var otherMesh = scene.meshes[index];
  26533. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26534. otherMesh.computeBonesUsingShaders = false;
  26535. }
  26536. }
  26537. }
  26538. else {
  26539. var currentFallbacks = this._defines[this._currentRank];
  26540. if (currentFallbacks) {
  26541. for (var index = 0; index < currentFallbacks.length; index++) {
  26542. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26543. }
  26544. }
  26545. this._currentRank++;
  26546. }
  26547. return currentDefines;
  26548. };
  26549. return EffectFallbacks;
  26550. }());
  26551. BABYLON.EffectFallbacks = EffectFallbacks;
  26552. var EffectCreationOptions = /** @class */ (function () {
  26553. function EffectCreationOptions() {
  26554. }
  26555. return EffectCreationOptions;
  26556. }());
  26557. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26558. var Effect = /** @class */ (function () {
  26559. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26560. if (samplers === void 0) { samplers = null; }
  26561. if (defines === void 0) { defines = null; }
  26562. if (fallbacks === void 0) { fallbacks = null; }
  26563. if (onCompiled === void 0) { onCompiled = null; }
  26564. if (onError === void 0) { onError = null; }
  26565. var _this = this;
  26566. this.uniqueId = 0;
  26567. this.onCompileObservable = new BABYLON.Observable();
  26568. this.onErrorObservable = new BABYLON.Observable();
  26569. this.onBindObservable = new BABYLON.Observable();
  26570. this._uniformBuffersNames = {};
  26571. this._isReady = false;
  26572. this._compilationError = "";
  26573. this.name = baseName;
  26574. if (attributesNamesOrOptions.attributes) {
  26575. var options = attributesNamesOrOptions;
  26576. this._engine = uniformsNamesOrEngine;
  26577. this._attributesNames = options.attributes;
  26578. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26579. this._samplers = options.samplers;
  26580. this.defines = options.defines;
  26581. this.onError = options.onError;
  26582. this.onCompiled = options.onCompiled;
  26583. this._fallbacks = options.fallbacks;
  26584. this._indexParameters = options.indexParameters;
  26585. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26586. if (options.uniformBuffersNames) {
  26587. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26588. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26589. }
  26590. }
  26591. }
  26592. else {
  26593. this._engine = engine;
  26594. this.defines = defines;
  26595. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26596. this._samplers = samplers;
  26597. this._attributesNames = attributesNamesOrOptions;
  26598. this.onError = onError;
  26599. this.onCompiled = onCompiled;
  26600. this._indexParameters = indexParameters;
  26601. this._fallbacks = fallbacks;
  26602. }
  26603. this.uniqueId = Effect._uniqueIdSeed++;
  26604. var vertexSource;
  26605. var fragmentSource;
  26606. if (baseName.vertexElement) {
  26607. vertexSource = document.getElementById(baseName.vertexElement);
  26608. if (!vertexSource) {
  26609. vertexSource = baseName.vertexElement;
  26610. }
  26611. }
  26612. else {
  26613. vertexSource = baseName.vertex || baseName;
  26614. }
  26615. if (baseName.fragmentElement) {
  26616. fragmentSource = document.getElementById(baseName.fragmentElement);
  26617. if (!fragmentSource) {
  26618. fragmentSource = baseName.fragmentElement;
  26619. }
  26620. }
  26621. else {
  26622. fragmentSource = baseName.fragment || baseName;
  26623. }
  26624. this._loadVertexShader(vertexSource, function (vertexCode) {
  26625. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26626. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26627. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26628. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26629. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26630. if (baseName) {
  26631. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26632. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26633. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26634. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26635. }
  26636. else {
  26637. _this._vertexSourceCode = migratedVertexCode;
  26638. _this._fragmentSourceCode = migratedFragmentCode;
  26639. }
  26640. _this._prepareEffect();
  26641. });
  26642. });
  26643. });
  26644. });
  26645. });
  26646. });
  26647. }
  26648. Object.defineProperty(Effect.prototype, "key", {
  26649. get: function () {
  26650. return this._key;
  26651. },
  26652. enumerable: true,
  26653. configurable: true
  26654. });
  26655. // Properties
  26656. Effect.prototype.isReady = function () {
  26657. return this._isReady;
  26658. };
  26659. Effect.prototype.getEngine = function () {
  26660. return this._engine;
  26661. };
  26662. Effect.prototype.getProgram = function () {
  26663. return this._program;
  26664. };
  26665. Effect.prototype.getAttributesNames = function () {
  26666. return this._attributesNames;
  26667. };
  26668. Effect.prototype.getAttributeLocation = function (index) {
  26669. return this._attributes[index];
  26670. };
  26671. Effect.prototype.getAttributeLocationByName = function (name) {
  26672. var index = this._attributesNames.indexOf(name);
  26673. return this._attributes[index];
  26674. };
  26675. Effect.prototype.getAttributesCount = function () {
  26676. return this._attributes.length;
  26677. };
  26678. Effect.prototype.getUniformIndex = function (uniformName) {
  26679. return this._uniformsNames.indexOf(uniformName);
  26680. };
  26681. Effect.prototype.getUniform = function (uniformName) {
  26682. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26683. };
  26684. Effect.prototype.getSamplers = function () {
  26685. return this._samplers;
  26686. };
  26687. Effect.prototype.getCompilationError = function () {
  26688. return this._compilationError;
  26689. };
  26690. // Methods
  26691. Effect.prototype.executeWhenCompiled = function (func) {
  26692. if (this.isReady()) {
  26693. func(this);
  26694. return;
  26695. }
  26696. this.onCompileObservable.add(function (effect) {
  26697. func(effect);
  26698. });
  26699. };
  26700. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26701. if (BABYLON.Tools.IsWindowObjectExist()) {
  26702. // DOM element ?
  26703. if (vertex instanceof HTMLElement) {
  26704. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26705. callback(vertexCode);
  26706. return;
  26707. }
  26708. }
  26709. // Base64 encoded ?
  26710. if (vertex.substr(0, 7) === "base64:") {
  26711. var vertexBinary = window.atob(vertex.substr(7));
  26712. callback(vertexBinary);
  26713. return;
  26714. }
  26715. // Is in local store ?
  26716. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26717. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26718. return;
  26719. }
  26720. var vertexShaderUrl;
  26721. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26722. vertexShaderUrl = vertex;
  26723. }
  26724. else {
  26725. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26726. }
  26727. // Vertex shader
  26728. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26729. };
  26730. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26731. if (BABYLON.Tools.IsWindowObjectExist()) {
  26732. // DOM element ?
  26733. if (fragment instanceof HTMLElement) {
  26734. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26735. callback(fragmentCode);
  26736. return;
  26737. }
  26738. }
  26739. // Base64 encoded ?
  26740. if (fragment.substr(0, 7) === "base64:") {
  26741. var fragmentBinary = window.atob(fragment.substr(7));
  26742. callback(fragmentBinary);
  26743. return;
  26744. }
  26745. // Is in local store ?
  26746. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26747. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26748. return;
  26749. }
  26750. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26751. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26752. return;
  26753. }
  26754. var fragmentShaderUrl;
  26755. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26756. fragmentShaderUrl = fragment;
  26757. }
  26758. else {
  26759. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26760. }
  26761. // Fragment shader
  26762. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26763. };
  26764. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26765. // Rebuild shaders source code
  26766. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26767. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26768. vertexCode = prefix + vertexCode;
  26769. fragmentCode = prefix + fragmentCode;
  26770. // Number lines of shaders source code
  26771. var i = 2;
  26772. var regex = /\n/gm;
  26773. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26774. i = 2;
  26775. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26776. // Dump shaders name and formatted source code
  26777. if (this.name.vertexElement) {
  26778. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26779. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26780. }
  26781. else if (this.name.vertex) {
  26782. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26783. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26784. }
  26785. else {
  26786. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26787. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26788. }
  26789. };
  26790. ;
  26791. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26792. var preparedSourceCode = this._processPrecision(sourceCode);
  26793. if (this._engine.webGLVersion == 1) {
  26794. callback(preparedSourceCode);
  26795. return;
  26796. }
  26797. // Already converted
  26798. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26799. callback(preparedSourceCode.replace("#version 300 es", ""));
  26800. return;
  26801. }
  26802. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26803. // Remove extensions
  26804. // #extension GL_OES_standard_derivatives : enable
  26805. // #extension GL_EXT_shader_texture_lod : enable
  26806. // #extension GL_EXT_frag_depth : enable
  26807. // #extension GL_EXT_draw_buffers : require
  26808. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26809. var result = preparedSourceCode.replace(regex, "");
  26810. // Migrate to GLSL v300
  26811. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26812. result = result.replace(/attribute[ \t]/g, "in ");
  26813. result = result.replace(/[ \t]attribute/g, " in");
  26814. if (isFragment) {
  26815. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26816. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26817. result = result.replace(/texture2D\s*\(/g, "texture(");
  26818. result = result.replace(/textureCube\s*\(/g, "texture(");
  26819. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26820. result = result.replace(/gl_FragColor/g, "glFragColor");
  26821. result = result.replace(/gl_FragData/g, "glFragData");
  26822. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26823. }
  26824. callback(result);
  26825. };
  26826. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26827. var _this = this;
  26828. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26829. var match = regex.exec(sourceCode);
  26830. var returnValue = new String(sourceCode);
  26831. while (match != null) {
  26832. var includeFile = match[1];
  26833. // Uniform declaration
  26834. if (includeFile.indexOf("__decl__") !== -1) {
  26835. includeFile = includeFile.replace(/__decl__/, "");
  26836. if (this._engine.supportsUniformBuffers) {
  26837. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26838. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26839. }
  26840. includeFile = includeFile + "Declaration";
  26841. }
  26842. if (Effect.IncludesShadersStore[includeFile]) {
  26843. // Substitution
  26844. var includeContent = Effect.IncludesShadersStore[includeFile];
  26845. if (match[2]) {
  26846. var splits = match[3].split(",");
  26847. for (var index = 0; index < splits.length; index += 2) {
  26848. var source = new RegExp(splits[index], "g");
  26849. var dest = splits[index + 1];
  26850. includeContent = includeContent.replace(source, dest);
  26851. }
  26852. }
  26853. if (match[4]) {
  26854. var indexString = match[5];
  26855. if (indexString.indexOf("..") !== -1) {
  26856. var indexSplits = indexString.split("..");
  26857. var minIndex = parseInt(indexSplits[0]);
  26858. var maxIndex = parseInt(indexSplits[1]);
  26859. var sourceIncludeContent = includeContent.slice(0);
  26860. includeContent = "";
  26861. if (isNaN(maxIndex)) {
  26862. maxIndex = this._indexParameters[indexSplits[1]];
  26863. }
  26864. for (var i = minIndex; i < maxIndex; i++) {
  26865. if (!this._engine.supportsUniformBuffers) {
  26866. // Ubo replacement
  26867. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26868. return p1 + "{X}";
  26869. });
  26870. }
  26871. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26872. }
  26873. }
  26874. else {
  26875. if (!this._engine.supportsUniformBuffers) {
  26876. // Ubo replacement
  26877. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26878. return p1 + "{X}";
  26879. });
  26880. }
  26881. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26882. }
  26883. }
  26884. // Replace
  26885. returnValue = returnValue.replace(match[0], includeContent);
  26886. }
  26887. else {
  26888. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26889. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26890. Effect.IncludesShadersStore[includeFile] = fileContent;
  26891. _this._processIncludes(returnValue, callback);
  26892. });
  26893. return;
  26894. }
  26895. match = regex.exec(sourceCode);
  26896. }
  26897. callback(returnValue);
  26898. };
  26899. Effect.prototype._processPrecision = function (source) {
  26900. if (source.indexOf("precision highp float") === -1) {
  26901. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26902. source = "precision mediump float;\n" + source;
  26903. }
  26904. else {
  26905. source = "precision highp float;\n" + source;
  26906. }
  26907. }
  26908. else {
  26909. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26910. source = source.replace("precision highp float", "precision mediump float");
  26911. }
  26912. }
  26913. return source;
  26914. };
  26915. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26916. var _this = this;
  26917. this._isReady = false;
  26918. this._vertexSourceCodeOverride = vertexSourceCode;
  26919. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26920. this.onError = function (effect, error) {
  26921. if (onError) {
  26922. onError(error);
  26923. }
  26924. };
  26925. this.onCompiled = function () {
  26926. var scenes = _this.getEngine().scenes;
  26927. for (var i = 0; i < scenes.length; i++) {
  26928. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26929. }
  26930. if (onCompiled) {
  26931. onCompiled(_this._program);
  26932. }
  26933. };
  26934. this._fallbacks = null;
  26935. this._prepareEffect();
  26936. };
  26937. Effect.prototype._prepareEffect = function () {
  26938. var attributesNames = this._attributesNames;
  26939. var defines = this.defines;
  26940. var fallbacks = this._fallbacks;
  26941. this._valueCache = {};
  26942. var previousProgram = this._program;
  26943. try {
  26944. var engine = this._engine;
  26945. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26946. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26947. }
  26948. else {
  26949. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26950. }
  26951. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26952. if (engine.supportsUniformBuffers) {
  26953. for (var name in this._uniformBuffersNames) {
  26954. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26955. }
  26956. }
  26957. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26958. this._attributes = engine.getAttributes(this._program, attributesNames);
  26959. var index;
  26960. for (index = 0; index < this._samplers.length; index++) {
  26961. var sampler = this.getUniform(this._samplers[index]);
  26962. if (sampler == null) {
  26963. this._samplers.splice(index, 1);
  26964. index--;
  26965. }
  26966. }
  26967. engine.bindSamplers(this);
  26968. this._compilationError = "";
  26969. this._isReady = true;
  26970. if (this.onCompiled) {
  26971. this.onCompiled(this);
  26972. }
  26973. this.onCompileObservable.notifyObservers(this);
  26974. this.onCompileObservable.clear();
  26975. // Unbind mesh reference in fallbacks
  26976. if (this._fallbacks) {
  26977. this._fallbacks.unBindMesh();
  26978. }
  26979. if (previousProgram) {
  26980. this.getEngine()._deleteProgram(previousProgram);
  26981. }
  26982. }
  26983. catch (e) {
  26984. this._compilationError = e.message;
  26985. // Let's go through fallbacks then
  26986. BABYLON.Tools.Error("Unable to compile effect:");
  26987. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26988. return " " + uniform;
  26989. }));
  26990. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26991. return " " + attribute;
  26992. }));
  26993. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26994. BABYLON.Tools.Error("Error: " + this._compilationError);
  26995. if (previousProgram) {
  26996. this._program = previousProgram;
  26997. this._isReady = true;
  26998. if (this.onError) {
  26999. this.onError(this, this._compilationError);
  27000. }
  27001. this.onErrorObservable.notifyObservers(this);
  27002. }
  27003. if (fallbacks && fallbacks.isMoreFallbacks) {
  27004. BABYLON.Tools.Error("Trying next fallback.");
  27005. this.defines = fallbacks.reduce(this.defines);
  27006. this._prepareEffect();
  27007. }
  27008. else {
  27009. if (this.onError) {
  27010. this.onError(this, this._compilationError);
  27011. }
  27012. this.onErrorObservable.notifyObservers(this);
  27013. this.onErrorObservable.clear();
  27014. // Unbind mesh reference in fallbacks
  27015. if (this._fallbacks) {
  27016. this._fallbacks.unBindMesh();
  27017. }
  27018. }
  27019. }
  27020. };
  27021. Object.defineProperty(Effect.prototype, "isSupported", {
  27022. get: function () {
  27023. return this._compilationError === "";
  27024. },
  27025. enumerable: true,
  27026. configurable: true
  27027. });
  27028. Effect.prototype._bindTexture = function (channel, texture) {
  27029. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27030. };
  27031. Effect.prototype.setTexture = function (channel, texture) {
  27032. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27033. };
  27034. Effect.prototype.setTextureArray = function (channel, textures) {
  27035. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27036. var initialPos = this._samplers.indexOf(channel);
  27037. for (var index = 1; index < textures.length; index++) {
  27038. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27039. }
  27040. }
  27041. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27042. };
  27043. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27044. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27045. };
  27046. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27047. var cache = this._valueCache[uniformName];
  27048. var flag = matrix.updateFlag;
  27049. if (cache !== undefined && cache === flag) {
  27050. return false;
  27051. }
  27052. this._valueCache[uniformName] = flag;
  27053. return true;
  27054. };
  27055. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27056. var cache = this._valueCache[uniformName];
  27057. if (!cache) {
  27058. cache = [x, y];
  27059. this._valueCache[uniformName] = cache;
  27060. return true;
  27061. }
  27062. var changed = false;
  27063. if (cache[0] !== x) {
  27064. cache[0] = x;
  27065. changed = true;
  27066. }
  27067. if (cache[1] !== y) {
  27068. cache[1] = y;
  27069. changed = true;
  27070. }
  27071. return changed;
  27072. };
  27073. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27074. var cache = this._valueCache[uniformName];
  27075. if (!cache) {
  27076. cache = [x, y, z];
  27077. this._valueCache[uniformName] = cache;
  27078. return true;
  27079. }
  27080. var changed = false;
  27081. if (cache[0] !== x) {
  27082. cache[0] = x;
  27083. changed = true;
  27084. }
  27085. if (cache[1] !== y) {
  27086. cache[1] = y;
  27087. changed = true;
  27088. }
  27089. if (cache[2] !== z) {
  27090. cache[2] = z;
  27091. changed = true;
  27092. }
  27093. return changed;
  27094. };
  27095. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27096. var cache = this._valueCache[uniformName];
  27097. if (!cache) {
  27098. cache = [x, y, z, w];
  27099. this._valueCache[uniformName] = cache;
  27100. return true;
  27101. }
  27102. var changed = false;
  27103. if (cache[0] !== x) {
  27104. cache[0] = x;
  27105. changed = true;
  27106. }
  27107. if (cache[1] !== y) {
  27108. cache[1] = y;
  27109. changed = true;
  27110. }
  27111. if (cache[2] !== z) {
  27112. cache[2] = z;
  27113. changed = true;
  27114. }
  27115. if (cache[3] !== w) {
  27116. cache[3] = w;
  27117. changed = true;
  27118. }
  27119. return changed;
  27120. };
  27121. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27122. var bufferName = this._uniformBuffersNames[name];
  27123. if (Effect._baseCache[bufferName] === buffer) {
  27124. return;
  27125. }
  27126. Effect._baseCache[bufferName] = buffer;
  27127. this._engine.bindUniformBufferBase(buffer, bufferName);
  27128. };
  27129. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27130. this._engine.bindUniformBlock(this._program, blockName, index);
  27131. };
  27132. Effect.prototype.setIntArray = function (uniformName, array) {
  27133. this._valueCache[uniformName] = null;
  27134. this._engine.setIntArray(this.getUniform(uniformName), array);
  27135. return this;
  27136. };
  27137. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27138. this._valueCache[uniformName] = null;
  27139. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27140. return this;
  27141. };
  27142. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27143. this._valueCache[uniformName] = null;
  27144. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27145. return this;
  27146. };
  27147. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27148. this._valueCache[uniformName] = null;
  27149. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27150. return this;
  27151. };
  27152. Effect.prototype.setFloatArray = function (uniformName, array) {
  27153. this._valueCache[uniformName] = null;
  27154. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27155. return this;
  27156. };
  27157. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27158. this._valueCache[uniformName] = null;
  27159. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27160. return this;
  27161. };
  27162. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27163. this._valueCache[uniformName] = null;
  27164. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27165. return this;
  27166. };
  27167. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27168. this._valueCache[uniformName] = null;
  27169. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27170. return this;
  27171. };
  27172. Effect.prototype.setArray = function (uniformName, array) {
  27173. this._valueCache[uniformName] = null;
  27174. this._engine.setArray(this.getUniform(uniformName), array);
  27175. return this;
  27176. };
  27177. Effect.prototype.setArray2 = function (uniformName, array) {
  27178. this._valueCache[uniformName] = null;
  27179. this._engine.setArray2(this.getUniform(uniformName), array);
  27180. return this;
  27181. };
  27182. Effect.prototype.setArray3 = function (uniformName, array) {
  27183. this._valueCache[uniformName] = null;
  27184. this._engine.setArray3(this.getUniform(uniformName), array);
  27185. return this;
  27186. };
  27187. Effect.prototype.setArray4 = function (uniformName, array) {
  27188. this._valueCache[uniformName] = null;
  27189. this._engine.setArray4(this.getUniform(uniformName), array);
  27190. return this;
  27191. };
  27192. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27193. if (!matrices) {
  27194. return this;
  27195. }
  27196. this._valueCache[uniformName] = null;
  27197. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27198. return this;
  27199. };
  27200. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27201. if (this._cacheMatrix(uniformName, matrix)) {
  27202. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27203. }
  27204. return this;
  27205. };
  27206. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27207. this._valueCache[uniformName] = null;
  27208. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27209. return this;
  27210. };
  27211. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27212. this._valueCache[uniformName] = null;
  27213. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27214. return this;
  27215. };
  27216. Effect.prototype.setFloat = function (uniformName, value) {
  27217. var cache = this._valueCache[uniformName];
  27218. if (cache !== undefined && cache === value)
  27219. return this;
  27220. this._valueCache[uniformName] = value;
  27221. this._engine.setFloat(this.getUniform(uniformName), value);
  27222. return this;
  27223. };
  27224. Effect.prototype.setBool = function (uniformName, bool) {
  27225. var cache = this._valueCache[uniformName];
  27226. if (cache !== undefined && cache === bool)
  27227. return this;
  27228. this._valueCache[uniformName] = bool;
  27229. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27230. return this;
  27231. };
  27232. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27233. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27234. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27235. }
  27236. return this;
  27237. };
  27238. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27239. if (this._cacheFloat2(uniformName, x, y)) {
  27240. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27241. }
  27242. return this;
  27243. };
  27244. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27245. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27246. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27247. }
  27248. return this;
  27249. };
  27250. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27251. if (this._cacheFloat3(uniformName, x, y, z)) {
  27252. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27253. }
  27254. return this;
  27255. };
  27256. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27257. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27258. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27259. }
  27260. return this;
  27261. };
  27262. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27263. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27264. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27265. }
  27266. return this;
  27267. };
  27268. Effect.prototype.setColor3 = function (uniformName, color3) {
  27269. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27270. this._engine.setColor3(this.getUniform(uniformName), color3);
  27271. }
  27272. return this;
  27273. };
  27274. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27275. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27276. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27277. }
  27278. return this;
  27279. };
  27280. Effect.ResetCache = function () {
  27281. Effect._baseCache = {};
  27282. };
  27283. Effect._uniqueIdSeed = 0;
  27284. Effect._baseCache = {};
  27285. // Statics
  27286. Effect.ShadersStore = {};
  27287. Effect.IncludesShadersStore = {};
  27288. return Effect;
  27289. }());
  27290. BABYLON.Effect = Effect;
  27291. })(BABYLON || (BABYLON = {}));
  27292. //# sourceMappingURL=babylon.effect.js.map
  27293. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27294. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27295. s = arguments[i];
  27296. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27297. t[p] = s[p];
  27298. }
  27299. return t;
  27300. };
  27301. var BABYLON;
  27302. (function (BABYLON) {
  27303. var MaterialDefines = /** @class */ (function () {
  27304. function MaterialDefines() {
  27305. this._isDirty = true;
  27306. this._areLightsDirty = true;
  27307. this._areAttributesDirty = true;
  27308. this._areTexturesDirty = true;
  27309. this._areFresnelDirty = true;
  27310. this._areMiscDirty = true;
  27311. this._areImageProcessingDirty = true;
  27312. this._normals = false;
  27313. this._uvs = false;
  27314. this._needNormals = false;
  27315. this._needUVs = false;
  27316. }
  27317. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27318. get: function () {
  27319. return this._isDirty;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. MaterialDefines.prototype.markAsProcessed = function () {
  27325. this._isDirty = false;
  27326. this._areAttributesDirty = false;
  27327. this._areTexturesDirty = false;
  27328. this._areFresnelDirty = false;
  27329. this._areLightsDirty = false;
  27330. this._areMiscDirty = false;
  27331. this._areImageProcessingDirty = false;
  27332. };
  27333. MaterialDefines.prototype.markAsUnprocessed = function () {
  27334. this._isDirty = true;
  27335. };
  27336. MaterialDefines.prototype.markAllAsDirty = function () {
  27337. this._areTexturesDirty = true;
  27338. this._areAttributesDirty = true;
  27339. this._areLightsDirty = true;
  27340. this._areFresnelDirty = true;
  27341. this._areMiscDirty = true;
  27342. this._areImageProcessingDirty = true;
  27343. this._isDirty = true;
  27344. };
  27345. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27346. this._areImageProcessingDirty = true;
  27347. this._isDirty = true;
  27348. };
  27349. MaterialDefines.prototype.markAsLightDirty = function () {
  27350. this._areLightsDirty = true;
  27351. this._isDirty = true;
  27352. };
  27353. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27354. this._areAttributesDirty = true;
  27355. this._isDirty = true;
  27356. };
  27357. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27358. this._areTexturesDirty = true;
  27359. this._isDirty = true;
  27360. };
  27361. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27362. this._areFresnelDirty = true;
  27363. this._isDirty = true;
  27364. };
  27365. MaterialDefines.prototype.markAsMiscDirty = function () {
  27366. this._areMiscDirty = true;
  27367. this._isDirty = true;
  27368. };
  27369. MaterialDefines.prototype.rebuild = function () {
  27370. if (this._keys) {
  27371. delete this._keys;
  27372. }
  27373. this._keys = [];
  27374. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27375. var key = _a[_i];
  27376. if (key[0] === "_") {
  27377. continue;
  27378. }
  27379. this._keys.push(key);
  27380. }
  27381. };
  27382. MaterialDefines.prototype.isEqual = function (other) {
  27383. if (this._keys.length !== other._keys.length) {
  27384. return false;
  27385. }
  27386. for (var index = 0; index < this._keys.length; index++) {
  27387. var prop = this._keys[index];
  27388. if (this[prop] !== other[prop]) {
  27389. return false;
  27390. }
  27391. }
  27392. return true;
  27393. };
  27394. MaterialDefines.prototype.cloneTo = function (other) {
  27395. if (this._keys.length !== other._keys.length) {
  27396. other._keys = this._keys.slice(0);
  27397. }
  27398. for (var index = 0; index < this._keys.length; index++) {
  27399. var prop = this._keys[index];
  27400. other[prop] = this[prop];
  27401. }
  27402. };
  27403. MaterialDefines.prototype.reset = function () {
  27404. for (var index = 0; index < this._keys.length; index++) {
  27405. var prop = this._keys[index];
  27406. if (typeof (this[prop]) === "number") {
  27407. this[prop] = 0;
  27408. }
  27409. else {
  27410. this[prop] = false;
  27411. }
  27412. }
  27413. };
  27414. MaterialDefines.prototype.toString = function () {
  27415. var result = "";
  27416. for (var index = 0; index < this._keys.length; index++) {
  27417. var prop = this._keys[index];
  27418. var value = this[prop];
  27419. if (typeof (value) === "number") {
  27420. result += "#define " + prop + " " + this[prop] + "\n";
  27421. }
  27422. else if (value) {
  27423. result += "#define " + prop + "\n";
  27424. }
  27425. }
  27426. return result;
  27427. };
  27428. return MaterialDefines;
  27429. }());
  27430. BABYLON.MaterialDefines = MaterialDefines;
  27431. var Material = /** @class */ (function () {
  27432. function Material(name, scene, doNotAdd) {
  27433. this.checkReadyOnEveryCall = false;
  27434. this.checkReadyOnlyOnce = false;
  27435. this.state = "";
  27436. this.alpha = 1.0;
  27437. this._backFaceCulling = true;
  27438. this.doNotSerialize = false;
  27439. this.storeEffectOnSubMeshes = false;
  27440. /**
  27441. * An event triggered when the material is disposed.
  27442. * @type {BABYLON.Observable}
  27443. */
  27444. this.onDisposeObservable = new BABYLON.Observable();
  27445. /**
  27446. * An event triggered when the material is bound.
  27447. * @type {BABYLON.Observable}
  27448. */
  27449. this.onBindObservable = new BABYLON.Observable();
  27450. /**
  27451. * An event triggered when the material is unbound.
  27452. * @type {BABYLON.Observable}
  27453. */
  27454. this.onUnBindObservable = new BABYLON.Observable();
  27455. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27456. this._needDepthPrePass = false;
  27457. this.disableDepthWrite = false;
  27458. this.forceDepthWrite = false;
  27459. this.separateCullingPass = false;
  27460. this._fogEnabled = true;
  27461. this.pointSize = 1.0;
  27462. this.zOffset = 0;
  27463. this._wasPreviouslyReady = false;
  27464. this._fillMode = Material.TriangleFillMode;
  27465. this.name = name;
  27466. this.id = name || BABYLON.Tools.RandomId();
  27467. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27468. if (this._scene.useRightHandedSystem) {
  27469. this.sideOrientation = Material.ClockWiseSideOrientation;
  27470. }
  27471. else {
  27472. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27473. }
  27474. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27475. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27476. if (!doNotAdd) {
  27477. this._scene.materials.push(this);
  27478. }
  27479. }
  27480. Object.defineProperty(Material, "TriangleFillMode", {
  27481. get: function () {
  27482. return Material._TriangleFillMode;
  27483. },
  27484. enumerable: true,
  27485. configurable: true
  27486. });
  27487. Object.defineProperty(Material, "WireFrameFillMode", {
  27488. get: function () {
  27489. return Material._WireFrameFillMode;
  27490. },
  27491. enumerable: true,
  27492. configurable: true
  27493. });
  27494. Object.defineProperty(Material, "PointFillMode", {
  27495. get: function () {
  27496. return Material._PointFillMode;
  27497. },
  27498. enumerable: true,
  27499. configurable: true
  27500. });
  27501. Object.defineProperty(Material, "PointListDrawMode", {
  27502. get: function () {
  27503. return Material._PointListDrawMode;
  27504. },
  27505. enumerable: true,
  27506. configurable: true
  27507. });
  27508. Object.defineProperty(Material, "LineListDrawMode", {
  27509. get: function () {
  27510. return Material._LineListDrawMode;
  27511. },
  27512. enumerable: true,
  27513. configurable: true
  27514. });
  27515. Object.defineProperty(Material, "LineLoopDrawMode", {
  27516. get: function () {
  27517. return Material._LineLoopDrawMode;
  27518. },
  27519. enumerable: true,
  27520. configurable: true
  27521. });
  27522. Object.defineProperty(Material, "LineStripDrawMode", {
  27523. get: function () {
  27524. return Material._LineStripDrawMode;
  27525. },
  27526. enumerable: true,
  27527. configurable: true
  27528. });
  27529. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27530. get: function () {
  27531. return Material._TriangleStripDrawMode;
  27532. },
  27533. enumerable: true,
  27534. configurable: true
  27535. });
  27536. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27537. get: function () {
  27538. return Material._TriangleFanDrawMode;
  27539. },
  27540. enumerable: true,
  27541. configurable: true
  27542. });
  27543. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27544. get: function () {
  27545. return Material._ClockWiseSideOrientation;
  27546. },
  27547. enumerable: true,
  27548. configurable: true
  27549. });
  27550. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27551. get: function () {
  27552. return Material._CounterClockWiseSideOrientation;
  27553. },
  27554. enumerable: true,
  27555. configurable: true
  27556. });
  27557. Object.defineProperty(Material, "TextureDirtyFlag", {
  27558. get: function () {
  27559. return Material._TextureDirtyFlag;
  27560. },
  27561. enumerable: true,
  27562. configurable: true
  27563. });
  27564. Object.defineProperty(Material, "LightDirtyFlag", {
  27565. get: function () {
  27566. return Material._LightDirtyFlag;
  27567. },
  27568. enumerable: true,
  27569. configurable: true
  27570. });
  27571. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27572. get: function () {
  27573. return Material._FresnelDirtyFlag;
  27574. },
  27575. enumerable: true,
  27576. configurable: true
  27577. });
  27578. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27579. get: function () {
  27580. return Material._AttributesDirtyFlag;
  27581. },
  27582. enumerable: true,
  27583. configurable: true
  27584. });
  27585. Object.defineProperty(Material, "MiscDirtyFlag", {
  27586. get: function () {
  27587. return Material._MiscDirtyFlag;
  27588. },
  27589. enumerable: true,
  27590. configurable: true
  27591. });
  27592. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27593. get: function () {
  27594. return this._backFaceCulling;
  27595. },
  27596. set: function (value) {
  27597. if (this._backFaceCulling === value) {
  27598. return;
  27599. }
  27600. this._backFaceCulling = value;
  27601. this.markAsDirty(Material.TextureDirtyFlag);
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. Object.defineProperty(Material.prototype, "onDispose", {
  27607. set: function (callback) {
  27608. if (this._onDisposeObserver) {
  27609. this.onDisposeObservable.remove(this._onDisposeObserver);
  27610. }
  27611. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27612. },
  27613. enumerable: true,
  27614. configurable: true
  27615. });
  27616. Object.defineProperty(Material.prototype, "onBind", {
  27617. set: function (callback) {
  27618. if (this._onBindObserver) {
  27619. this.onBindObservable.remove(this._onBindObserver);
  27620. }
  27621. this._onBindObserver = this.onBindObservable.add(callback);
  27622. },
  27623. enumerable: true,
  27624. configurable: true
  27625. });
  27626. Object.defineProperty(Material.prototype, "alphaMode", {
  27627. get: function () {
  27628. return this._alphaMode;
  27629. },
  27630. set: function (value) {
  27631. if (this._alphaMode === value) {
  27632. return;
  27633. }
  27634. this._alphaMode = value;
  27635. this.markAsDirty(Material.TextureDirtyFlag);
  27636. },
  27637. enumerable: true,
  27638. configurable: true
  27639. });
  27640. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27641. get: function () {
  27642. return this._needDepthPrePass;
  27643. },
  27644. set: function (value) {
  27645. if (this._needDepthPrePass === value) {
  27646. return;
  27647. }
  27648. this._needDepthPrePass = value;
  27649. if (this._needDepthPrePass) {
  27650. this.checkReadyOnEveryCall = true;
  27651. }
  27652. },
  27653. enumerable: true,
  27654. configurable: true
  27655. });
  27656. Object.defineProperty(Material.prototype, "fogEnabled", {
  27657. get: function () {
  27658. return this._fogEnabled;
  27659. },
  27660. set: function (value) {
  27661. if (this._fogEnabled === value) {
  27662. return;
  27663. }
  27664. this._fogEnabled = value;
  27665. this.markAsDirty(Material.MiscDirtyFlag);
  27666. },
  27667. enumerable: true,
  27668. configurable: true
  27669. });
  27670. Object.defineProperty(Material.prototype, "wireframe", {
  27671. get: function () {
  27672. return this._fillMode === Material.WireFrameFillMode;
  27673. },
  27674. set: function (value) {
  27675. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27676. },
  27677. enumerable: true,
  27678. configurable: true
  27679. });
  27680. Object.defineProperty(Material.prototype, "pointsCloud", {
  27681. get: function () {
  27682. return this._fillMode === Material.PointFillMode;
  27683. },
  27684. set: function (value) {
  27685. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27686. },
  27687. enumerable: true,
  27688. configurable: true
  27689. });
  27690. Object.defineProperty(Material.prototype, "fillMode", {
  27691. get: function () {
  27692. return this._fillMode;
  27693. },
  27694. set: function (value) {
  27695. if (this._fillMode === value) {
  27696. return;
  27697. }
  27698. this._fillMode = value;
  27699. this.markAsDirty(Material.MiscDirtyFlag);
  27700. },
  27701. enumerable: true,
  27702. configurable: true
  27703. });
  27704. /**
  27705. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27706. * subclasses should override adding information pertainent to themselves
  27707. */
  27708. Material.prototype.toString = function (fullDetails) {
  27709. var ret = "Name: " + this.name;
  27710. if (fullDetails) {
  27711. }
  27712. return ret;
  27713. };
  27714. /**
  27715. * Child classes can use it to update shaders
  27716. */
  27717. Material.prototype.getClassName = function () {
  27718. return "Material";
  27719. };
  27720. Object.defineProperty(Material.prototype, "isFrozen", {
  27721. get: function () {
  27722. return this.checkReadyOnlyOnce;
  27723. },
  27724. enumerable: true,
  27725. configurable: true
  27726. });
  27727. Material.prototype.freeze = function () {
  27728. this.checkReadyOnlyOnce = true;
  27729. };
  27730. Material.prototype.unfreeze = function () {
  27731. this.checkReadyOnlyOnce = false;
  27732. };
  27733. Material.prototype.isReady = function (mesh, useInstances) {
  27734. return true;
  27735. };
  27736. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27737. return false;
  27738. };
  27739. Material.prototype.getEffect = function () {
  27740. return this._effect;
  27741. };
  27742. Material.prototype.getScene = function () {
  27743. return this._scene;
  27744. };
  27745. Material.prototype.needAlphaBlending = function () {
  27746. return (this.alpha < 1.0);
  27747. };
  27748. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27749. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27750. };
  27751. Material.prototype.needAlphaTesting = function () {
  27752. return false;
  27753. };
  27754. Material.prototype.getAlphaTestTexture = function () {
  27755. return null;
  27756. };
  27757. Material.prototype.markDirty = function () {
  27758. this._wasPreviouslyReady = false;
  27759. };
  27760. Material.prototype._preBind = function (effect, overrideOrientation) {
  27761. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27762. var engine = this._scene.getEngine();
  27763. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27764. var reverse = orientation === Material.ClockWiseSideOrientation;
  27765. engine.enableEffect(effect ? effect : this._effect);
  27766. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27767. return reverse;
  27768. };
  27769. Material.prototype.bind = function (world, mesh) {
  27770. };
  27771. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27772. };
  27773. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27774. };
  27775. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27776. sceneUbo.bindToEffect(effect, "Scene");
  27777. };
  27778. Material.prototype.bindView = function (effect) {
  27779. if (!this._useUBO) {
  27780. effect.setMatrix("view", this.getScene().getViewMatrix());
  27781. }
  27782. else {
  27783. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27784. }
  27785. };
  27786. Material.prototype.bindViewProjection = function (effect) {
  27787. if (!this._useUBO) {
  27788. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27789. }
  27790. else {
  27791. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27792. }
  27793. };
  27794. Material.prototype._afterBind = function (mesh) {
  27795. this._scene._cachedMaterial = this;
  27796. if (mesh) {
  27797. this._scene._cachedVisibility = mesh.visibility;
  27798. }
  27799. else {
  27800. this._scene._cachedVisibility = 1;
  27801. }
  27802. if (mesh) {
  27803. this.onBindObservable.notifyObservers(mesh);
  27804. }
  27805. if (this.disableDepthWrite) {
  27806. var engine = this._scene.getEngine();
  27807. this._cachedDepthWriteState = engine.getDepthWrite();
  27808. engine.setDepthWrite(false);
  27809. }
  27810. };
  27811. Material.prototype.unbind = function () {
  27812. this.onUnBindObservable.notifyObservers(this);
  27813. if (this.disableDepthWrite) {
  27814. var engine = this._scene.getEngine();
  27815. engine.setDepthWrite(this._cachedDepthWriteState);
  27816. }
  27817. };
  27818. Material.prototype.getActiveTextures = function () {
  27819. return [];
  27820. };
  27821. Material.prototype.hasTexture = function (texture) {
  27822. return false;
  27823. };
  27824. Material.prototype.clone = function (name) {
  27825. return null;
  27826. };
  27827. Material.prototype.getBindedMeshes = function () {
  27828. var result = new Array();
  27829. for (var index = 0; index < this._scene.meshes.length; index++) {
  27830. var mesh = this._scene.meshes[index];
  27831. if (mesh.material === this) {
  27832. result.push(mesh);
  27833. }
  27834. }
  27835. return result;
  27836. };
  27837. /**
  27838. * Force shader compilation including textures ready check
  27839. */
  27840. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27841. var _this = this;
  27842. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27843. var subMesh = new BABYLON.BaseSubMesh();
  27844. var scene = this.getScene();
  27845. var engine = scene.getEngine();
  27846. var checkReady = function () {
  27847. if (!_this._scene || !_this._scene.getEngine()) {
  27848. return;
  27849. }
  27850. if (subMesh._materialDefines) {
  27851. subMesh._materialDefines._renderId = -1;
  27852. }
  27853. var alphaTestState = engine.getAlphaTesting();
  27854. var clipPlaneState = scene.clipPlane;
  27855. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27856. if (localOptions.clipPlane) {
  27857. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27858. }
  27859. if (_this.storeEffectOnSubMeshes) {
  27860. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27861. if (onCompiled) {
  27862. onCompiled(_this);
  27863. }
  27864. }
  27865. else {
  27866. setTimeout(checkReady, 16);
  27867. }
  27868. }
  27869. else {
  27870. if (_this.isReady(mesh)) {
  27871. if (onCompiled) {
  27872. onCompiled(_this);
  27873. }
  27874. }
  27875. else {
  27876. setTimeout(checkReady, 16);
  27877. }
  27878. }
  27879. engine.setAlphaTesting(alphaTestState);
  27880. if (options && options.clipPlane) {
  27881. scene.clipPlane = clipPlaneState;
  27882. }
  27883. };
  27884. checkReady();
  27885. };
  27886. Material.prototype.markAsDirty = function (flag) {
  27887. if (flag & Material.TextureDirtyFlag) {
  27888. this._markAllSubMeshesAsTexturesDirty();
  27889. }
  27890. if (flag & Material.LightDirtyFlag) {
  27891. this._markAllSubMeshesAsLightsDirty();
  27892. }
  27893. if (flag & Material.FresnelDirtyFlag) {
  27894. this._markAllSubMeshesAsFresnelDirty();
  27895. }
  27896. if (flag & Material.AttributesDirtyFlag) {
  27897. this._markAllSubMeshesAsAttributesDirty();
  27898. }
  27899. if (flag & Material.MiscDirtyFlag) {
  27900. this._markAllSubMeshesAsMiscDirty();
  27901. }
  27902. this.getScene().resetCachedMaterial();
  27903. };
  27904. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27905. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27906. var mesh = _a[_i];
  27907. if (!mesh.subMeshes) {
  27908. continue;
  27909. }
  27910. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27911. var subMesh = _c[_b];
  27912. if (subMesh.getMaterial() !== this) {
  27913. continue;
  27914. }
  27915. if (!subMesh._materialDefines) {
  27916. continue;
  27917. }
  27918. func(subMesh._materialDefines);
  27919. }
  27920. }
  27921. };
  27922. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27923. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27924. };
  27925. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27926. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27927. };
  27928. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27929. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27930. };
  27931. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27932. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27933. };
  27934. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27935. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27936. };
  27937. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27938. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27939. };
  27940. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27941. // Animations
  27942. this.getScene().stopAnimation(this);
  27943. // Remove from scene
  27944. var index = this._scene.materials.indexOf(this);
  27945. if (index >= 0) {
  27946. this._scene.materials.splice(index, 1);
  27947. }
  27948. // Remove from meshes
  27949. for (index = 0; index < this._scene.meshes.length; index++) {
  27950. var mesh = this._scene.meshes[index];
  27951. if (mesh.material === this) {
  27952. mesh.material = null;
  27953. if (mesh.geometry) {
  27954. var geometry = (mesh.geometry);
  27955. if (this.storeEffectOnSubMeshes) {
  27956. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27957. var subMesh = _a[_i];
  27958. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27959. if (forceDisposeEffect && subMesh._materialEffect) {
  27960. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27961. }
  27962. }
  27963. }
  27964. else {
  27965. geometry._releaseVertexArrayObject(this._effect);
  27966. }
  27967. }
  27968. }
  27969. }
  27970. this._uniformBuffer.dispose();
  27971. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27972. if (forceDisposeEffect && this._effect) {
  27973. if (!this.storeEffectOnSubMeshes) {
  27974. this._scene.getEngine()._releaseEffect(this._effect);
  27975. }
  27976. this._effect = null;
  27977. }
  27978. // Callback
  27979. this.onDisposeObservable.notifyObservers(this);
  27980. this.onDisposeObservable.clear();
  27981. this.onBindObservable.clear();
  27982. this.onUnBindObservable.clear();
  27983. };
  27984. Material.prototype.serialize = function () {
  27985. return BABYLON.SerializationHelper.Serialize(this);
  27986. };
  27987. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27988. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27989. multiMaterial.id = parsedMultiMaterial.id;
  27990. if (BABYLON.Tags) {
  27991. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27992. }
  27993. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27994. var subMatId = parsedMultiMaterial.materials[matIndex];
  27995. if (subMatId) {
  27996. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27997. }
  27998. else {
  27999. multiMaterial.subMaterials.push(null);
  28000. }
  28001. }
  28002. return multiMaterial;
  28003. };
  28004. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28005. if (!parsedMaterial.customType) {
  28006. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28007. }
  28008. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28009. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28010. if (!BABYLON.LegacyPBRMaterial) {
  28011. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28012. return;
  28013. }
  28014. }
  28015. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28016. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28017. ;
  28018. };
  28019. // Triangle views
  28020. Material._TriangleFillMode = 0;
  28021. Material._WireFrameFillMode = 1;
  28022. Material._PointFillMode = 2;
  28023. // Draw modes
  28024. Material._PointListDrawMode = 3;
  28025. Material._LineListDrawMode = 4;
  28026. Material._LineLoopDrawMode = 5;
  28027. Material._LineStripDrawMode = 6;
  28028. Material._TriangleStripDrawMode = 7;
  28029. Material._TriangleFanDrawMode = 8;
  28030. Material._ClockWiseSideOrientation = 0;
  28031. Material._CounterClockWiseSideOrientation = 1;
  28032. Material._TextureDirtyFlag = 1;
  28033. Material._LightDirtyFlag = 2;
  28034. Material._FresnelDirtyFlag = 4;
  28035. Material._AttributesDirtyFlag = 8;
  28036. Material._MiscDirtyFlag = 16;
  28037. __decorate([
  28038. BABYLON.serialize()
  28039. ], Material.prototype, "id", void 0);
  28040. __decorate([
  28041. BABYLON.serialize()
  28042. ], Material.prototype, "name", void 0);
  28043. __decorate([
  28044. BABYLON.serialize()
  28045. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28046. __decorate([
  28047. BABYLON.serialize()
  28048. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28049. __decorate([
  28050. BABYLON.serialize()
  28051. ], Material.prototype, "state", void 0);
  28052. __decorate([
  28053. BABYLON.serialize()
  28054. ], Material.prototype, "alpha", void 0);
  28055. __decorate([
  28056. BABYLON.serialize("backFaceCulling")
  28057. ], Material.prototype, "_backFaceCulling", void 0);
  28058. __decorate([
  28059. BABYLON.serialize()
  28060. ], Material.prototype, "sideOrientation", void 0);
  28061. __decorate([
  28062. BABYLON.serialize("alphaMode")
  28063. ], Material.prototype, "_alphaMode", void 0);
  28064. __decorate([
  28065. BABYLON.serialize()
  28066. ], Material.prototype, "_needDepthPrePass", void 0);
  28067. __decorate([
  28068. BABYLON.serialize()
  28069. ], Material.prototype, "disableDepthWrite", void 0);
  28070. __decorate([
  28071. BABYLON.serialize()
  28072. ], Material.prototype, "forceDepthWrite", void 0);
  28073. __decorate([
  28074. BABYLON.serialize()
  28075. ], Material.prototype, "separateCullingPass", void 0);
  28076. __decorate([
  28077. BABYLON.serialize("fogEnabled")
  28078. ], Material.prototype, "_fogEnabled", void 0);
  28079. __decorate([
  28080. BABYLON.serialize()
  28081. ], Material.prototype, "pointSize", void 0);
  28082. __decorate([
  28083. BABYLON.serialize()
  28084. ], Material.prototype, "zOffset", void 0);
  28085. __decorate([
  28086. BABYLON.serialize()
  28087. ], Material.prototype, "wireframe", null);
  28088. __decorate([
  28089. BABYLON.serialize()
  28090. ], Material.prototype, "pointsCloud", null);
  28091. __decorate([
  28092. BABYLON.serialize()
  28093. ], Material.prototype, "fillMode", null);
  28094. return Material;
  28095. }());
  28096. BABYLON.Material = Material;
  28097. })(BABYLON || (BABYLON = {}));
  28098. //# sourceMappingURL=babylon.material.js.map
  28099. var BABYLON;
  28100. (function (BABYLON) {
  28101. var UniformBuffer = /** @class */ (function () {
  28102. /**
  28103. * Uniform buffer objects.
  28104. *
  28105. * Handles blocks of uniform on the GPU.
  28106. *
  28107. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28108. *
  28109. * For more information, please refer to :
  28110. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28111. */
  28112. function UniformBuffer(engine, data, dynamic) {
  28113. this._engine = engine;
  28114. this._noUBO = !engine.supportsUniformBuffers;
  28115. this._dynamic = dynamic;
  28116. this._data = data || [];
  28117. this._uniformLocations = {};
  28118. this._uniformSizes = {};
  28119. this._uniformLocationPointer = 0;
  28120. this._needSync = false;
  28121. if (this._noUBO) {
  28122. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28123. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28124. this.updateFloat = this._updateFloatForEffect;
  28125. this.updateFloat2 = this._updateFloat2ForEffect;
  28126. this.updateFloat3 = this._updateFloat3ForEffect;
  28127. this.updateFloat4 = this._updateFloat4ForEffect;
  28128. this.updateMatrix = this._updateMatrixForEffect;
  28129. this.updateVector3 = this._updateVector3ForEffect;
  28130. this.updateVector4 = this._updateVector4ForEffect;
  28131. this.updateColor3 = this._updateColor3ForEffect;
  28132. this.updateColor4 = this._updateColor4ForEffect;
  28133. }
  28134. else {
  28135. this._engine._uniformBuffers.push(this);
  28136. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28137. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28138. this.updateFloat = this._updateFloatForUniform;
  28139. this.updateFloat2 = this._updateFloat2ForUniform;
  28140. this.updateFloat3 = this._updateFloat3ForUniform;
  28141. this.updateFloat4 = this._updateFloat4ForUniform;
  28142. this.updateMatrix = this._updateMatrixForUniform;
  28143. this.updateVector3 = this._updateVector3ForUniform;
  28144. this.updateVector4 = this._updateVector4ForUniform;
  28145. this.updateColor3 = this._updateColor3ForUniform;
  28146. this.updateColor4 = this._updateColor4ForUniform;
  28147. }
  28148. }
  28149. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28150. // Properties
  28151. /**
  28152. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28153. * or just falling back on setUniformXXX calls.
  28154. */
  28155. get: function () {
  28156. return !this._noUBO;
  28157. },
  28158. enumerable: true,
  28159. configurable: true
  28160. });
  28161. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28162. /**
  28163. * Indicates if the WebGL underlying uniform buffer is in sync
  28164. * with the javascript cache data.
  28165. */
  28166. get: function () {
  28167. return !this._needSync;
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. /**
  28173. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28174. * Also, a dynamic UniformBuffer will disable cache verification and always
  28175. * update the underlying WebGL uniform buffer to the GPU.
  28176. */
  28177. UniformBuffer.prototype.isDynamic = function () {
  28178. return this._dynamic !== undefined;
  28179. };
  28180. /**
  28181. * The data cache on JS side.
  28182. */
  28183. UniformBuffer.prototype.getData = function () {
  28184. return this._bufferData;
  28185. };
  28186. /**
  28187. * The underlying WebGL Uniform buffer.
  28188. */
  28189. UniformBuffer.prototype.getBuffer = function () {
  28190. return this._buffer;
  28191. };
  28192. /**
  28193. * std140 layout specifies how to align data within an UBO structure.
  28194. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28195. * for specs.
  28196. */
  28197. UniformBuffer.prototype._fillAlignment = function (size) {
  28198. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28199. // and 4x4 matrices
  28200. // TODO : change if other types are used
  28201. var alignment;
  28202. if (size <= 2) {
  28203. alignment = size;
  28204. }
  28205. else {
  28206. alignment = 4;
  28207. }
  28208. if ((this._uniformLocationPointer % alignment) !== 0) {
  28209. var oldPointer = this._uniformLocationPointer;
  28210. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28211. var diff = this._uniformLocationPointer - oldPointer;
  28212. for (var i = 0; i < diff; i++) {
  28213. this._data.push(0);
  28214. }
  28215. }
  28216. };
  28217. /**
  28218. * Adds an uniform in the buffer.
  28219. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28220. * for the layout to be correct !
  28221. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28222. * @param {number|number[]} size Data size, or data directly.
  28223. */
  28224. UniformBuffer.prototype.addUniform = function (name, size) {
  28225. if (this._noUBO) {
  28226. return;
  28227. }
  28228. if (this._uniformLocations[name] !== undefined) {
  28229. // Already existing uniform
  28230. return;
  28231. }
  28232. // This function must be called in the order of the shader layout !
  28233. // size can be the size of the uniform, or data directly
  28234. var data;
  28235. if (size instanceof Array) {
  28236. data = size;
  28237. size = data.length;
  28238. }
  28239. else {
  28240. size = size;
  28241. data = [];
  28242. // Fill with zeros
  28243. for (var i = 0; i < size; i++) {
  28244. data.push(0);
  28245. }
  28246. }
  28247. this._fillAlignment(size);
  28248. this._uniformSizes[name] = size;
  28249. this._uniformLocations[name] = this._uniformLocationPointer;
  28250. this._uniformLocationPointer += size;
  28251. for (var i = 0; i < size; i++) {
  28252. this._data.push(data[i]);
  28253. }
  28254. this._needSync = true;
  28255. };
  28256. /**
  28257. * Wrapper for addUniform.
  28258. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28259. * @param {Matrix} mat A 4x4 matrix.
  28260. */
  28261. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28262. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28263. };
  28264. /**
  28265. * Wrapper for addUniform.
  28266. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28267. * @param {number} x
  28268. * @param {number} y
  28269. */
  28270. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28271. var temp = [x, y];
  28272. this.addUniform(name, temp);
  28273. };
  28274. /**
  28275. * Wrapper for addUniform.
  28276. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28277. * @param {number} x
  28278. * @param {number} y
  28279. * @param {number} z
  28280. */
  28281. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28282. var temp = [x, y, z];
  28283. this.addUniform(name, temp);
  28284. };
  28285. /**
  28286. * Wrapper for addUniform.
  28287. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28288. * @param {Color3} color
  28289. */
  28290. UniformBuffer.prototype.addColor3 = function (name, color) {
  28291. var temp = new Array();
  28292. color.toArray(temp);
  28293. this.addUniform(name, temp);
  28294. };
  28295. /**
  28296. * Wrapper for addUniform.
  28297. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28298. * @param {Color3} color
  28299. * @param {number} alpha
  28300. */
  28301. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28302. var temp = new Array();
  28303. color.toArray(temp);
  28304. temp.push(alpha);
  28305. this.addUniform(name, temp);
  28306. };
  28307. /**
  28308. * Wrapper for addUniform.
  28309. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28310. * @param {Vector3} vector
  28311. */
  28312. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28313. var temp = new Array();
  28314. vector.toArray(temp);
  28315. this.addUniform(name, temp);
  28316. };
  28317. /**
  28318. * Wrapper for addUniform.
  28319. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28320. */
  28321. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28322. this.addUniform(name, 12);
  28323. };
  28324. /**
  28325. * Wrapper for addUniform.
  28326. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28327. */
  28328. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28329. this.addUniform(name, 8);
  28330. };
  28331. /**
  28332. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28333. */
  28334. UniformBuffer.prototype.create = function () {
  28335. if (this._noUBO) {
  28336. return;
  28337. }
  28338. if (this._buffer) {
  28339. return; // nothing to do
  28340. }
  28341. // See spec, alignment must be filled as a vec4
  28342. this._fillAlignment(4);
  28343. this._bufferData = new Float32Array(this._data);
  28344. this._rebuild();
  28345. this._needSync = true;
  28346. };
  28347. UniformBuffer.prototype._rebuild = function () {
  28348. if (this._noUBO) {
  28349. return;
  28350. }
  28351. if (this._dynamic) {
  28352. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28353. }
  28354. else {
  28355. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28356. }
  28357. };
  28358. /**
  28359. * Updates the WebGL Uniform Buffer on the GPU.
  28360. * If the `dynamic` flag is set to true, no cache comparison is done.
  28361. * Otherwise, the buffer will be updated only if the cache differs.
  28362. */
  28363. UniformBuffer.prototype.update = function () {
  28364. if (!this._buffer) {
  28365. this.create();
  28366. return;
  28367. }
  28368. if (!this._dynamic && !this._needSync) {
  28369. return;
  28370. }
  28371. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28372. this._needSync = false;
  28373. };
  28374. /**
  28375. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28376. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28377. * @param {number[]|Float32Array} data Flattened data
  28378. * @param {number} size Size of the data.
  28379. */
  28380. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28381. var location = this._uniformLocations[uniformName];
  28382. if (location === undefined) {
  28383. if (this._buffer) {
  28384. // Cannot add an uniform if the buffer is already created
  28385. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28386. return;
  28387. }
  28388. this.addUniform(uniformName, size);
  28389. location = this._uniformLocations[uniformName];
  28390. }
  28391. if (!this._buffer) {
  28392. this.create();
  28393. }
  28394. if (!this._dynamic) {
  28395. // Cache for static uniform buffers
  28396. var changed = false;
  28397. for (var i = 0; i < size; i++) {
  28398. if (this._bufferData[location + i] !== data[i]) {
  28399. changed = true;
  28400. this._bufferData[location + i] = data[i];
  28401. }
  28402. }
  28403. this._needSync = this._needSync || changed;
  28404. }
  28405. else {
  28406. // No cache for dynamic
  28407. for (var i = 0; i < size; i++) {
  28408. this._bufferData[location + i] = data[i];
  28409. }
  28410. }
  28411. };
  28412. // Update methods
  28413. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28414. // To match std140, matrix must be realigned
  28415. for (var i = 0; i < 3; i++) {
  28416. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28417. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28418. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28419. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28420. }
  28421. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28422. };
  28423. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28424. this._currentEffect.setMatrix3x3(name, matrix);
  28425. };
  28426. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28427. this._currentEffect.setMatrix2x2(name, matrix);
  28428. };
  28429. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28430. // To match std140, matrix must be realigned
  28431. for (var i = 0; i < 2; i++) {
  28432. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28433. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28434. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28435. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28436. }
  28437. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28438. };
  28439. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28440. this._currentEffect.setFloat(name, x);
  28441. };
  28442. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28443. UniformBuffer._tempBuffer[0] = x;
  28444. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28445. };
  28446. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28447. if (suffix === void 0) { suffix = ""; }
  28448. this._currentEffect.setFloat2(name + suffix, x, y);
  28449. };
  28450. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28451. if (suffix === void 0) { suffix = ""; }
  28452. UniformBuffer._tempBuffer[0] = x;
  28453. UniformBuffer._tempBuffer[1] = y;
  28454. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28455. };
  28456. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28457. if (suffix === void 0) { suffix = ""; }
  28458. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28459. };
  28460. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28461. if (suffix === void 0) { suffix = ""; }
  28462. UniformBuffer._tempBuffer[0] = x;
  28463. UniformBuffer._tempBuffer[1] = y;
  28464. UniformBuffer._tempBuffer[2] = z;
  28465. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28466. };
  28467. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28468. if (suffix === void 0) { suffix = ""; }
  28469. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28470. };
  28471. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28472. if (suffix === void 0) { suffix = ""; }
  28473. UniformBuffer._tempBuffer[0] = x;
  28474. UniformBuffer._tempBuffer[1] = y;
  28475. UniformBuffer._tempBuffer[2] = z;
  28476. UniformBuffer._tempBuffer[3] = w;
  28477. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28478. };
  28479. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28480. this._currentEffect.setMatrix(name, mat);
  28481. };
  28482. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28483. this.updateUniform(name, mat.toArray(), 16);
  28484. };
  28485. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28486. this._currentEffect.setVector3(name, vector);
  28487. };
  28488. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28489. vector.toArray(UniformBuffer._tempBuffer);
  28490. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28491. };
  28492. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28493. this._currentEffect.setVector4(name, vector);
  28494. };
  28495. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28496. vector.toArray(UniformBuffer._tempBuffer);
  28497. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28498. };
  28499. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28500. if (suffix === void 0) { suffix = ""; }
  28501. this._currentEffect.setColor3(name + suffix, color);
  28502. };
  28503. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28504. if (suffix === void 0) { suffix = ""; }
  28505. color.toArray(UniformBuffer._tempBuffer);
  28506. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28507. };
  28508. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28509. if (suffix === void 0) { suffix = ""; }
  28510. this._currentEffect.setColor4(name + suffix, color, alpha);
  28511. };
  28512. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28513. if (suffix === void 0) { suffix = ""; }
  28514. color.toArray(UniformBuffer._tempBuffer);
  28515. UniformBuffer._tempBuffer[3] = alpha;
  28516. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28517. };
  28518. /**
  28519. * Sets a sampler uniform on the effect.
  28520. * @param {string} name Name of the sampler.
  28521. * @param {Texture} texture
  28522. */
  28523. UniformBuffer.prototype.setTexture = function (name, texture) {
  28524. this._currentEffect.setTexture(name, texture);
  28525. };
  28526. /**
  28527. * Directly updates the value of the uniform in the cache AND on the GPU.
  28528. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28529. * @param {number[]|Float32Array} data Flattened data
  28530. */
  28531. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28532. this.updateUniform(uniformName, data, data.length);
  28533. this.update();
  28534. };
  28535. /**
  28536. * Binds this uniform buffer to an effect.
  28537. * @param {Effect} effect
  28538. * @param {string} name Name of the uniform block in the shader.
  28539. */
  28540. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28541. this._currentEffect = effect;
  28542. if (this._noUBO || !this._buffer) {
  28543. return;
  28544. }
  28545. effect.bindUniformBuffer(this._buffer, name);
  28546. };
  28547. /**
  28548. * Disposes the uniform buffer.
  28549. */
  28550. UniformBuffer.prototype.dispose = function () {
  28551. if (this._noUBO) {
  28552. return;
  28553. }
  28554. var index = this._engine._uniformBuffers.indexOf(this);
  28555. if (index !== -1) {
  28556. this._engine._uniformBuffers.splice(index, 1);
  28557. }
  28558. if (!this._buffer) {
  28559. return;
  28560. }
  28561. if (this._engine._releaseBuffer(this._buffer)) {
  28562. this._buffer = null;
  28563. }
  28564. };
  28565. // Pool for avoiding memory leaks
  28566. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28567. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28568. return UniformBuffer;
  28569. }());
  28570. BABYLON.UniformBuffer = UniformBuffer;
  28571. })(BABYLON || (BABYLON = {}));
  28572. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28573. var BABYLON;
  28574. (function (BABYLON) {
  28575. var VertexData = /** @class */ (function () {
  28576. function VertexData() {
  28577. }
  28578. VertexData.prototype.set = function (data, kind) {
  28579. switch (kind) {
  28580. case BABYLON.VertexBuffer.PositionKind:
  28581. this.positions = data;
  28582. break;
  28583. case BABYLON.VertexBuffer.NormalKind:
  28584. this.normals = data;
  28585. break;
  28586. case BABYLON.VertexBuffer.TangentKind:
  28587. this.tangents = data;
  28588. break;
  28589. case BABYLON.VertexBuffer.UVKind:
  28590. this.uvs = data;
  28591. break;
  28592. case BABYLON.VertexBuffer.UV2Kind:
  28593. this.uvs2 = data;
  28594. break;
  28595. case BABYLON.VertexBuffer.UV3Kind:
  28596. this.uvs3 = data;
  28597. break;
  28598. case BABYLON.VertexBuffer.UV4Kind:
  28599. this.uvs4 = data;
  28600. break;
  28601. case BABYLON.VertexBuffer.UV5Kind:
  28602. this.uvs5 = data;
  28603. break;
  28604. case BABYLON.VertexBuffer.UV6Kind:
  28605. this.uvs6 = data;
  28606. break;
  28607. case BABYLON.VertexBuffer.ColorKind:
  28608. this.colors = data;
  28609. break;
  28610. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28611. this.matricesIndices = data;
  28612. break;
  28613. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28614. this.matricesWeights = data;
  28615. break;
  28616. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28617. this.matricesIndicesExtra = data;
  28618. break;
  28619. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28620. this.matricesWeightsExtra = data;
  28621. break;
  28622. }
  28623. };
  28624. /**
  28625. * Associates the vertexData to the passed Mesh.
  28626. * Sets it as updatable or not (default `false`).
  28627. * Returns the VertexData.
  28628. */
  28629. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28630. this._applyTo(mesh, updatable);
  28631. return this;
  28632. };
  28633. /**
  28634. * Associates the vertexData to the passed Geometry.
  28635. * Sets it as updatable or not (default `false`).
  28636. * Returns the VertexData.
  28637. */
  28638. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28639. this._applyTo(geometry, updatable);
  28640. return this;
  28641. };
  28642. /**
  28643. * Updates the associated mesh.
  28644. * Returns the VertexData.
  28645. */
  28646. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28647. this._update(mesh);
  28648. return this;
  28649. };
  28650. /**
  28651. * Updates the associated geometry.
  28652. * Returns the VertexData.
  28653. */
  28654. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28655. this._update(geometry);
  28656. return this;
  28657. };
  28658. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28659. if (updatable === void 0) { updatable = false; }
  28660. if (this.positions) {
  28661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28662. }
  28663. if (this.normals) {
  28664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28665. }
  28666. if (this.tangents) {
  28667. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28668. }
  28669. if (this.uvs) {
  28670. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28671. }
  28672. if (this.uvs2) {
  28673. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28674. }
  28675. if (this.uvs3) {
  28676. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28677. }
  28678. if (this.uvs4) {
  28679. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28680. }
  28681. if (this.uvs5) {
  28682. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28683. }
  28684. if (this.uvs6) {
  28685. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28686. }
  28687. if (this.colors) {
  28688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28689. }
  28690. if (this.matricesIndices) {
  28691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28692. }
  28693. if (this.matricesWeights) {
  28694. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28695. }
  28696. if (this.matricesIndicesExtra) {
  28697. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28698. }
  28699. if (this.matricesWeightsExtra) {
  28700. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28701. }
  28702. if (this.indices) {
  28703. meshOrGeometry.setIndices(this.indices, null, updatable);
  28704. }
  28705. return this;
  28706. };
  28707. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28708. if (this.positions) {
  28709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28710. }
  28711. if (this.normals) {
  28712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28713. }
  28714. if (this.tangents) {
  28715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28716. }
  28717. if (this.uvs) {
  28718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28719. }
  28720. if (this.uvs2) {
  28721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28722. }
  28723. if (this.uvs3) {
  28724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28725. }
  28726. if (this.uvs4) {
  28727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28728. }
  28729. if (this.uvs5) {
  28730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28731. }
  28732. if (this.uvs6) {
  28733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28734. }
  28735. if (this.colors) {
  28736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28737. }
  28738. if (this.matricesIndices) {
  28739. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28740. }
  28741. if (this.matricesWeights) {
  28742. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28743. }
  28744. if (this.matricesIndicesExtra) {
  28745. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28746. }
  28747. if (this.matricesWeightsExtra) {
  28748. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28749. }
  28750. if (this.indices) {
  28751. meshOrGeometry.setIndices(this.indices, null);
  28752. }
  28753. return this;
  28754. };
  28755. /**
  28756. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28757. * Returns the VertexData.
  28758. */
  28759. VertexData.prototype.transform = function (matrix) {
  28760. var transformed = BABYLON.Vector3.Zero();
  28761. var index;
  28762. if (this.positions) {
  28763. var position = BABYLON.Vector3.Zero();
  28764. for (index = 0; index < this.positions.length; index += 3) {
  28765. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28766. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28767. this.positions[index] = transformed.x;
  28768. this.positions[index + 1] = transformed.y;
  28769. this.positions[index + 2] = transformed.z;
  28770. }
  28771. }
  28772. if (this.normals) {
  28773. var normal = BABYLON.Vector3.Zero();
  28774. for (index = 0; index < this.normals.length; index += 3) {
  28775. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28776. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28777. this.normals[index] = transformed.x;
  28778. this.normals[index + 1] = transformed.y;
  28779. this.normals[index + 2] = transformed.z;
  28780. }
  28781. }
  28782. if (this.tangents) {
  28783. var tangent = BABYLON.Vector4.Zero();
  28784. var tangentTransformed = BABYLON.Vector4.Zero();
  28785. for (index = 0; index < this.tangents.length; index += 4) {
  28786. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28787. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28788. this.tangents[index] = tangentTransformed.x;
  28789. this.tangents[index + 1] = tangentTransformed.y;
  28790. this.tangents[index + 2] = tangentTransformed.z;
  28791. this.tangents[index + 3] = tangentTransformed.w;
  28792. }
  28793. }
  28794. return this;
  28795. };
  28796. /**
  28797. * Merges the passed VertexData into the current one.
  28798. * Returns the modified VertexData.
  28799. */
  28800. VertexData.prototype.merge = function (other, options) {
  28801. options = options || {};
  28802. if (other.indices) {
  28803. if (!this.indices) {
  28804. this.indices = [];
  28805. }
  28806. var offset = this.positions ? this.positions.length / 3 : 0;
  28807. for (var index = 0; index < other.indices.length; index++) {
  28808. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28809. this.indices.push(other.indices[index] + offset);
  28810. }
  28811. }
  28812. this.positions = this._mergeElement(this.positions, other.positions);
  28813. if (!this.positions) {
  28814. return this;
  28815. }
  28816. var count = this.positions.length / 3;
  28817. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28818. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28819. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28820. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28821. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28822. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28823. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28824. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28825. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  28826. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28827. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28828. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28829. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28830. return this;
  28831. };
  28832. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  28833. if (length === void 0) { length = 0; }
  28834. if (defaultValue === void 0) { defaultValue = 0; }
  28835. if (!other && !source) {
  28836. return null;
  28837. }
  28838. if (!other) {
  28839. var padding = new Float32Array(source.length);
  28840. padding.fill(defaultValue);
  28841. return this._mergeElement(source, padding, length);
  28842. }
  28843. if (!source) {
  28844. if (length === 0 || length === other.length) {
  28845. return other;
  28846. }
  28847. var padding = new Float32Array(length - other.length);
  28848. padding.fill(defaultValue);
  28849. return this._mergeElement(padding, other, length);
  28850. }
  28851. var len = other.length + source.length;
  28852. var isSrcTypedArray = source instanceof Float32Array;
  28853. var isOthTypedArray = other instanceof Float32Array;
  28854. // use non-loop method when the source is Float32Array
  28855. if (isSrcTypedArray) {
  28856. var ret32 = new Float32Array(len);
  28857. ret32.set(source);
  28858. ret32.set(other, source.length);
  28859. return ret32;
  28860. // source is number[], when other is also use concat
  28861. }
  28862. else if (!isOthTypedArray) {
  28863. return source.concat(other);
  28864. // source is a number[], but other is a Float32Array, loop required
  28865. }
  28866. else {
  28867. var ret = source.slice(0); // copy source to a separate array
  28868. for (var i = 0, len = other.length; i < len; i++) {
  28869. ret.push(other[i]);
  28870. }
  28871. return ret;
  28872. }
  28873. };
  28874. /**
  28875. * Serializes the VertexData.
  28876. * Returns a serialized object.
  28877. */
  28878. VertexData.prototype.serialize = function () {
  28879. var serializationObject = this.serialize();
  28880. if (this.positions) {
  28881. serializationObject.positions = this.positions;
  28882. }
  28883. if (this.normals) {
  28884. serializationObject.normals = this.normals;
  28885. }
  28886. if (this.tangents) {
  28887. serializationObject.tangents = this.tangents;
  28888. }
  28889. if (this.uvs) {
  28890. serializationObject.uvs = this.uvs;
  28891. }
  28892. if (this.uvs2) {
  28893. serializationObject.uvs2 = this.uvs2;
  28894. }
  28895. if (this.uvs3) {
  28896. serializationObject.uvs3 = this.uvs3;
  28897. }
  28898. if (this.uvs4) {
  28899. serializationObject.uvs4 = this.uvs4;
  28900. }
  28901. if (this.uvs5) {
  28902. serializationObject.uvs5 = this.uvs5;
  28903. }
  28904. if (this.uvs6) {
  28905. serializationObject.uvs6 = this.uvs6;
  28906. }
  28907. if (this.colors) {
  28908. serializationObject.colors = this.colors;
  28909. }
  28910. if (this.matricesIndices) {
  28911. serializationObject.matricesIndices = this.matricesIndices;
  28912. serializationObject.matricesIndices._isExpanded = true;
  28913. }
  28914. if (this.matricesWeights) {
  28915. serializationObject.matricesWeights = this.matricesWeights;
  28916. }
  28917. if (this.matricesIndicesExtra) {
  28918. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28919. serializationObject.matricesIndicesExtra._isExpanded = true;
  28920. }
  28921. if (this.matricesWeightsExtra) {
  28922. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28923. }
  28924. serializationObject.indices = this.indices;
  28925. return serializationObject;
  28926. };
  28927. // Statics
  28928. /**
  28929. * Returns the object VertexData associated to the passed mesh.
  28930. */
  28931. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28932. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28933. };
  28934. /**
  28935. * Returns the object VertexData associated to the passed geometry.
  28936. */
  28937. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28938. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28939. };
  28940. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28941. var result = new VertexData();
  28942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28943. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28944. }
  28945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28946. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28947. }
  28948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28949. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28950. }
  28951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28952. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28953. }
  28954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28955. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28956. }
  28957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28958. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28959. }
  28960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28961. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28962. }
  28963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28964. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28965. }
  28966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28967. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28968. }
  28969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28970. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28971. }
  28972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28973. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28974. }
  28975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28976. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28977. }
  28978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28979. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28980. }
  28981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28982. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28983. }
  28984. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28985. return result;
  28986. };
  28987. /**
  28988. * Creates the vertexData of the Ribbon.
  28989. */
  28990. VertexData.CreateRibbon = function (options) {
  28991. var pathArray = options.pathArray;
  28992. var closeArray = options.closeArray || false;
  28993. var closePath = options.closePath || false;
  28994. var invertUV = options.invertUV || false;
  28995. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28996. var offset = options.offset || defaultOffset;
  28997. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28998. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28999. var customUV = options.uvs;
  29000. var customColors = options.colors;
  29001. var positions = [];
  29002. var indices = [];
  29003. var normals = [];
  29004. var uvs = [];
  29005. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29006. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29007. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29008. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29009. var minlg; // minimal length among all paths from pathArray
  29010. var lg = []; // array of path lengths : nb of vertex per path
  29011. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29012. var p; // path iterator
  29013. var i; // point iterator
  29014. var j; // point iterator
  29015. // if single path in pathArray
  29016. if (pathArray.length < 2) {
  29017. var ar1 = [];
  29018. var ar2 = [];
  29019. for (i = 0; i < pathArray[0].length - offset; i++) {
  29020. ar1.push(pathArray[0][i]);
  29021. ar2.push(pathArray[0][i + offset]);
  29022. }
  29023. pathArray = [ar1, ar2];
  29024. }
  29025. // positions and horizontal distances (u)
  29026. var idc = 0;
  29027. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29028. var path;
  29029. var l;
  29030. minlg = pathArray[0].length;
  29031. var vectlg;
  29032. var dist;
  29033. for (p = 0; p < pathArray.length; p++) {
  29034. uTotalDistance[p] = 0;
  29035. us[p] = [0];
  29036. path = pathArray[p];
  29037. l = path.length;
  29038. minlg = (minlg < l) ? minlg : l;
  29039. j = 0;
  29040. while (j < l) {
  29041. positions.push(path[j].x, path[j].y, path[j].z);
  29042. if (j > 0) {
  29043. vectlg = path[j].subtract(path[j - 1]).length();
  29044. dist = vectlg + uTotalDistance[p];
  29045. us[p].push(dist);
  29046. uTotalDistance[p] = dist;
  29047. }
  29048. j++;
  29049. }
  29050. if (closePath) {
  29051. j--;
  29052. positions.push(path[0].x, path[0].y, path[0].z);
  29053. vectlg = path[j].subtract(path[0]).length();
  29054. dist = vectlg + uTotalDistance[p];
  29055. us[p].push(dist);
  29056. uTotalDistance[p] = dist;
  29057. }
  29058. lg[p] = l + closePathCorr;
  29059. idx[p] = idc;
  29060. idc += (l + closePathCorr);
  29061. }
  29062. // vertical distances (v)
  29063. var path1;
  29064. var path2;
  29065. var vertex1 = null;
  29066. var vertex2 = null;
  29067. for (i = 0; i < minlg + closePathCorr; i++) {
  29068. vTotalDistance[i] = 0;
  29069. vs[i] = [0];
  29070. for (p = 0; p < pathArray.length - 1; p++) {
  29071. path1 = pathArray[p];
  29072. path2 = pathArray[p + 1];
  29073. if (i === minlg) {
  29074. vertex1 = path1[0];
  29075. vertex2 = path2[0];
  29076. }
  29077. else {
  29078. vertex1 = path1[i];
  29079. vertex2 = path2[i];
  29080. }
  29081. vectlg = vertex2.subtract(vertex1).length();
  29082. dist = vectlg + vTotalDistance[i];
  29083. vs[i].push(dist);
  29084. vTotalDistance[i] = dist;
  29085. }
  29086. if (closeArray && vertex2 && vertex1) {
  29087. path1 = pathArray[p];
  29088. path2 = pathArray[0];
  29089. if (i === minlg) {
  29090. vertex2 = path2[0];
  29091. }
  29092. vectlg = vertex2.subtract(vertex1).length();
  29093. dist = vectlg + vTotalDistance[i];
  29094. vTotalDistance[i] = dist;
  29095. }
  29096. }
  29097. // uvs
  29098. var u;
  29099. var v;
  29100. if (customUV) {
  29101. for (p = 0; p < customUV.length; p++) {
  29102. uvs.push(customUV[p].x, customUV[p].y);
  29103. }
  29104. }
  29105. else {
  29106. for (p = 0; p < pathArray.length; p++) {
  29107. for (i = 0; i < minlg + closePathCorr; i++) {
  29108. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29109. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29110. if (invertUV) {
  29111. uvs.push(v, u);
  29112. }
  29113. else {
  29114. uvs.push(u, v);
  29115. }
  29116. }
  29117. }
  29118. }
  29119. // indices
  29120. p = 0; // path index
  29121. var pi = 0; // positions array index
  29122. var l1 = lg[p] - 1; // path1 length
  29123. var l2 = lg[p + 1] - 1; // path2 length
  29124. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29125. var shft = idx[1] - idx[0]; // shift
  29126. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29127. while (pi <= min && p < path1nb) {
  29128. // 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
  29129. indices.push(pi, pi + shft, pi + 1);
  29130. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29131. pi += 1;
  29132. if (pi === min) {
  29133. p++;
  29134. if (p === lg.length - 1) {
  29135. shft = idx[0] - idx[p];
  29136. l1 = lg[p] - 1;
  29137. l2 = lg[0] - 1;
  29138. }
  29139. else {
  29140. shft = idx[p + 1] - idx[p];
  29141. l1 = lg[p] - 1;
  29142. l2 = lg[p + 1] - 1;
  29143. }
  29144. pi = idx[p];
  29145. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29146. }
  29147. }
  29148. // normals
  29149. VertexData.ComputeNormals(positions, indices, normals);
  29150. if (closePath) {
  29151. var indexFirst = 0;
  29152. var indexLast = 0;
  29153. for (p = 0; p < pathArray.length; p++) {
  29154. indexFirst = idx[p] * 3;
  29155. if (p + 1 < pathArray.length) {
  29156. indexLast = (idx[p + 1] - 1) * 3;
  29157. }
  29158. else {
  29159. indexLast = normals.length - 3;
  29160. }
  29161. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29162. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29163. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29164. normals[indexLast] = normals[indexFirst];
  29165. normals[indexLast + 1] = normals[indexFirst + 1];
  29166. normals[indexLast + 2] = normals[indexFirst + 2];
  29167. }
  29168. }
  29169. // sides
  29170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29171. // Colors
  29172. var colors = null;
  29173. if (customColors) {
  29174. colors = new Float32Array(customColors.length * 4);
  29175. for (var c = 0; c < customColors.length; c++) {
  29176. colors[c * 4] = customColors[c].r;
  29177. colors[c * 4 + 1] = customColors[c].g;
  29178. colors[c * 4 + 2] = customColors[c].b;
  29179. colors[c * 4 + 3] = customColors[c].a;
  29180. }
  29181. }
  29182. // Result
  29183. var vertexData = new VertexData();
  29184. var positions32 = new Float32Array(positions);
  29185. var normals32 = new Float32Array(normals);
  29186. var uvs32 = new Float32Array(uvs);
  29187. vertexData.indices = indices;
  29188. vertexData.positions = positions32;
  29189. vertexData.normals = normals32;
  29190. vertexData.uvs = uvs32;
  29191. if (colors) {
  29192. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29193. }
  29194. if (closePath) {
  29195. vertexData._idx = idx;
  29196. }
  29197. return vertexData;
  29198. };
  29199. /**
  29200. * Creates the VertexData of the Box.
  29201. */
  29202. VertexData.CreateBox = function (options) {
  29203. var normalsSource = [
  29204. new BABYLON.Vector3(0, 0, 1),
  29205. new BABYLON.Vector3(0, 0, -1),
  29206. new BABYLON.Vector3(1, 0, 0),
  29207. new BABYLON.Vector3(-1, 0, 0),
  29208. new BABYLON.Vector3(0, 1, 0),
  29209. new BABYLON.Vector3(0, -1, 0)
  29210. ];
  29211. var indices = [];
  29212. var positions = [];
  29213. var normals = [];
  29214. var uvs = [];
  29215. var width = options.width || options.size || 1;
  29216. var height = options.height || options.size || 1;
  29217. var depth = options.depth || options.size || 1;
  29218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29219. var faceUV = options.faceUV || new Array(6);
  29220. var faceColors = options.faceColors;
  29221. var colors = [];
  29222. // default face colors and UV if undefined
  29223. for (var f = 0; f < 6; f++) {
  29224. if (faceUV[f] === undefined) {
  29225. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29226. }
  29227. if (faceColors && faceColors[f] === undefined) {
  29228. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29229. }
  29230. }
  29231. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29232. // Create each face in turn.
  29233. for (var index = 0; index < normalsSource.length; index++) {
  29234. var normal = normalsSource[index];
  29235. // Get two vectors perpendicular to the face normal and to each other.
  29236. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29237. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29238. // Six indices (two triangles) per face.
  29239. var verticesLength = positions.length / 3;
  29240. indices.push(verticesLength);
  29241. indices.push(verticesLength + 1);
  29242. indices.push(verticesLength + 2);
  29243. indices.push(verticesLength);
  29244. indices.push(verticesLength + 2);
  29245. indices.push(verticesLength + 3);
  29246. // Four vertices per face.
  29247. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29248. positions.push(vertex.x, vertex.y, vertex.z);
  29249. normals.push(normal.x, normal.y, normal.z);
  29250. uvs.push(faceUV[index].z, faceUV[index].w);
  29251. if (faceColors) {
  29252. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29253. }
  29254. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29255. positions.push(vertex.x, vertex.y, vertex.z);
  29256. normals.push(normal.x, normal.y, normal.z);
  29257. uvs.push(faceUV[index].x, faceUV[index].w);
  29258. if (faceColors) {
  29259. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29260. }
  29261. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29262. positions.push(vertex.x, vertex.y, vertex.z);
  29263. normals.push(normal.x, normal.y, normal.z);
  29264. uvs.push(faceUV[index].x, faceUV[index].y);
  29265. if (faceColors) {
  29266. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29267. }
  29268. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29269. positions.push(vertex.x, vertex.y, vertex.z);
  29270. normals.push(normal.x, normal.y, normal.z);
  29271. uvs.push(faceUV[index].z, faceUV[index].y);
  29272. if (faceColors) {
  29273. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29274. }
  29275. }
  29276. // sides
  29277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29278. // Result
  29279. var vertexData = new VertexData();
  29280. vertexData.indices = indices;
  29281. vertexData.positions = positions;
  29282. vertexData.normals = normals;
  29283. vertexData.uvs = uvs;
  29284. if (faceColors) {
  29285. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29286. vertexData.colors = totalColors;
  29287. }
  29288. return vertexData;
  29289. };
  29290. /**
  29291. * Creates the VertexData of the Sphere.
  29292. */
  29293. VertexData.CreateSphere = function (options) {
  29294. var segments = options.segments || 32;
  29295. var diameterX = options.diameterX || options.diameter || 1;
  29296. var diameterY = options.diameterY || options.diameter || 1;
  29297. var diameterZ = options.diameterZ || options.diameter || 1;
  29298. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29299. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29300. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29301. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29302. var totalZRotationSteps = 2 + segments;
  29303. var totalYRotationSteps = 2 * totalZRotationSteps;
  29304. var indices = [];
  29305. var positions = [];
  29306. var normals = [];
  29307. var uvs = [];
  29308. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29309. var normalizedZ = zRotationStep / totalZRotationSteps;
  29310. var angleZ = normalizedZ * Math.PI * slice;
  29311. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29312. var normalizedY = yRotationStep / totalYRotationSteps;
  29313. var angleY = normalizedY * Math.PI * 2 * arc;
  29314. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29315. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29316. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29317. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29318. var vertex = complete.multiply(radius);
  29319. var normal = complete.divide(radius).normalize();
  29320. positions.push(vertex.x, vertex.y, vertex.z);
  29321. normals.push(normal.x, normal.y, normal.z);
  29322. uvs.push(normalizedY, normalizedZ);
  29323. }
  29324. if (zRotationStep > 0) {
  29325. var verticesCount = positions.length / 3;
  29326. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29327. indices.push((firstIndex));
  29328. indices.push((firstIndex + 1));
  29329. indices.push(firstIndex + totalYRotationSteps + 1);
  29330. indices.push((firstIndex + totalYRotationSteps + 1));
  29331. indices.push((firstIndex + 1));
  29332. indices.push((firstIndex + totalYRotationSteps + 2));
  29333. }
  29334. }
  29335. }
  29336. // Sides
  29337. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29338. // Result
  29339. var vertexData = new VertexData();
  29340. vertexData.indices = indices;
  29341. vertexData.positions = positions;
  29342. vertexData.normals = normals;
  29343. vertexData.uvs = uvs;
  29344. return vertexData;
  29345. };
  29346. /**
  29347. * Creates the VertexData of the Cylinder or Cone.
  29348. */
  29349. VertexData.CreateCylinder = function (options) {
  29350. var height = options.height || 2;
  29351. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29352. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29353. var tessellation = options.tessellation || 24;
  29354. var subdivisions = options.subdivisions || 1;
  29355. var hasRings = options.hasRings ? true : false;
  29356. var enclose = options.enclose ? true : false;
  29357. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29358. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29359. var faceUV = options.faceUV || new Array(3);
  29360. var faceColors = options.faceColors;
  29361. // default face colors and UV if undefined
  29362. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29363. var ringNb = (hasRings) ? subdivisions : 1;
  29364. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29365. var f;
  29366. for (f = 0; f < surfaceNb; f++) {
  29367. if (faceColors && faceColors[f] === undefined) {
  29368. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29369. }
  29370. }
  29371. for (f = 0; f < surfaceNb; f++) {
  29372. if (faceUV && faceUV[f] === undefined) {
  29373. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29374. }
  29375. }
  29376. var indices = new Array();
  29377. var positions = new Array();
  29378. var normals = new Array();
  29379. var uvs = new Array();
  29380. var colors = new Array();
  29381. var angle_step = Math.PI * 2 * arc / tessellation;
  29382. var angle;
  29383. var h;
  29384. var radius;
  29385. var tan = (diameterBottom - diameterTop) / 2 / height;
  29386. var ringVertex = BABYLON.Vector3.Zero();
  29387. var ringNormal = BABYLON.Vector3.Zero();
  29388. var ringFirstVertex = BABYLON.Vector3.Zero();
  29389. var ringFirstNormal = BABYLON.Vector3.Zero();
  29390. var quadNormal = BABYLON.Vector3.Zero();
  29391. var Y = BABYLON.Axis.Y;
  29392. // positions, normals, uvs
  29393. var i;
  29394. var j;
  29395. var r;
  29396. var ringIdx = 1;
  29397. var s = 1; // surface index
  29398. var cs = 0;
  29399. var v = 0;
  29400. for (i = 0; i <= subdivisions; i++) {
  29401. h = i / subdivisions;
  29402. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29403. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29404. for (r = 0; r < ringIdx; r++) {
  29405. if (hasRings) {
  29406. s += r;
  29407. }
  29408. if (enclose) {
  29409. s += 2 * r;
  29410. }
  29411. for (j = 0; j <= tessellation; j++) {
  29412. angle = j * angle_step;
  29413. // position
  29414. ringVertex.x = Math.cos(-angle) * radius;
  29415. ringVertex.y = -height / 2 + h * height;
  29416. ringVertex.z = Math.sin(-angle) * radius;
  29417. // normal
  29418. if (diameterTop === 0 && i === subdivisions) {
  29419. // if no top cap, reuse former normals
  29420. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29421. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29422. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29423. }
  29424. else {
  29425. ringNormal.x = ringVertex.x;
  29426. ringNormal.z = ringVertex.z;
  29427. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29428. ringNormal.normalize();
  29429. }
  29430. // keep first ring vertex values for enclose
  29431. if (j === 0) {
  29432. ringFirstVertex.copyFrom(ringVertex);
  29433. ringFirstNormal.copyFrom(ringNormal);
  29434. }
  29435. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29436. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29437. if (hasRings) {
  29438. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29439. }
  29440. else {
  29441. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29442. }
  29443. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29444. if (faceColors) {
  29445. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29446. }
  29447. }
  29448. // if enclose, add four vertices and their dedicated normals
  29449. if (arc !== 1 && enclose) {
  29450. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29451. positions.push(0, ringVertex.y, 0);
  29452. positions.push(0, ringVertex.y, 0);
  29453. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29454. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29455. quadNormal.normalize();
  29456. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29457. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29458. quadNormal.normalize();
  29459. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29460. if (hasRings) {
  29461. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29462. }
  29463. else {
  29464. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29465. }
  29466. uvs.push(faceUV[s + 1].x, v);
  29467. uvs.push(faceUV[s + 1].z, v);
  29468. if (hasRings) {
  29469. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29470. }
  29471. else {
  29472. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29473. }
  29474. uvs.push(faceUV[s + 2].x, v);
  29475. uvs.push(faceUV[s + 2].z, v);
  29476. if (faceColors) {
  29477. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29478. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29479. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29480. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29481. }
  29482. }
  29483. if (cs !== s) {
  29484. cs = s;
  29485. }
  29486. }
  29487. }
  29488. // indices
  29489. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29490. var s;
  29491. i = 0;
  29492. for (s = 0; s < subdivisions; s++) {
  29493. var i0 = 0;
  29494. var i1 = 0;
  29495. var i2 = 0;
  29496. var i3 = 0;
  29497. for (j = 0; j < tessellation; j++) {
  29498. i0 = i * (e + 1) + j;
  29499. i1 = (i + 1) * (e + 1) + j;
  29500. i2 = i * (e + 1) + (j + 1);
  29501. i3 = (i + 1) * (e + 1) + (j + 1);
  29502. indices.push(i0, i1, i2);
  29503. indices.push(i3, i2, i1);
  29504. }
  29505. if (arc !== 1 && enclose) {
  29506. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29507. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29508. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29509. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29510. }
  29511. i = (hasRings) ? (i + 2) : (i + 1);
  29512. }
  29513. // Caps
  29514. var createCylinderCap = function (isTop) {
  29515. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29516. if (radius === 0) {
  29517. return;
  29518. }
  29519. // Cap positions, normals & uvs
  29520. var angle;
  29521. var circleVector;
  29522. var i;
  29523. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29524. var c = null;
  29525. if (faceColors) {
  29526. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29527. }
  29528. // cap center
  29529. var vbase = positions.length / 3;
  29530. var offset = isTop ? height / 2 : -height / 2;
  29531. var center = new BABYLON.Vector3(0, offset, 0);
  29532. positions.push(center.x, center.y, center.z);
  29533. normals.push(0, isTop ? 1 : -1, 0);
  29534. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29535. if (c) {
  29536. colors.push(c.r, c.g, c.b, c.a);
  29537. }
  29538. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29539. for (i = 0; i <= tessellation; i++) {
  29540. angle = Math.PI * 2 * i * arc / tessellation;
  29541. var cos = Math.cos(-angle);
  29542. var sin = Math.sin(-angle);
  29543. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29544. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29545. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29546. normals.push(0, isTop ? 1 : -1, 0);
  29547. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29548. if (c) {
  29549. colors.push(c.r, c.g, c.b, c.a);
  29550. }
  29551. }
  29552. // Cap indices
  29553. for (i = 0; i < tessellation; i++) {
  29554. if (!isTop) {
  29555. indices.push(vbase);
  29556. indices.push(vbase + (i + 1));
  29557. indices.push(vbase + (i + 2));
  29558. }
  29559. else {
  29560. indices.push(vbase);
  29561. indices.push(vbase + (i + 2));
  29562. indices.push(vbase + (i + 1));
  29563. }
  29564. }
  29565. };
  29566. // add caps to geometry
  29567. createCylinderCap(false);
  29568. createCylinderCap(true);
  29569. // Sides
  29570. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29571. var vertexData = new VertexData();
  29572. vertexData.indices = indices;
  29573. vertexData.positions = positions;
  29574. vertexData.normals = normals;
  29575. vertexData.uvs = uvs;
  29576. if (faceColors) {
  29577. vertexData.colors = colors;
  29578. }
  29579. return vertexData;
  29580. };
  29581. /**
  29582. * Creates the VertexData of the Torus.
  29583. */
  29584. VertexData.CreateTorus = function (options) {
  29585. var indices = [];
  29586. var positions = [];
  29587. var normals = [];
  29588. var uvs = [];
  29589. var diameter = options.diameter || 1;
  29590. var thickness = options.thickness || 0.5;
  29591. var tessellation = options.tessellation || 16;
  29592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29593. var stride = tessellation + 1;
  29594. for (var i = 0; i <= tessellation; i++) {
  29595. var u = i / tessellation;
  29596. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29597. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29598. for (var j = 0; j <= tessellation; j++) {
  29599. var v = 1 - j / tessellation;
  29600. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29601. var dx = Math.cos(innerAngle);
  29602. var dy = Math.sin(innerAngle);
  29603. // Create a vertex.
  29604. var normal = new BABYLON.Vector3(dx, dy, 0);
  29605. var position = normal.scale(thickness / 2);
  29606. var textureCoordinate = new BABYLON.Vector2(u, v);
  29607. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29608. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29609. positions.push(position.x, position.y, position.z);
  29610. normals.push(normal.x, normal.y, normal.z);
  29611. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29612. // And create indices for two triangles.
  29613. var nextI = (i + 1) % stride;
  29614. var nextJ = (j + 1) % stride;
  29615. indices.push(i * stride + j);
  29616. indices.push(i * stride + nextJ);
  29617. indices.push(nextI * stride + j);
  29618. indices.push(i * stride + nextJ);
  29619. indices.push(nextI * stride + nextJ);
  29620. indices.push(nextI * stride + j);
  29621. }
  29622. }
  29623. // Sides
  29624. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29625. // Result
  29626. var vertexData = new VertexData();
  29627. vertexData.indices = indices;
  29628. vertexData.positions = positions;
  29629. vertexData.normals = normals;
  29630. vertexData.uvs = uvs;
  29631. return vertexData;
  29632. };
  29633. /**
  29634. * Creates the VertexData of the LineSystem.
  29635. */
  29636. VertexData.CreateLineSystem = function (options) {
  29637. var indices = [];
  29638. var positions = [];
  29639. var lines = options.lines;
  29640. var colors = options.colors;
  29641. var vertexColors = [];
  29642. var idx = 0;
  29643. for (var l = 0; l < lines.length; l++) {
  29644. var points = lines[l];
  29645. for (var index = 0; index < points.length; index++) {
  29646. positions.push(points[index].x, points[index].y, points[index].z);
  29647. if (colors) {
  29648. var color = colors[l];
  29649. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29650. }
  29651. if (index > 0) {
  29652. indices.push(idx - 1);
  29653. indices.push(idx);
  29654. }
  29655. idx++;
  29656. }
  29657. }
  29658. var vertexData = new VertexData();
  29659. vertexData.indices = indices;
  29660. vertexData.positions = positions;
  29661. if (colors) {
  29662. vertexData.colors = vertexColors;
  29663. }
  29664. return vertexData;
  29665. };
  29666. /**
  29667. * Create the VertexData of the DashedLines.
  29668. */
  29669. VertexData.CreateDashedLines = function (options) {
  29670. var dashSize = options.dashSize || 3;
  29671. var gapSize = options.gapSize || 1;
  29672. var dashNb = options.dashNb || 200;
  29673. var points = options.points;
  29674. var positions = new Array();
  29675. var indices = new Array();
  29676. var curvect = BABYLON.Vector3.Zero();
  29677. var lg = 0;
  29678. var nb = 0;
  29679. var shft = 0;
  29680. var dashshft = 0;
  29681. var curshft = 0;
  29682. var idx = 0;
  29683. var i = 0;
  29684. for (i = 0; i < points.length - 1; i++) {
  29685. points[i + 1].subtractToRef(points[i], curvect);
  29686. lg += curvect.length();
  29687. }
  29688. shft = lg / dashNb;
  29689. dashshft = dashSize * shft / (dashSize + gapSize);
  29690. for (i = 0; i < points.length - 1; i++) {
  29691. points[i + 1].subtractToRef(points[i], curvect);
  29692. nb = Math.floor(curvect.length() / shft);
  29693. curvect.normalize();
  29694. for (var j = 0; j < nb; j++) {
  29695. curshft = shft * j;
  29696. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29697. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29698. indices.push(idx, idx + 1);
  29699. idx += 2;
  29700. }
  29701. }
  29702. // Result
  29703. var vertexData = new VertexData();
  29704. vertexData.positions = positions;
  29705. vertexData.indices = indices;
  29706. return vertexData;
  29707. };
  29708. /**
  29709. * Creates the VertexData of the Ground.
  29710. */
  29711. VertexData.CreateGround = function (options) {
  29712. var indices = [];
  29713. var positions = [];
  29714. var normals = [];
  29715. var uvs = [];
  29716. var row, col;
  29717. var width = options.width || 1;
  29718. var height = options.height || 1;
  29719. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29720. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29721. for (row = 0; row <= subdivisionsY; row++) {
  29722. for (col = 0; col <= subdivisionsX; col++) {
  29723. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29724. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29725. positions.push(position.x, position.y, position.z);
  29726. normals.push(normal.x, normal.y, normal.z);
  29727. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29728. }
  29729. }
  29730. for (row = 0; row < subdivisionsY; row++) {
  29731. for (col = 0; col < subdivisionsX; col++) {
  29732. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29733. indices.push(col + 1 + row * (subdivisionsX + 1));
  29734. indices.push(col + row * (subdivisionsX + 1));
  29735. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29736. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29737. indices.push(col + row * (subdivisionsX + 1));
  29738. }
  29739. }
  29740. // Result
  29741. var vertexData = new VertexData();
  29742. vertexData.indices = indices;
  29743. vertexData.positions = positions;
  29744. vertexData.normals = normals;
  29745. vertexData.uvs = uvs;
  29746. return vertexData;
  29747. };
  29748. /**
  29749. * Creates the VertexData of the TiledGround.
  29750. */
  29751. VertexData.CreateTiledGround = function (options) {
  29752. var xmin = options.xmin || -1.0;
  29753. var zmin = options.zmin || -1.0;
  29754. var xmax = options.xmax || 1.0;
  29755. var zmax = options.zmax || 1.0;
  29756. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29757. var precision = options.precision || { w: 1, h: 1 };
  29758. var indices = new Array();
  29759. var positions = new Array();
  29760. var normals = new Array();
  29761. var uvs = new Array();
  29762. var row, col, tileRow, tileCol;
  29763. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29764. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29765. precision.w = (precision.w < 1) ? 1 : precision.w;
  29766. precision.h = (precision.h < 1) ? 1 : precision.h;
  29767. var tileSize = {
  29768. 'w': (xmax - xmin) / subdivisions.w,
  29769. 'h': (zmax - zmin) / subdivisions.h
  29770. };
  29771. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29772. // Indices
  29773. var base = positions.length / 3;
  29774. var rowLength = precision.w + 1;
  29775. for (row = 0; row < precision.h; row++) {
  29776. for (col = 0; col < precision.w; col++) {
  29777. var square = [
  29778. base + col + row * rowLength,
  29779. base + (col + 1) + row * rowLength,
  29780. base + (col + 1) + (row + 1) * rowLength,
  29781. base + col + (row + 1) * rowLength
  29782. ];
  29783. indices.push(square[1]);
  29784. indices.push(square[2]);
  29785. indices.push(square[3]);
  29786. indices.push(square[0]);
  29787. indices.push(square[1]);
  29788. indices.push(square[3]);
  29789. }
  29790. }
  29791. // Position, normals and uvs
  29792. var position = BABYLON.Vector3.Zero();
  29793. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29794. for (row = 0; row <= precision.h; row++) {
  29795. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29796. for (col = 0; col <= precision.w; col++) {
  29797. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29798. position.y = 0;
  29799. positions.push(position.x, position.y, position.z);
  29800. normals.push(normal.x, normal.y, normal.z);
  29801. uvs.push(col / precision.w, row / precision.h);
  29802. }
  29803. }
  29804. }
  29805. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29806. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29807. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29808. }
  29809. }
  29810. // Result
  29811. var vertexData = new VertexData();
  29812. vertexData.indices = indices;
  29813. vertexData.positions = positions;
  29814. vertexData.normals = normals;
  29815. vertexData.uvs = uvs;
  29816. return vertexData;
  29817. };
  29818. /**
  29819. * Creates the VertexData of the Ground designed from a heightmap.
  29820. */
  29821. VertexData.CreateGroundFromHeightMap = function (options) {
  29822. var indices = [];
  29823. var positions = [];
  29824. var normals = [];
  29825. var uvs = [];
  29826. var row, col;
  29827. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29828. // Vertices
  29829. for (row = 0; row <= options.subdivisions; row++) {
  29830. for (col = 0; col <= options.subdivisions; col++) {
  29831. 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));
  29832. // Compute height
  29833. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29834. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29835. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29836. var r = options.buffer[pos] / 255.0;
  29837. var g = options.buffer[pos + 1] / 255.0;
  29838. var b = options.buffer[pos + 2] / 255.0;
  29839. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29840. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29841. // Add vertex
  29842. positions.push(position.x, position.y, position.z);
  29843. normals.push(0, 0, 0);
  29844. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29845. }
  29846. }
  29847. // Indices
  29848. for (row = 0; row < options.subdivisions; row++) {
  29849. for (col = 0; col < options.subdivisions; col++) {
  29850. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29851. indices.push(col + 1 + row * (options.subdivisions + 1));
  29852. indices.push(col + row * (options.subdivisions + 1));
  29853. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29854. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29855. indices.push(col + row * (options.subdivisions + 1));
  29856. }
  29857. }
  29858. // Normals
  29859. VertexData.ComputeNormals(positions, indices, normals);
  29860. // Result
  29861. var vertexData = new VertexData();
  29862. vertexData.indices = indices;
  29863. vertexData.positions = positions;
  29864. vertexData.normals = normals;
  29865. vertexData.uvs = uvs;
  29866. return vertexData;
  29867. };
  29868. /**
  29869. * Creates the VertexData of the Plane.
  29870. */
  29871. VertexData.CreatePlane = function (options) {
  29872. var indices = [];
  29873. var positions = [];
  29874. var normals = [];
  29875. var uvs = [];
  29876. var width = options.width || options.size || 1;
  29877. var height = options.height || options.size || 1;
  29878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29879. // Vertices
  29880. var halfWidth = width / 2.0;
  29881. var halfHeight = height / 2.0;
  29882. positions.push(-halfWidth, -halfHeight, 0);
  29883. normals.push(0, 0, -1.0);
  29884. uvs.push(0.0, 0.0);
  29885. positions.push(halfWidth, -halfHeight, 0);
  29886. normals.push(0, 0, -1.0);
  29887. uvs.push(1.0, 0.0);
  29888. positions.push(halfWidth, halfHeight, 0);
  29889. normals.push(0, 0, -1.0);
  29890. uvs.push(1.0, 1.0);
  29891. positions.push(-halfWidth, halfHeight, 0);
  29892. normals.push(0, 0, -1.0);
  29893. uvs.push(0.0, 1.0);
  29894. // Indices
  29895. indices.push(0);
  29896. indices.push(1);
  29897. indices.push(2);
  29898. indices.push(0);
  29899. indices.push(2);
  29900. indices.push(3);
  29901. // Sides
  29902. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29903. // Result
  29904. var vertexData = new VertexData();
  29905. vertexData.indices = indices;
  29906. vertexData.positions = positions;
  29907. vertexData.normals = normals;
  29908. vertexData.uvs = uvs;
  29909. return vertexData;
  29910. };
  29911. /**
  29912. * Creates the VertexData of the Disc or regular Polygon.
  29913. */
  29914. VertexData.CreateDisc = function (options) {
  29915. var positions = new Array();
  29916. var indices = new Array();
  29917. var normals = new Array();
  29918. var uvs = new Array();
  29919. var radius = options.radius || 0.5;
  29920. var tessellation = options.tessellation || 64;
  29921. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29922. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29923. // positions and uvs
  29924. positions.push(0, 0, 0); // disc center first
  29925. uvs.push(0.5, 0.5);
  29926. var theta = Math.PI * 2 * arc;
  29927. var step = theta / tessellation;
  29928. for (var a = 0; a < theta; a += step) {
  29929. var x = Math.cos(a);
  29930. var y = Math.sin(a);
  29931. var u = (x + 1) / 2;
  29932. var v = (1 - y) / 2;
  29933. positions.push(radius * x, radius * y, 0);
  29934. uvs.push(u, v);
  29935. }
  29936. if (arc === 1) {
  29937. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29938. uvs.push(uvs[2], uvs[3]);
  29939. }
  29940. //indices
  29941. var vertexNb = positions.length / 3;
  29942. for (var i = 1; i < vertexNb - 1; i++) {
  29943. indices.push(i + 1, 0, i);
  29944. }
  29945. // result
  29946. VertexData.ComputeNormals(positions, indices, normals);
  29947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29948. var vertexData = new VertexData();
  29949. vertexData.indices = indices;
  29950. vertexData.positions = positions;
  29951. vertexData.normals = normals;
  29952. vertexData.uvs = uvs;
  29953. return vertexData;
  29954. };
  29955. /**
  29956. * Re-creates the VertexData of the Polygon for sideOrientation.
  29957. */
  29958. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29959. var faceUV = fUV || new Array(3);
  29960. var faceColors = fColors;
  29961. var colors = [];
  29962. // default face colors and UV if undefined
  29963. for (var f = 0; f < 3; f++) {
  29964. if (faceUV[f] === undefined) {
  29965. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29966. }
  29967. if (faceColors && faceColors[f] === undefined) {
  29968. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29969. }
  29970. }
  29971. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29972. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29973. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29974. var indices = polygon.getIndices();
  29975. // set face colours and textures
  29976. var idx = 0;
  29977. var face = 0;
  29978. for (var index = 0; index < normals.length; index += 3) {
  29979. //Edge Face no. 1
  29980. if (Math.abs(normals[index + 1]) < 0.001) {
  29981. face = 1;
  29982. }
  29983. //Top Face no. 0
  29984. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29985. face = 0;
  29986. }
  29987. //Bottom Face no. 2
  29988. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29989. face = 2;
  29990. }
  29991. idx = index / 3;
  29992. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29993. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29994. if (faceColors) {
  29995. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29996. }
  29997. }
  29998. // sides
  29999. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30000. // Result
  30001. var vertexData = new VertexData();
  30002. vertexData.indices = indices;
  30003. vertexData.positions = positions;
  30004. vertexData.normals = normals;
  30005. vertexData.uvs = uvs;
  30006. if (faceColors) {
  30007. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30008. vertexData.colors = totalColors;
  30009. }
  30010. return vertexData;
  30011. };
  30012. /**
  30013. * Creates the VertexData of the IcoSphere.
  30014. */
  30015. VertexData.CreateIcoSphere = function (options) {
  30016. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30017. var radius = options.radius || 1;
  30018. var flat = (options.flat === undefined) ? true : options.flat;
  30019. var subdivisions = options.subdivisions || 4;
  30020. var radiusX = options.radiusX || radius;
  30021. var radiusY = options.radiusY || radius;
  30022. var radiusZ = options.radiusZ || radius;
  30023. var t = (1 + Math.sqrt(5)) / 2;
  30024. // 12 vertex x,y,z
  30025. var ico_vertices = [
  30026. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30027. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30028. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30029. ];
  30030. // index of 3 vertex makes a face of icopshere
  30031. var ico_indices = [
  30032. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30033. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30034. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30035. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30036. ];
  30037. // vertex for uv have aliased position, not for UV
  30038. var vertices_unalias_id = [
  30039. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30040. // vertex alias
  30041. 0,
  30042. 2,
  30043. 3,
  30044. 3,
  30045. 3,
  30046. 4,
  30047. 7,
  30048. 8,
  30049. 9,
  30050. 9,
  30051. 10,
  30052. 11 // 23: B + 12
  30053. ];
  30054. // uv as integer step (not pixels !)
  30055. var ico_vertexuv = [
  30056. 5, 1, 3, 1, 6, 4, 0, 0,
  30057. 5, 3, 4, 2, 2, 2, 4, 0,
  30058. 2, 0, 1, 1, 6, 0, 6, 2,
  30059. // vertex alias (for same vertex on different faces)
  30060. 0, 4,
  30061. 3, 3,
  30062. 4, 4,
  30063. 3, 1,
  30064. 4, 2,
  30065. 4, 4,
  30066. 0, 2,
  30067. 1, 1,
  30068. 2, 2,
  30069. 3, 3,
  30070. 1, 3,
  30071. 2, 4 // 23: B + 12
  30072. ];
  30073. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30074. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30075. // First island of uv mapping
  30076. // v = 4h 3+ 2
  30077. // v = 3h 9+ 4
  30078. // v = 2h 9+ 5 B
  30079. // v = 1h 9 1 0
  30080. // v = 0h 3 8 7 A
  30081. // u = 0 1 2 3 4 5 6 *a
  30082. // Second island of uv mapping
  30083. // v = 4h 0+ B+ 4+
  30084. // v = 3h A+ 2+
  30085. // v = 2h 7+ 6 3+
  30086. // v = 1h 8+ 3+
  30087. // v = 0h
  30088. // u = 0 1 2 3 4 5 6 *a
  30089. // Face layout on texture UV mapping
  30090. // ============
  30091. // \ 4 /\ 16 / ======
  30092. // \ / \ / /\ 11 /
  30093. // \/ 7 \/ / \ /
  30094. // ======= / 10 \/
  30095. // /\ 17 /\ =======
  30096. // / \ / \ \ 15 /\
  30097. // / 8 \/ 12 \ \ / \
  30098. // ============ \/ 6 \
  30099. // \ 18 /\ ============
  30100. // \ / \ \ 5 /\ 0 /
  30101. // \/ 13 \ \ / \ /
  30102. // ======= \/ 1 \/
  30103. // =============
  30104. // /\ 19 /\ 2 /\
  30105. // / \ / \ / \
  30106. // / 14 \/ 9 \/ 3 \
  30107. // ===================
  30108. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30109. var ustep = 138 / 1024;
  30110. var vstep = 239 / 1024;
  30111. var uoffset = 60 / 1024;
  30112. var voffset = 26 / 1024;
  30113. // Second island should have margin, not to touch the first island
  30114. // avoid any borderline artefact in pixel rounding
  30115. var island_u_offset = -40 / 1024;
  30116. var island_v_offset = +20 / 1024;
  30117. // face is either island 0 or 1 :
  30118. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30119. var island = [
  30120. 0, 0, 0, 0, 1,
  30121. 0, 0, 1, 1, 0,
  30122. 0, 0, 1, 1, 0,
  30123. 0, 1, 1, 1, 0 // 15 - 19
  30124. ];
  30125. var indices = new Array();
  30126. var positions = new Array();
  30127. var normals = new Array();
  30128. var uvs = new Array();
  30129. var current_indice = 0;
  30130. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30131. var face_vertex_pos = new Array(3);
  30132. var face_vertex_uv = new Array(3);
  30133. var v012;
  30134. for (v012 = 0; v012 < 3; v012++) {
  30135. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30136. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30137. }
  30138. // create all with normals
  30139. for (var face = 0; face < 20; face++) {
  30140. // 3 vertex per face
  30141. for (v012 = 0; v012 < 3; v012++) {
  30142. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30143. var v_id = ico_indices[3 * face + v012];
  30144. // vertex have 3D position (x,y,z)
  30145. 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]);
  30146. // Normalize to get normal, then scale to radius
  30147. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30148. // uv Coordinates from vertex ID
  30149. 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);
  30150. }
  30151. // Subdivide the face (interpolate pos, norm, uv)
  30152. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30153. // - norm is linear interpolation of vertex corner normal
  30154. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30155. // - uv is linear interpolation
  30156. //
  30157. // Topology is as below for sub-divide by 2
  30158. // vertex shown as v0,v1,v2
  30159. // interp index is i1 to progress in range [v0,v1[
  30160. // interp index is i2 to progress in range [v0,v2[
  30161. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30162. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30163. //
  30164. //
  30165. // i2 v2
  30166. // ^ ^
  30167. // / / \
  30168. // / / \
  30169. // / / \
  30170. // / / (0,1) \
  30171. // / #---------\
  30172. // / / \ (0,0)'/ \
  30173. // / / \ / \
  30174. // / / \ / \
  30175. // / / (0,0) \ / (1,0) \
  30176. // / #---------#---------\
  30177. // v0 v1
  30178. //
  30179. // --------------------> i1
  30180. //
  30181. // interp of (i1,i2):
  30182. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30183. // along i1 : lerp(x0,x1, i1/(S-i2))
  30184. //
  30185. // centroid of triangle is needed to get help normal computation
  30186. // (c1,c2) are used for centroid location
  30187. var interp_vertex = function (i1, i2, c1, c2) {
  30188. // vertex is interpolated from
  30189. // - face_vertex_pos[0..2]
  30190. // - face_vertex_uv[0..2]
  30191. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30192. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30193. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30194. pos_interp.normalize();
  30195. var vertex_normal;
  30196. if (flat) {
  30197. // in flat mode, recalculate normal as face centroid normal
  30198. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30199. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30200. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30201. }
  30202. else {
  30203. // in smooth mode, recalculate normal from each single vertex position
  30204. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30205. }
  30206. // Vertex normal need correction due to X,Y,Z radius scaling
  30207. vertex_normal.x /= radiusX;
  30208. vertex_normal.y /= radiusY;
  30209. vertex_normal.z /= radiusZ;
  30210. vertex_normal.normalize();
  30211. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30212. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30213. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30214. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30215. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30216. uvs.push(uv_interp.x, uv_interp.y);
  30217. // push each vertex has member of a face
  30218. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30219. indices.push(current_indice);
  30220. current_indice++;
  30221. };
  30222. for (var i2 = 0; i2 < subdivisions; i2++) {
  30223. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30224. // face : (i1,i2) for /\ :
  30225. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30226. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30227. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30228. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30229. if (i1 + i2 + 1 < subdivisions) {
  30230. // face : (i1,i2)' for \/ :
  30231. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30232. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30233. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30234. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30235. }
  30236. }
  30237. }
  30238. }
  30239. // Sides
  30240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30241. // Result
  30242. var vertexData = new VertexData();
  30243. vertexData.indices = indices;
  30244. vertexData.positions = positions;
  30245. vertexData.normals = normals;
  30246. vertexData.uvs = uvs;
  30247. return vertexData;
  30248. };
  30249. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30250. /**
  30251. * Creates the VertexData of the Polyhedron.
  30252. */
  30253. VertexData.CreatePolyhedron = function (options) {
  30254. // provided polyhedron types :
  30255. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30256. // 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)
  30257. var polyhedra = [];
  30258. 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]] };
  30259. 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]] };
  30260. polyhedra[2] = {
  30261. 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]],
  30262. 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]]
  30263. };
  30264. polyhedra[3] = {
  30265. 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]],
  30266. 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]]
  30267. };
  30268. polyhedra[4] = {
  30269. 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]],
  30270. 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]]
  30271. };
  30272. 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]] };
  30273. 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]] };
  30274. 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]] };
  30275. 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]] };
  30276. 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]] };
  30277. 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]] };
  30278. 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]] };
  30279. 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]] };
  30280. 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]] };
  30281. polyhedra[14] = {
  30282. 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]],
  30283. 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]]
  30284. };
  30285. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30286. var size = options.size;
  30287. var sizeX = options.sizeX || size || 1;
  30288. var sizeY = options.sizeY || size || 1;
  30289. var sizeZ = options.sizeZ || size || 1;
  30290. var data = options.custom || polyhedra[type];
  30291. var nbfaces = data.face.length;
  30292. var faceUV = options.faceUV || new Array(nbfaces);
  30293. var faceColors = options.faceColors;
  30294. var flat = (options.flat === undefined) ? true : options.flat;
  30295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30296. var positions = new Array();
  30297. var indices = new Array();
  30298. var normals = new Array();
  30299. var uvs = new Array();
  30300. var colors = new Array();
  30301. var index = 0;
  30302. var faceIdx = 0; // face cursor in the array "indexes"
  30303. var indexes = new Array();
  30304. var i = 0;
  30305. var f = 0;
  30306. var u, v, ang, x, y, tmp;
  30307. // default face colors and UV if undefined
  30308. if (flat) {
  30309. for (f = 0; f < nbfaces; f++) {
  30310. if (faceColors && faceColors[f] === undefined) {
  30311. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30312. }
  30313. if (faceUV && faceUV[f] === undefined) {
  30314. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30315. }
  30316. }
  30317. }
  30318. if (!flat) {
  30319. for (i = 0; i < data.vertex.length; i++) {
  30320. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30321. uvs.push(0, 0);
  30322. }
  30323. for (f = 0; f < nbfaces; f++) {
  30324. for (i = 0; i < data.face[f].length - 2; i++) {
  30325. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30326. }
  30327. }
  30328. }
  30329. else {
  30330. for (f = 0; f < nbfaces; f++) {
  30331. var fl = data.face[f].length; // number of vertices of the current face
  30332. ang = 2 * Math.PI / fl;
  30333. x = 0.5 * Math.tan(ang / 2);
  30334. y = 0.5;
  30335. // positions, uvs, colors
  30336. for (i = 0; i < fl; i++) {
  30337. // positions
  30338. 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);
  30339. indexes.push(index);
  30340. index++;
  30341. // uvs
  30342. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30343. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30344. uvs.push(u, v);
  30345. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30346. y = x * Math.sin(ang) + y * Math.cos(ang);
  30347. x = tmp;
  30348. // colors
  30349. if (faceColors) {
  30350. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30351. }
  30352. }
  30353. // indices from indexes
  30354. for (i = 0; i < fl - 2; i++) {
  30355. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30356. }
  30357. faceIdx += fl;
  30358. }
  30359. }
  30360. VertexData.ComputeNormals(positions, indices, normals);
  30361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30362. var vertexData = new VertexData();
  30363. vertexData.positions = positions;
  30364. vertexData.indices = indices;
  30365. vertexData.normals = normals;
  30366. vertexData.uvs = uvs;
  30367. if (faceColors && flat) {
  30368. vertexData.colors = colors;
  30369. }
  30370. return vertexData;
  30371. };
  30372. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30373. /**
  30374. * Creates the VertexData of the Torus Knot.
  30375. */
  30376. VertexData.CreateTorusKnot = function (options) {
  30377. var indices = new Array();
  30378. var positions = new Array();
  30379. var normals = new Array();
  30380. var uvs = new Array();
  30381. var radius = options.radius || 2;
  30382. var tube = options.tube || 0.5;
  30383. var radialSegments = options.radialSegments || 32;
  30384. var tubularSegments = options.tubularSegments || 32;
  30385. var p = options.p || 2;
  30386. var q = options.q || 3;
  30387. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30388. // Helper
  30389. var getPos = function (angle) {
  30390. var cu = Math.cos(angle);
  30391. var su = Math.sin(angle);
  30392. var quOverP = q / p * angle;
  30393. var cs = Math.cos(quOverP);
  30394. var tx = radius * (2 + cs) * 0.5 * cu;
  30395. var ty = radius * (2 + cs) * su * 0.5;
  30396. var tz = radius * Math.sin(quOverP) * 0.5;
  30397. return new BABYLON.Vector3(tx, ty, tz);
  30398. };
  30399. // Vertices
  30400. var i;
  30401. var j;
  30402. for (i = 0; i <= radialSegments; i++) {
  30403. var modI = i % radialSegments;
  30404. var u = modI / radialSegments * 2 * p * Math.PI;
  30405. var p1 = getPos(u);
  30406. var p2 = getPos(u + 0.01);
  30407. var tang = p2.subtract(p1);
  30408. var n = p2.add(p1);
  30409. var bitan = BABYLON.Vector3.Cross(tang, n);
  30410. n = BABYLON.Vector3.Cross(bitan, tang);
  30411. bitan.normalize();
  30412. n.normalize();
  30413. for (j = 0; j < tubularSegments; j++) {
  30414. var modJ = j % tubularSegments;
  30415. var v = modJ / tubularSegments * 2 * Math.PI;
  30416. var cx = -tube * Math.cos(v);
  30417. var cy = tube * Math.sin(v);
  30418. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30419. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30420. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30421. uvs.push(i / radialSegments);
  30422. uvs.push(j / tubularSegments);
  30423. }
  30424. }
  30425. for (i = 0; i < radialSegments; i++) {
  30426. for (j = 0; j < tubularSegments; j++) {
  30427. var jNext = (j + 1) % tubularSegments;
  30428. var a = i * tubularSegments + j;
  30429. var b = (i + 1) * tubularSegments + j;
  30430. var c = (i + 1) * tubularSegments + jNext;
  30431. var d = i * tubularSegments + jNext;
  30432. indices.push(d);
  30433. indices.push(b);
  30434. indices.push(a);
  30435. indices.push(d);
  30436. indices.push(c);
  30437. indices.push(b);
  30438. }
  30439. }
  30440. // Normals
  30441. VertexData.ComputeNormals(positions, indices, normals);
  30442. // Sides
  30443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30444. // Result
  30445. var vertexData = new VertexData();
  30446. vertexData.indices = indices;
  30447. vertexData.positions = positions;
  30448. vertexData.normals = normals;
  30449. vertexData.uvs = uvs;
  30450. return vertexData;
  30451. };
  30452. // Tools
  30453. /**
  30454. * @param {any} - positions (number[] or Float32Array)
  30455. * @param {any} - indices (number[] or Uint16Array)
  30456. * @param {any} - normals (number[] or Float32Array)
  30457. * options (optional) :
  30458. * facetPositions : optional array of facet positions (vector3)
  30459. * facetNormals : optional array of facet normals (vector3)
  30460. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30461. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30462. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30463. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30464. * bInfo : optional bounding info, required for facetPartitioning computation
  30465. * useRightHandedSystem: optional boolean to for right handed system computation
  30466. * depthSort : optional boolean to enable the facet depth sort computation
  30467. * distanceTo : optional Vector3 to compute the facet depth from this location
  30468. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30469. */
  30470. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30471. // temporary scalar variables
  30472. var index = 0; // facet index
  30473. var p1p2x = 0.0; // p1p2 vector x coordinate
  30474. var p1p2y = 0.0; // p1p2 vector y coordinate
  30475. var p1p2z = 0.0; // p1p2 vector z coordinate
  30476. var p3p2x = 0.0; // p3p2 vector x coordinate
  30477. var p3p2y = 0.0; // p3p2 vector y coordinate
  30478. var p3p2z = 0.0; // p3p2 vector z coordinate
  30479. var faceNormalx = 0.0; // facet normal x coordinate
  30480. var faceNormaly = 0.0; // facet normal y coordinate
  30481. var faceNormalz = 0.0; // facet normal z coordinate
  30482. var length = 0.0; // facet normal length before normalization
  30483. var v1x = 0; // vector1 x index in the positions array
  30484. var v1y = 0; // vector1 y index in the positions array
  30485. var v1z = 0; // vector1 z index in the positions array
  30486. var v2x = 0; // vector2 x index in the positions array
  30487. var v2y = 0; // vector2 y index in the positions array
  30488. var v2z = 0; // vector2 z index in the positions array
  30489. var v3x = 0; // vector3 x index in the positions array
  30490. var v3y = 0; // vector3 y index in the positions array
  30491. var v3z = 0; // vector3 z index in the positions array
  30492. var computeFacetNormals = false;
  30493. var computeFacetPositions = false;
  30494. var computeFacetPartitioning = false;
  30495. var computeDepthSort = false;
  30496. var faceNormalSign = 1;
  30497. var ratio = 0;
  30498. var distanceTo = null;
  30499. if (options) {
  30500. computeFacetNormals = (options.facetNormals) ? true : false;
  30501. computeFacetPositions = (options.facetPositions) ? true : false;
  30502. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30503. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30504. ratio = options.ratio || 0;
  30505. computeDepthSort = (options.depthSort) ? true : false;
  30506. distanceTo = (options.distanceTo);
  30507. if (computeDepthSort) {
  30508. if (distanceTo === undefined) {
  30509. distanceTo = BABYLON.Vector3.Zero();
  30510. }
  30511. var depthSortedFacets = options.depthSortedFacets;
  30512. }
  30513. }
  30514. // facetPartitioning reinit if needed
  30515. var xSubRatio = 0;
  30516. var ySubRatio = 0;
  30517. var zSubRatio = 0;
  30518. var subSq = 0;
  30519. if (computeFacetPartitioning && options && options.bbSize) {
  30520. var ox = 0; // X partitioning index for facet position
  30521. var oy = 0; // Y partinioning index for facet position
  30522. var oz = 0; // Z partinioning index for facet position
  30523. var b1x = 0; // X partitioning index for facet v1 vertex
  30524. var b1y = 0; // Y partitioning index for facet v1 vertex
  30525. var b1z = 0; // z partitioning index for facet v1 vertex
  30526. var b2x = 0; // X partitioning index for facet v2 vertex
  30527. var b2y = 0; // Y partitioning index for facet v2 vertex
  30528. var b2z = 0; // Z partitioning index for facet v2 vertex
  30529. var b3x = 0; // X partitioning index for facet v3 vertex
  30530. var b3y = 0; // Y partitioning index for facet v3 vertex
  30531. var b3z = 0; // Z partitioning index for facet v3 vertex
  30532. var block_idx_o = 0; // facet barycenter block index
  30533. var block_idx_v1 = 0; // v1 vertex block index
  30534. var block_idx_v2 = 0; // v2 vertex block index
  30535. var block_idx_v3 = 0; // v3 vertex block index
  30536. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30537. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30538. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30539. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30540. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30541. subSq = options.subDiv.max * options.subDiv.max;
  30542. options.facetPartitioning.length = 0;
  30543. }
  30544. // reset the normals
  30545. for (index = 0; index < positions.length; index++) {
  30546. normals[index] = 0.0;
  30547. }
  30548. // Loop : 1 indice triplet = 1 facet
  30549. var nbFaces = (indices.length / 3) | 0;
  30550. for (index = 0; index < nbFaces; index++) {
  30551. // get the indexes of the coordinates of each vertex of the facet
  30552. v1x = indices[index * 3] * 3;
  30553. v1y = v1x + 1;
  30554. v1z = v1x + 2;
  30555. v2x = indices[index * 3 + 1] * 3;
  30556. v2y = v2x + 1;
  30557. v2z = v2x + 2;
  30558. v3x = indices[index * 3 + 2] * 3;
  30559. v3y = v3x + 1;
  30560. v3z = v3x + 2;
  30561. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30562. p1p2y = positions[v1y] - positions[v2y];
  30563. p1p2z = positions[v1z] - positions[v2z];
  30564. p3p2x = positions[v3x] - positions[v2x];
  30565. p3p2y = positions[v3y] - positions[v2y];
  30566. p3p2z = positions[v3z] - positions[v2z];
  30567. // compute the face normal with the cross product
  30568. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30569. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30570. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30571. // normalize this normal and store it in the array facetData
  30572. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30573. length = (length === 0) ? 1.0 : length;
  30574. faceNormalx /= length;
  30575. faceNormaly /= length;
  30576. faceNormalz /= length;
  30577. if (computeFacetNormals && options) {
  30578. options.facetNormals[index].x = faceNormalx;
  30579. options.facetNormals[index].y = faceNormaly;
  30580. options.facetNormals[index].z = faceNormalz;
  30581. }
  30582. if (computeFacetPositions && options) {
  30583. // compute and the facet barycenter coordinates in the array facetPositions
  30584. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30585. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30586. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30587. }
  30588. if (computeFacetPartitioning && options) {
  30589. // store the facet indexes in arrays in the main facetPartitioning array :
  30590. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30591. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30592. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30593. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30594. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30595. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30596. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30597. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30598. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30599. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30600. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30601. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30602. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30603. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30604. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30605. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30606. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30607. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30608. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30609. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30610. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30611. // push each facet index in each block containing the vertex
  30612. options.facetPartitioning[block_idx_v1].push(index);
  30613. if (block_idx_v2 != block_idx_v1) {
  30614. options.facetPartitioning[block_idx_v2].push(index);
  30615. }
  30616. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30617. options.facetPartitioning[block_idx_v3].push(index);
  30618. }
  30619. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30620. options.facetPartitioning[block_idx_o].push(index);
  30621. }
  30622. }
  30623. if (computeDepthSort && options && options.facetPositions) {
  30624. var dsf = depthSortedFacets[index];
  30625. dsf.ind = index * 3;
  30626. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30627. }
  30628. // compute the normals anyway
  30629. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30630. normals[v1y] += faceNormaly;
  30631. normals[v1z] += faceNormalz;
  30632. normals[v2x] += faceNormalx;
  30633. normals[v2y] += faceNormaly;
  30634. normals[v2z] += faceNormalz;
  30635. normals[v3x] += faceNormalx;
  30636. normals[v3y] += faceNormaly;
  30637. normals[v3z] += faceNormalz;
  30638. }
  30639. // last normalization of each normal
  30640. for (index = 0; index < normals.length / 3; index++) {
  30641. faceNormalx = normals[index * 3];
  30642. faceNormaly = normals[index * 3 + 1];
  30643. faceNormalz = normals[index * 3 + 2];
  30644. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30645. length = (length === 0) ? 1.0 : length;
  30646. faceNormalx /= length;
  30647. faceNormaly /= length;
  30648. faceNormalz /= length;
  30649. normals[index * 3] = faceNormalx;
  30650. normals[index * 3 + 1] = faceNormaly;
  30651. normals[index * 3 + 2] = faceNormalz;
  30652. }
  30653. };
  30654. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30655. var li = indices.length;
  30656. var ln = normals.length;
  30657. var i;
  30658. var n;
  30659. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30660. switch (sideOrientation) {
  30661. case BABYLON.Mesh.FRONTSIDE:
  30662. // nothing changed
  30663. break;
  30664. case BABYLON.Mesh.BACKSIDE:
  30665. var tmp;
  30666. // indices
  30667. for (i = 0; i < li; i += 3) {
  30668. tmp = indices[i];
  30669. indices[i] = indices[i + 2];
  30670. indices[i + 2] = tmp;
  30671. }
  30672. // normals
  30673. for (n = 0; n < ln; n++) {
  30674. normals[n] = -normals[n];
  30675. }
  30676. break;
  30677. case BABYLON.Mesh.DOUBLESIDE:
  30678. // positions
  30679. var lp = positions.length;
  30680. var l = lp / 3;
  30681. for (var p = 0; p < lp; p++) {
  30682. positions[lp + p] = positions[p];
  30683. }
  30684. // indices
  30685. for (i = 0; i < li; i += 3) {
  30686. indices[i + li] = indices[i + 2] + l;
  30687. indices[i + 1 + li] = indices[i + 1] + l;
  30688. indices[i + 2 + li] = indices[i] + l;
  30689. }
  30690. // normals
  30691. for (n = 0; n < ln; n++) {
  30692. normals[ln + n] = -normals[n];
  30693. }
  30694. // uvs
  30695. var lu = uvs.length;
  30696. var u = 0;
  30697. for (u = 0; u < lu; u++) {
  30698. uvs[u + lu] = uvs[u];
  30699. }
  30700. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30701. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30702. u = 0;
  30703. for (i = 0; i < lu / 2; i++) {
  30704. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30705. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30706. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30707. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30708. u += 2;
  30709. }
  30710. break;
  30711. }
  30712. };
  30713. /**
  30714. * Creates a new VertexData from the imported parameters.
  30715. */
  30716. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30717. var vertexData = new VertexData();
  30718. // positions
  30719. var positions = parsedVertexData.positions;
  30720. if (positions) {
  30721. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30722. }
  30723. // normals
  30724. var normals = parsedVertexData.normals;
  30725. if (normals) {
  30726. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30727. }
  30728. // tangents
  30729. var tangents = parsedVertexData.tangents;
  30730. if (tangents) {
  30731. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30732. }
  30733. // uvs
  30734. var uvs = parsedVertexData.uvs;
  30735. if (uvs) {
  30736. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30737. }
  30738. // uv2s
  30739. var uv2s = parsedVertexData.uv2s;
  30740. if (uv2s) {
  30741. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30742. }
  30743. // uv3s
  30744. var uv3s = parsedVertexData.uv3s;
  30745. if (uv3s) {
  30746. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30747. }
  30748. // uv4s
  30749. var uv4s = parsedVertexData.uv4s;
  30750. if (uv4s) {
  30751. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30752. }
  30753. // uv5s
  30754. var uv5s = parsedVertexData.uv5s;
  30755. if (uv5s) {
  30756. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30757. }
  30758. // uv6s
  30759. var uv6s = parsedVertexData.uv6s;
  30760. if (uv6s) {
  30761. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30762. }
  30763. // colors
  30764. var colors = parsedVertexData.colors;
  30765. if (colors) {
  30766. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30767. }
  30768. // matricesIndices
  30769. var matricesIndices = parsedVertexData.matricesIndices;
  30770. if (matricesIndices) {
  30771. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30772. }
  30773. // matricesWeights
  30774. var matricesWeights = parsedVertexData.matricesWeights;
  30775. if (matricesWeights) {
  30776. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30777. }
  30778. // indices
  30779. var indices = parsedVertexData.indices;
  30780. if (indices) {
  30781. vertexData.indices = indices;
  30782. }
  30783. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30784. };
  30785. return VertexData;
  30786. }());
  30787. BABYLON.VertexData = VertexData;
  30788. })(BABYLON || (BABYLON = {}));
  30789. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30790. var BABYLON;
  30791. (function (BABYLON) {
  30792. var Geometry = /** @class */ (function () {
  30793. function Geometry(id, scene, vertexData, updatable, mesh) {
  30794. if (updatable === void 0) { updatable = false; }
  30795. if (mesh === void 0) { mesh = null; }
  30796. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30797. this._totalVertices = 0;
  30798. this._isDisposed = false;
  30799. this._indexBufferIsUpdatable = false;
  30800. this.id = id;
  30801. this._engine = scene.getEngine();
  30802. this._meshes = [];
  30803. this._scene = scene;
  30804. //Init vertex buffer cache
  30805. this._vertexBuffers = {};
  30806. this._indices = [];
  30807. this._updatable = updatable;
  30808. // vertexData
  30809. if (vertexData) {
  30810. this.setAllVerticesData(vertexData, updatable);
  30811. }
  30812. else {
  30813. this._totalVertices = 0;
  30814. this._indices = [];
  30815. }
  30816. if (this._engine.getCaps().vertexArrayObject) {
  30817. this._vertexArrayObjects = {};
  30818. }
  30819. // applyToMesh
  30820. if (mesh) {
  30821. if (mesh.getClassName() === "LinesMesh") {
  30822. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30823. this.updateExtend();
  30824. }
  30825. this.applyToMesh(mesh);
  30826. mesh.computeWorldMatrix(true);
  30827. }
  30828. }
  30829. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30830. /**
  30831. * 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
  30832. * @returns The Bias Vector
  30833. */
  30834. get: function () {
  30835. return this._boundingBias;
  30836. },
  30837. set: function (value) {
  30838. if (this._boundingBias && this._boundingBias.equals(value)) {
  30839. return;
  30840. }
  30841. this._boundingBias = value.clone();
  30842. this.updateBoundingInfo(true, null);
  30843. },
  30844. enumerable: true,
  30845. configurable: true
  30846. });
  30847. Geometry.CreateGeometryForMesh = function (mesh) {
  30848. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30849. geometry.applyToMesh(mesh);
  30850. return geometry;
  30851. };
  30852. Object.defineProperty(Geometry.prototype, "extend", {
  30853. get: function () {
  30854. return this._extend;
  30855. },
  30856. enumerable: true,
  30857. configurable: true
  30858. });
  30859. Geometry.prototype.getScene = function () {
  30860. return this._scene;
  30861. };
  30862. Geometry.prototype.getEngine = function () {
  30863. return this._engine;
  30864. };
  30865. Geometry.prototype.isReady = function () {
  30866. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30867. };
  30868. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30869. get: function () {
  30870. for (var index = 0; index < this._meshes.length; index++) {
  30871. if (!this._meshes[index].doNotSerialize) {
  30872. return false;
  30873. }
  30874. }
  30875. return true;
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Geometry.prototype._rebuild = function () {
  30881. if (this._vertexArrayObjects) {
  30882. this._vertexArrayObjects = {};
  30883. }
  30884. // Index buffer
  30885. if (this._meshes.length !== 0 && this._indices) {
  30886. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30887. }
  30888. // Vertex buffers
  30889. for (var key in this._vertexBuffers) {
  30890. var vertexBuffer = this._vertexBuffers[key];
  30891. vertexBuffer._rebuild();
  30892. }
  30893. };
  30894. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30895. vertexData.applyToGeometry(this, updatable);
  30896. this.notifyUpdate();
  30897. };
  30898. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30899. if (updatable === void 0) { updatable = false; }
  30900. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30901. this.setVerticesBuffer(buffer);
  30902. };
  30903. Geometry.prototype.removeVerticesData = function (kind) {
  30904. if (this._vertexBuffers[kind]) {
  30905. this._vertexBuffers[kind].dispose();
  30906. delete this._vertexBuffers[kind];
  30907. }
  30908. };
  30909. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30910. var kind = buffer.getKind();
  30911. if (this._vertexBuffers[kind]) {
  30912. this._vertexBuffers[kind].dispose();
  30913. }
  30914. this._vertexBuffers[kind] = buffer;
  30915. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30916. var data = buffer.getData();
  30917. var stride = buffer.getStrideSize();
  30918. this._totalVertices = data.length / stride;
  30919. this.updateExtend(data, stride);
  30920. this._resetPointsArrayCache();
  30921. var meshes = this._meshes;
  30922. var numOfMeshes = meshes.length;
  30923. for (var index = 0; index < numOfMeshes; index++) {
  30924. var mesh = meshes[index];
  30925. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30926. mesh._createGlobalSubMesh(false);
  30927. mesh.computeWorldMatrix(true);
  30928. }
  30929. }
  30930. this.notifyUpdate(kind);
  30931. if (this._vertexArrayObjects) {
  30932. this._disposeVertexArrayObjects();
  30933. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30934. }
  30935. };
  30936. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30937. var vertexBuffer = this.getVertexBuffer(kind);
  30938. if (!vertexBuffer) {
  30939. return;
  30940. }
  30941. vertexBuffer.updateDirectly(data, offset);
  30942. this.notifyUpdate(kind);
  30943. };
  30944. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30945. if (updateExtends === void 0) { updateExtends = false; }
  30946. var vertexBuffer = this.getVertexBuffer(kind);
  30947. if (!vertexBuffer) {
  30948. return;
  30949. }
  30950. vertexBuffer.update(data);
  30951. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30952. var stride = vertexBuffer.getStrideSize();
  30953. this._totalVertices = data.length / stride;
  30954. this.updateBoundingInfo(updateExtends, data);
  30955. }
  30956. this.notifyUpdate(kind);
  30957. };
  30958. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30959. if (updateExtends) {
  30960. this.updateExtend(data);
  30961. }
  30962. var meshes = this._meshes;
  30963. var numOfMeshes = meshes.length;
  30964. this._resetPointsArrayCache();
  30965. for (var index = 0; index < numOfMeshes; index++) {
  30966. var mesh = meshes[index];
  30967. if (updateExtends) {
  30968. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30969. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30970. var subMesh = mesh.subMeshes[subIndex];
  30971. subMesh.refreshBoundingInfo();
  30972. }
  30973. }
  30974. }
  30975. };
  30976. Geometry.prototype._bind = function (effect, indexToBind) {
  30977. if (!effect) {
  30978. return;
  30979. }
  30980. if (indexToBind === undefined) {
  30981. indexToBind = this._indexBuffer;
  30982. }
  30983. var vbs = this.getVertexBuffers();
  30984. if (!vbs) {
  30985. return;
  30986. }
  30987. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30988. this._engine.bindBuffers(vbs, indexToBind, effect);
  30989. return;
  30990. }
  30991. // Using VAO
  30992. if (!this._vertexArrayObjects[effect.key]) {
  30993. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30994. }
  30995. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30996. };
  30997. Geometry.prototype.getTotalVertices = function () {
  30998. if (!this.isReady()) {
  30999. return 0;
  31000. }
  31001. return this._totalVertices;
  31002. };
  31003. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31004. var vertexBuffer = this.getVertexBuffer(kind);
  31005. if (!vertexBuffer) {
  31006. return null;
  31007. }
  31008. var orig = vertexBuffer.getData();
  31009. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31010. return orig;
  31011. }
  31012. else {
  31013. var len = orig.length;
  31014. var copy = [];
  31015. for (var i = 0; i < len; i++) {
  31016. copy.push(orig[i]);
  31017. }
  31018. return copy;
  31019. }
  31020. };
  31021. /**
  31022. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31023. * Possible `kind` values :
  31024. * - BABYLON.VertexBuffer.PositionKind
  31025. * - BABYLON.VertexBuffer.UVKind
  31026. * - BABYLON.VertexBuffer.UV2Kind
  31027. * - BABYLON.VertexBuffer.UV3Kind
  31028. * - BABYLON.VertexBuffer.UV4Kind
  31029. * - BABYLON.VertexBuffer.UV5Kind
  31030. * - BABYLON.VertexBuffer.UV6Kind
  31031. * - BABYLON.VertexBuffer.ColorKind
  31032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31036. */
  31037. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31038. var vb = this._vertexBuffers[kind];
  31039. if (!vb) {
  31040. return false;
  31041. }
  31042. return vb.isUpdatable();
  31043. };
  31044. Geometry.prototype.getVertexBuffer = function (kind) {
  31045. if (!this.isReady()) {
  31046. return null;
  31047. }
  31048. return this._vertexBuffers[kind];
  31049. };
  31050. Geometry.prototype.getVertexBuffers = function () {
  31051. if (!this.isReady()) {
  31052. return null;
  31053. }
  31054. return this._vertexBuffers;
  31055. };
  31056. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31057. if (!this._vertexBuffers) {
  31058. if (this._delayInfo) {
  31059. return this._delayInfo.indexOf(kind) !== -1;
  31060. }
  31061. return false;
  31062. }
  31063. return this._vertexBuffers[kind] !== undefined;
  31064. };
  31065. Geometry.prototype.getVerticesDataKinds = function () {
  31066. var result = [];
  31067. var kind;
  31068. if (!this._vertexBuffers && this._delayInfo) {
  31069. for (kind in this._delayInfo) {
  31070. result.push(kind);
  31071. }
  31072. }
  31073. else {
  31074. for (kind in this._vertexBuffers) {
  31075. result.push(kind);
  31076. }
  31077. }
  31078. return result;
  31079. };
  31080. Geometry.prototype.updateIndices = function (indices, offset) {
  31081. if (!this._indexBuffer) {
  31082. return;
  31083. }
  31084. if (!this._indexBufferIsUpdatable) {
  31085. this.setIndices(indices, null, true);
  31086. }
  31087. else {
  31088. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31089. }
  31090. };
  31091. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31092. if (totalVertices === void 0) { totalVertices = null; }
  31093. if (updatable === void 0) { updatable = false; }
  31094. if (this._indexBuffer) {
  31095. this._engine._releaseBuffer(this._indexBuffer);
  31096. }
  31097. this._disposeVertexArrayObjects();
  31098. this._indices = indices;
  31099. this._indexBufferIsUpdatable = updatable;
  31100. if (this._meshes.length !== 0 && this._indices) {
  31101. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31102. }
  31103. if (totalVertices != undefined) {
  31104. this._totalVertices = totalVertices;
  31105. }
  31106. var meshes = this._meshes;
  31107. var numOfMeshes = meshes.length;
  31108. for (var index = 0; index < numOfMeshes; index++) {
  31109. meshes[index]._createGlobalSubMesh(true);
  31110. }
  31111. this.notifyUpdate();
  31112. };
  31113. Geometry.prototype.getTotalIndices = function () {
  31114. if (!this.isReady()) {
  31115. return 0;
  31116. }
  31117. return this._indices.length;
  31118. };
  31119. Geometry.prototype.getIndices = function (copyWhenShared) {
  31120. if (!this.isReady()) {
  31121. return null;
  31122. }
  31123. var orig = this._indices;
  31124. if (!copyWhenShared || this._meshes.length === 1) {
  31125. return orig;
  31126. }
  31127. else {
  31128. var len = orig.length;
  31129. var copy = [];
  31130. for (var i = 0; i < len; i++) {
  31131. copy.push(orig[i]);
  31132. }
  31133. return copy;
  31134. }
  31135. };
  31136. Geometry.prototype.getIndexBuffer = function () {
  31137. if (!this.isReady()) {
  31138. return null;
  31139. }
  31140. return this._indexBuffer;
  31141. };
  31142. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31143. if (effect === void 0) { effect = null; }
  31144. if (!effect || !this._vertexArrayObjects) {
  31145. return;
  31146. }
  31147. if (this._vertexArrayObjects[effect.key]) {
  31148. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31149. delete this._vertexArrayObjects[effect.key];
  31150. }
  31151. };
  31152. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31153. var meshes = this._meshes;
  31154. var index = meshes.indexOf(mesh);
  31155. if (index === -1) {
  31156. return;
  31157. }
  31158. meshes.splice(index, 1);
  31159. mesh._geometry = null;
  31160. if (meshes.length === 0 && shouldDispose) {
  31161. this.dispose();
  31162. }
  31163. };
  31164. Geometry.prototype.applyToMesh = function (mesh) {
  31165. if (mesh._geometry === this) {
  31166. return;
  31167. }
  31168. var previousGeometry = mesh._geometry;
  31169. if (previousGeometry) {
  31170. previousGeometry.releaseForMesh(mesh);
  31171. }
  31172. var meshes = this._meshes;
  31173. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31174. mesh._geometry = this;
  31175. this._scene.pushGeometry(this);
  31176. meshes.push(mesh);
  31177. if (this.isReady()) {
  31178. this._applyToMesh(mesh);
  31179. }
  31180. else {
  31181. mesh._boundingInfo = this._boundingInfo;
  31182. }
  31183. };
  31184. Geometry.prototype.updateExtend = function (data, stride) {
  31185. if (data === void 0) { data = null; }
  31186. if (!data) {
  31187. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31188. }
  31189. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31190. };
  31191. Geometry.prototype._applyToMesh = function (mesh) {
  31192. var numOfMeshes = this._meshes.length;
  31193. // vertexBuffers
  31194. for (var kind in this._vertexBuffers) {
  31195. if (numOfMeshes === 1) {
  31196. this._vertexBuffers[kind].create();
  31197. }
  31198. var buffer = this._vertexBuffers[kind].getBuffer();
  31199. if (buffer)
  31200. buffer.references = numOfMeshes;
  31201. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31202. if (!this._extend) {
  31203. this.updateExtend(this._vertexBuffers[kind].getData());
  31204. }
  31205. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31206. mesh._createGlobalSubMesh(false);
  31207. //bounding info was just created again, world matrix should be applied again.
  31208. mesh._updateBoundingInfo();
  31209. }
  31210. }
  31211. // indexBuffer
  31212. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31213. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31214. }
  31215. if (this._indexBuffer) {
  31216. this._indexBuffer.references = numOfMeshes;
  31217. }
  31218. };
  31219. Geometry.prototype.notifyUpdate = function (kind) {
  31220. if (this.onGeometryUpdated) {
  31221. this.onGeometryUpdated(this, kind);
  31222. }
  31223. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31224. var mesh = _a[_i];
  31225. mesh._markSubMeshesAsAttributesDirty();
  31226. }
  31227. };
  31228. Geometry.prototype.load = function (scene, onLoaded) {
  31229. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31230. return;
  31231. }
  31232. if (this.isReady()) {
  31233. if (onLoaded) {
  31234. onLoaded();
  31235. }
  31236. return;
  31237. }
  31238. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31239. this._queueLoad(scene, onLoaded);
  31240. };
  31241. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31242. var _this = this;
  31243. if (!this.delayLoadingFile) {
  31244. return;
  31245. }
  31246. scene._addPendingData(this);
  31247. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31248. if (!_this._delayLoadingFunction) {
  31249. return;
  31250. }
  31251. _this._delayLoadingFunction(JSON.parse(data), _this);
  31252. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31253. _this._delayInfo = [];
  31254. scene._removePendingData(_this);
  31255. var meshes = _this._meshes;
  31256. var numOfMeshes = meshes.length;
  31257. for (var index = 0; index < numOfMeshes; index++) {
  31258. _this._applyToMesh(meshes[index]);
  31259. }
  31260. if (onLoaded) {
  31261. onLoaded();
  31262. }
  31263. }, function () { }, scene.database);
  31264. };
  31265. /**
  31266. * Invert the geometry to move from a right handed system to a left handed one.
  31267. */
  31268. Geometry.prototype.toLeftHanded = function () {
  31269. // Flip faces
  31270. var tIndices = this.getIndices(false);
  31271. if (tIndices != null && tIndices.length > 0) {
  31272. for (var i = 0; i < tIndices.length; i += 3) {
  31273. var tTemp = tIndices[i + 0];
  31274. tIndices[i + 0] = tIndices[i + 2];
  31275. tIndices[i + 2] = tTemp;
  31276. }
  31277. this.setIndices(tIndices);
  31278. }
  31279. // Negate position.z
  31280. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31281. if (tPositions != null && tPositions.length > 0) {
  31282. for (var i = 0; i < tPositions.length; i += 3) {
  31283. tPositions[i + 2] = -tPositions[i + 2];
  31284. }
  31285. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31286. }
  31287. // Negate normal.z
  31288. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31289. if (tNormals != null && tNormals.length > 0) {
  31290. for (var i = 0; i < tNormals.length; i += 3) {
  31291. tNormals[i + 2] = -tNormals[i + 2];
  31292. }
  31293. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31294. }
  31295. };
  31296. // Cache
  31297. Geometry.prototype._resetPointsArrayCache = function () {
  31298. this._positions = null;
  31299. };
  31300. Geometry.prototype._generatePointsArray = function () {
  31301. if (this._positions)
  31302. return true;
  31303. this._positions = [];
  31304. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31305. if (!data) {
  31306. return false;
  31307. }
  31308. for (var index = 0; index < data.length; index += 3) {
  31309. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31310. }
  31311. return true;
  31312. };
  31313. Geometry.prototype.isDisposed = function () {
  31314. return this._isDisposed;
  31315. };
  31316. Geometry.prototype._disposeVertexArrayObjects = function () {
  31317. if (this._vertexArrayObjects) {
  31318. for (var kind in this._vertexArrayObjects) {
  31319. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31320. }
  31321. this._vertexArrayObjects = {};
  31322. }
  31323. };
  31324. Geometry.prototype.dispose = function () {
  31325. var meshes = this._meshes;
  31326. var numOfMeshes = meshes.length;
  31327. var index;
  31328. for (index = 0; index < numOfMeshes; index++) {
  31329. this.releaseForMesh(meshes[index]);
  31330. }
  31331. this._meshes = [];
  31332. this._disposeVertexArrayObjects();
  31333. for (var kind in this._vertexBuffers) {
  31334. this._vertexBuffers[kind].dispose();
  31335. }
  31336. this._vertexBuffers = {};
  31337. this._totalVertices = 0;
  31338. if (this._indexBuffer) {
  31339. this._engine._releaseBuffer(this._indexBuffer);
  31340. }
  31341. this._indexBuffer = null;
  31342. this._indices = [];
  31343. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31344. this.delayLoadingFile = null;
  31345. this._delayLoadingFunction = null;
  31346. this._delayInfo = [];
  31347. this._boundingInfo = null;
  31348. this._scene.removeGeometry(this);
  31349. this._isDisposed = true;
  31350. };
  31351. Geometry.prototype.copy = function (id) {
  31352. var vertexData = new BABYLON.VertexData();
  31353. vertexData.indices = [];
  31354. var indices = this.getIndices();
  31355. if (indices) {
  31356. for (var index = 0; index < indices.length; index++) {
  31357. vertexData.indices.push(indices[index]);
  31358. }
  31359. }
  31360. var updatable = false;
  31361. var stopChecking = false;
  31362. var kind;
  31363. for (kind in this._vertexBuffers) {
  31364. // using slice() to make a copy of the array and not just reference it
  31365. var data = this.getVerticesData(kind);
  31366. if (data instanceof Float32Array) {
  31367. vertexData.set(new Float32Array(data), kind);
  31368. }
  31369. else {
  31370. vertexData.set(data.slice(0), kind);
  31371. }
  31372. if (!stopChecking) {
  31373. var vb = this.getVertexBuffer(kind);
  31374. if (vb) {
  31375. updatable = vb.isUpdatable();
  31376. stopChecking = !updatable;
  31377. }
  31378. }
  31379. }
  31380. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31381. geometry.delayLoadState = this.delayLoadState;
  31382. geometry.delayLoadingFile = this.delayLoadingFile;
  31383. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31384. for (kind in this._delayInfo) {
  31385. geometry._delayInfo = geometry._delayInfo || [];
  31386. geometry._delayInfo.push(kind);
  31387. }
  31388. // Bounding info
  31389. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31390. return geometry;
  31391. };
  31392. Geometry.prototype.serialize = function () {
  31393. var serializationObject = {};
  31394. serializationObject.id = this.id;
  31395. serializationObject.updatable = this._updatable;
  31396. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31397. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31398. }
  31399. return serializationObject;
  31400. };
  31401. Geometry.prototype.toNumberArray = function (origin) {
  31402. if (Array.isArray(origin)) {
  31403. return origin;
  31404. }
  31405. else {
  31406. return Array.prototype.slice.call(origin);
  31407. }
  31408. };
  31409. Geometry.prototype.serializeVerticeData = function () {
  31410. var serializationObject = this.serialize();
  31411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31412. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31413. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31414. serializationObject.positions._updatable = true;
  31415. }
  31416. }
  31417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31418. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31420. serializationObject.normals._updatable = true;
  31421. }
  31422. }
  31423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31424. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31426. serializationObject.uvs._updatable = true;
  31427. }
  31428. }
  31429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31430. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31431. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31432. serializationObject.uv2s._updatable = true;
  31433. }
  31434. }
  31435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31436. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31437. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31438. serializationObject.uv3s._updatable = true;
  31439. }
  31440. }
  31441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31442. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31443. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31444. serializationObject.uv4s._updatable = true;
  31445. }
  31446. }
  31447. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31448. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31449. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31450. serializationObject.uv5s._updatable = true;
  31451. }
  31452. }
  31453. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31454. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31455. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31456. serializationObject.uv6s._updatable = true;
  31457. }
  31458. }
  31459. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31460. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31461. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31462. serializationObject.colors._updatable = true;
  31463. }
  31464. }
  31465. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31466. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31467. serializationObject.matricesIndices._isExpanded = true;
  31468. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31469. serializationObject.matricesIndices._updatable = true;
  31470. }
  31471. }
  31472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31473. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31474. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31475. serializationObject.matricesWeights._updatable = true;
  31476. }
  31477. }
  31478. serializationObject.indices = this.toNumberArray(this.getIndices());
  31479. return serializationObject;
  31480. };
  31481. // Statics
  31482. Geometry.ExtractFromMesh = function (mesh, id) {
  31483. var geometry = mesh._geometry;
  31484. if (!geometry) {
  31485. return null;
  31486. }
  31487. return geometry.copy(id);
  31488. };
  31489. /**
  31490. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31491. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31492. * Be aware Math.random() could cause collisions, but:
  31493. * "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"
  31494. */
  31495. Geometry.RandomId = function () {
  31496. return BABYLON.Tools.RandomId();
  31497. };
  31498. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31499. var scene = mesh.getScene();
  31500. // Geometry
  31501. var geometryId = parsedGeometry.geometryId;
  31502. if (geometryId) {
  31503. var geometry = scene.getGeometryByID(geometryId);
  31504. if (geometry) {
  31505. geometry.applyToMesh(mesh);
  31506. }
  31507. }
  31508. else if (parsedGeometry instanceof ArrayBuffer) {
  31509. var binaryInfo = mesh._binaryInfo;
  31510. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31511. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31512. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31513. }
  31514. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31515. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31516. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31517. }
  31518. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31519. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31520. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31521. }
  31522. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31523. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31524. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31525. }
  31526. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31527. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31528. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31529. }
  31530. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31531. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31532. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31533. }
  31534. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31535. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31536. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31537. }
  31538. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31539. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31540. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31541. }
  31542. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31543. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31544. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31545. }
  31546. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31547. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31549. }
  31550. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31551. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31552. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31553. }
  31554. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31555. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31556. mesh.setIndices(indicesData, null);
  31557. }
  31558. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31559. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31560. mesh.subMeshes = [];
  31561. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31562. var materialIndex = subMeshesData[(i * 5) + 0];
  31563. var verticesStart = subMeshesData[(i * 5) + 1];
  31564. var verticesCount = subMeshesData[(i * 5) + 2];
  31565. var indexStart = subMeshesData[(i * 5) + 3];
  31566. var indexCount = subMeshesData[(i * 5) + 4];
  31567. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31568. }
  31569. }
  31570. }
  31571. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31572. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31573. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31574. if (parsedGeometry.uvs) {
  31575. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31576. }
  31577. if (parsedGeometry.uvs2) {
  31578. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31579. }
  31580. if (parsedGeometry.uvs3) {
  31581. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31582. }
  31583. if (parsedGeometry.uvs4) {
  31584. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31585. }
  31586. if (parsedGeometry.uvs5) {
  31587. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31588. }
  31589. if (parsedGeometry.uvs6) {
  31590. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31591. }
  31592. if (parsedGeometry.colors) {
  31593. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31594. }
  31595. if (parsedGeometry.matricesIndices) {
  31596. if (!parsedGeometry.matricesIndices._isExpanded) {
  31597. var floatIndices = [];
  31598. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31599. var matricesIndex = parsedGeometry.matricesIndices[i];
  31600. floatIndices.push(matricesIndex & 0x000000FF);
  31601. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31602. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31603. floatIndices.push(matricesIndex >> 24);
  31604. }
  31605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31606. }
  31607. else {
  31608. delete parsedGeometry.matricesIndices._isExpanded;
  31609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31610. }
  31611. }
  31612. if (parsedGeometry.matricesIndicesExtra) {
  31613. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31614. var floatIndices = [];
  31615. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31616. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31617. floatIndices.push(matricesIndex & 0x000000FF);
  31618. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31619. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31620. floatIndices.push(matricesIndex >> 24);
  31621. }
  31622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31623. }
  31624. else {
  31625. delete parsedGeometry.matricesIndices._isExpanded;
  31626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31627. }
  31628. }
  31629. if (parsedGeometry.matricesWeights) {
  31630. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31632. }
  31633. if (parsedGeometry.matricesWeightsExtra) {
  31634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31635. }
  31636. mesh.setIndices(parsedGeometry.indices, null);
  31637. }
  31638. // SubMeshes
  31639. if (parsedGeometry.subMeshes) {
  31640. mesh.subMeshes = [];
  31641. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31642. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31643. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31644. }
  31645. }
  31646. // Flat shading
  31647. if (mesh._shouldGenerateFlatShading) {
  31648. mesh.convertToFlatShadedMesh();
  31649. delete mesh._shouldGenerateFlatShading;
  31650. }
  31651. // Update
  31652. mesh.computeWorldMatrix(true);
  31653. // Octree
  31654. if (scene['_selectionOctree']) {
  31655. scene['_selectionOctree'].addMesh(mesh);
  31656. }
  31657. };
  31658. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31659. var epsilon = 1e-3;
  31660. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31661. return;
  31662. }
  31663. var noInfluenceBoneIndex = 0.0;
  31664. if (parsedGeometry.skeletonId > -1) {
  31665. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31666. if (!skeleton) {
  31667. return;
  31668. }
  31669. noInfluenceBoneIndex = skeleton.bones.length;
  31670. }
  31671. else {
  31672. return;
  31673. }
  31674. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31675. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31676. var matricesWeights = parsedGeometry.matricesWeights;
  31677. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31678. var influencers = parsedGeometry.numBoneInfluencer;
  31679. var size = matricesWeights.length;
  31680. for (var i = 0; i < size; i += 4) {
  31681. var weight = 0.0;
  31682. var firstZeroWeight = -1;
  31683. for (var j = 0; j < 4; j++) {
  31684. var w = matricesWeights[i + j];
  31685. weight += w;
  31686. if (w < epsilon && firstZeroWeight < 0) {
  31687. firstZeroWeight = j;
  31688. }
  31689. }
  31690. if (matricesWeightsExtra) {
  31691. for (var j = 0; j < 4; j++) {
  31692. var w = matricesWeightsExtra[i + j];
  31693. weight += w;
  31694. if (w < epsilon && firstZeroWeight < 0) {
  31695. firstZeroWeight = j + 4;
  31696. }
  31697. }
  31698. }
  31699. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31700. firstZeroWeight = influencers - 1;
  31701. }
  31702. if (weight > epsilon) {
  31703. var mweight = 1.0 / weight;
  31704. for (var j = 0; j < 4; j++) {
  31705. matricesWeights[i + j] *= mweight;
  31706. }
  31707. if (matricesWeightsExtra) {
  31708. for (var j = 0; j < 4; j++) {
  31709. matricesWeightsExtra[i + j] *= mweight;
  31710. }
  31711. }
  31712. }
  31713. else {
  31714. if (firstZeroWeight >= 4) {
  31715. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31716. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31717. }
  31718. else {
  31719. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31720. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31721. }
  31722. }
  31723. }
  31724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31725. if (parsedGeometry.matricesWeightsExtra) {
  31726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31727. }
  31728. };
  31729. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31730. if (scene.getGeometryByID(parsedVertexData.id)) {
  31731. return null; // null since geometry could be something else than a box...
  31732. }
  31733. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31734. if (BABYLON.Tags) {
  31735. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31736. }
  31737. if (parsedVertexData.delayLoadingFile) {
  31738. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31739. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31740. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31741. geometry._delayInfo = [];
  31742. if (parsedVertexData.hasUVs) {
  31743. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31744. }
  31745. if (parsedVertexData.hasUVs2) {
  31746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31747. }
  31748. if (parsedVertexData.hasUVs3) {
  31749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31750. }
  31751. if (parsedVertexData.hasUVs4) {
  31752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31753. }
  31754. if (parsedVertexData.hasUVs5) {
  31755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31756. }
  31757. if (parsedVertexData.hasUVs6) {
  31758. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31759. }
  31760. if (parsedVertexData.hasColors) {
  31761. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31762. }
  31763. if (parsedVertexData.hasMatricesIndices) {
  31764. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31765. }
  31766. if (parsedVertexData.hasMatricesWeights) {
  31767. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31768. }
  31769. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31770. }
  31771. else {
  31772. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31773. }
  31774. scene.pushGeometry(geometry, true);
  31775. return geometry;
  31776. };
  31777. return Geometry;
  31778. }());
  31779. BABYLON.Geometry = Geometry;
  31780. /////// Primitives //////////////////////////////////////////////
  31781. (function (Geometry) {
  31782. var Primitives;
  31783. (function (Primitives) {
  31784. /// Abstract class
  31785. var _Primitive = /** @class */ (function (_super) {
  31786. __extends(_Primitive, _super);
  31787. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31788. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31789. if (mesh === void 0) { mesh = null; }
  31790. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31791. _this._canBeRegenerated = _canBeRegenerated;
  31792. _this._beingRegenerated = true;
  31793. _this.regenerate();
  31794. _this._beingRegenerated = false;
  31795. return _this;
  31796. }
  31797. _Primitive.prototype.canBeRegenerated = function () {
  31798. return this._canBeRegenerated;
  31799. };
  31800. _Primitive.prototype.regenerate = function () {
  31801. if (!this._canBeRegenerated) {
  31802. return;
  31803. }
  31804. this._beingRegenerated = true;
  31805. this.setAllVerticesData(this._regenerateVertexData(), false);
  31806. this._beingRegenerated = false;
  31807. };
  31808. _Primitive.prototype.asNewGeometry = function (id) {
  31809. return _super.prototype.copy.call(this, id);
  31810. };
  31811. // overrides
  31812. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31813. if (!this._beingRegenerated) {
  31814. return;
  31815. }
  31816. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31817. };
  31818. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31819. if (!this._beingRegenerated) {
  31820. return;
  31821. }
  31822. _super.prototype.setVerticesData.call(this, kind, data, false);
  31823. };
  31824. // to override
  31825. // protected
  31826. _Primitive.prototype._regenerateVertexData = function () {
  31827. throw new Error("Abstract method");
  31828. };
  31829. _Primitive.prototype.copy = function (id) {
  31830. throw new Error("Must be overriden in sub-classes.");
  31831. };
  31832. _Primitive.prototype.serialize = function () {
  31833. var serializationObject = _super.prototype.serialize.call(this);
  31834. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31835. return serializationObject;
  31836. };
  31837. return _Primitive;
  31838. }(Geometry));
  31839. Primitives._Primitive = _Primitive;
  31840. var Ribbon = /** @class */ (function (_super) {
  31841. __extends(Ribbon, _super);
  31842. // Members
  31843. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31844. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31845. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31846. _this.pathArray = pathArray;
  31847. _this.closeArray = closeArray;
  31848. _this.closePath = closePath;
  31849. _this.offset = offset;
  31850. _this.side = side;
  31851. return _this;
  31852. }
  31853. Ribbon.prototype._regenerateVertexData = function () {
  31854. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31855. };
  31856. Ribbon.prototype.copy = function (id) {
  31857. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31858. };
  31859. return Ribbon;
  31860. }(_Primitive));
  31861. Primitives.Ribbon = Ribbon;
  31862. var Box = /** @class */ (function (_super) {
  31863. __extends(Box, _super);
  31864. // Members
  31865. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31866. if (mesh === void 0) { mesh = null; }
  31867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31868. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31869. _this.size = size;
  31870. _this.side = side;
  31871. return _this;
  31872. }
  31873. Box.prototype._regenerateVertexData = function () {
  31874. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31875. };
  31876. Box.prototype.copy = function (id) {
  31877. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31878. };
  31879. Box.prototype.serialize = function () {
  31880. var serializationObject = _super.prototype.serialize.call(this);
  31881. serializationObject.size = this.size;
  31882. return serializationObject;
  31883. };
  31884. Box.Parse = function (parsedBox, scene) {
  31885. if (scene.getGeometryByID(parsedBox.id)) {
  31886. return null; // null since geometry could be something else than a box...
  31887. }
  31888. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31889. if (BABYLON.Tags) {
  31890. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31891. }
  31892. scene.pushGeometry(box, true);
  31893. return box;
  31894. };
  31895. return Box;
  31896. }(_Primitive));
  31897. Primitives.Box = Box;
  31898. var Sphere = /** @class */ (function (_super) {
  31899. __extends(Sphere, _super);
  31900. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31901. if (mesh === void 0) { mesh = null; }
  31902. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31903. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31904. _this.segments = segments;
  31905. _this.diameter = diameter;
  31906. _this.side = side;
  31907. return _this;
  31908. }
  31909. Sphere.prototype._regenerateVertexData = function () {
  31910. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31911. };
  31912. Sphere.prototype.copy = function (id) {
  31913. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31914. };
  31915. Sphere.prototype.serialize = function () {
  31916. var serializationObject = _super.prototype.serialize.call(this);
  31917. serializationObject.segments = this.segments;
  31918. serializationObject.diameter = this.diameter;
  31919. return serializationObject;
  31920. };
  31921. Sphere.Parse = function (parsedSphere, scene) {
  31922. if (scene.getGeometryByID(parsedSphere.id)) {
  31923. return null; // null since geometry could be something else than a sphere...
  31924. }
  31925. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31926. if (BABYLON.Tags) {
  31927. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31928. }
  31929. scene.pushGeometry(sphere, true);
  31930. return sphere;
  31931. };
  31932. return Sphere;
  31933. }(_Primitive));
  31934. Primitives.Sphere = Sphere;
  31935. var Disc = /** @class */ (function (_super) {
  31936. __extends(Disc, _super);
  31937. // Members
  31938. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31939. if (mesh === void 0) { mesh = null; }
  31940. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31941. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31942. _this.radius = radius;
  31943. _this.tessellation = tessellation;
  31944. _this.side = side;
  31945. return _this;
  31946. }
  31947. Disc.prototype._regenerateVertexData = function () {
  31948. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31949. };
  31950. Disc.prototype.copy = function (id) {
  31951. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31952. };
  31953. return Disc;
  31954. }(_Primitive));
  31955. Primitives.Disc = Disc;
  31956. var Cylinder = /** @class */ (function (_super) {
  31957. __extends(Cylinder, _super);
  31958. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31959. if (subdivisions === void 0) { subdivisions = 1; }
  31960. if (mesh === void 0) { mesh = null; }
  31961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31962. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31963. _this.height = height;
  31964. _this.diameterTop = diameterTop;
  31965. _this.diameterBottom = diameterBottom;
  31966. _this.tessellation = tessellation;
  31967. _this.subdivisions = subdivisions;
  31968. _this.side = side;
  31969. return _this;
  31970. }
  31971. Cylinder.prototype._regenerateVertexData = function () {
  31972. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31973. };
  31974. Cylinder.prototype.copy = function (id) {
  31975. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31976. };
  31977. Cylinder.prototype.serialize = function () {
  31978. var serializationObject = _super.prototype.serialize.call(this);
  31979. serializationObject.height = this.height;
  31980. serializationObject.diameterTop = this.diameterTop;
  31981. serializationObject.diameterBottom = this.diameterBottom;
  31982. serializationObject.tessellation = this.tessellation;
  31983. return serializationObject;
  31984. };
  31985. Cylinder.Parse = function (parsedCylinder, scene) {
  31986. if (scene.getGeometryByID(parsedCylinder.id)) {
  31987. return null; // null since geometry could be something else than a cylinder...
  31988. }
  31989. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31990. if (BABYLON.Tags) {
  31991. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31992. }
  31993. scene.pushGeometry(cylinder, true);
  31994. return cylinder;
  31995. };
  31996. return Cylinder;
  31997. }(_Primitive));
  31998. Primitives.Cylinder = Cylinder;
  31999. var Torus = /** @class */ (function (_super) {
  32000. __extends(Torus, _super);
  32001. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32002. if (mesh === void 0) { mesh = null; }
  32003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32005. _this.diameter = diameter;
  32006. _this.thickness = thickness;
  32007. _this.tessellation = tessellation;
  32008. _this.side = side;
  32009. return _this;
  32010. }
  32011. Torus.prototype._regenerateVertexData = function () {
  32012. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32013. };
  32014. Torus.prototype.copy = function (id) {
  32015. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32016. };
  32017. Torus.prototype.serialize = function () {
  32018. var serializationObject = _super.prototype.serialize.call(this);
  32019. serializationObject.diameter = this.diameter;
  32020. serializationObject.thickness = this.thickness;
  32021. serializationObject.tessellation = this.tessellation;
  32022. return serializationObject;
  32023. };
  32024. Torus.Parse = function (parsedTorus, scene) {
  32025. if (scene.getGeometryByID(parsedTorus.id)) {
  32026. return null; // null since geometry could be something else than a torus...
  32027. }
  32028. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32029. if (BABYLON.Tags) {
  32030. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32031. }
  32032. scene.pushGeometry(torus, true);
  32033. return torus;
  32034. };
  32035. return Torus;
  32036. }(_Primitive));
  32037. Primitives.Torus = Torus;
  32038. var Ground = /** @class */ (function (_super) {
  32039. __extends(Ground, _super);
  32040. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32041. if (mesh === void 0) { mesh = null; }
  32042. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32043. _this.width = width;
  32044. _this.height = height;
  32045. _this.subdivisions = subdivisions;
  32046. return _this;
  32047. }
  32048. Ground.prototype._regenerateVertexData = function () {
  32049. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32050. };
  32051. Ground.prototype.copy = function (id) {
  32052. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32053. };
  32054. Ground.prototype.serialize = function () {
  32055. var serializationObject = _super.prototype.serialize.call(this);
  32056. serializationObject.width = this.width;
  32057. serializationObject.height = this.height;
  32058. serializationObject.subdivisions = this.subdivisions;
  32059. return serializationObject;
  32060. };
  32061. Ground.Parse = function (parsedGround, scene) {
  32062. if (scene.getGeometryByID(parsedGround.id)) {
  32063. return null; // null since geometry could be something else than a ground...
  32064. }
  32065. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32066. if (BABYLON.Tags) {
  32067. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32068. }
  32069. scene.pushGeometry(ground, true);
  32070. return ground;
  32071. };
  32072. return Ground;
  32073. }(_Primitive));
  32074. Primitives.Ground = Ground;
  32075. var TiledGround = /** @class */ (function (_super) {
  32076. __extends(TiledGround, _super);
  32077. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32078. if (mesh === void 0) { mesh = null; }
  32079. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32080. _this.xmin = xmin;
  32081. _this.zmin = zmin;
  32082. _this.xmax = xmax;
  32083. _this.zmax = zmax;
  32084. _this.subdivisions = subdivisions;
  32085. _this.precision = precision;
  32086. return _this;
  32087. }
  32088. TiledGround.prototype._regenerateVertexData = function () {
  32089. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32090. };
  32091. TiledGround.prototype.copy = function (id) {
  32092. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32093. };
  32094. return TiledGround;
  32095. }(_Primitive));
  32096. Primitives.TiledGround = TiledGround;
  32097. var Plane = /** @class */ (function (_super) {
  32098. __extends(Plane, _super);
  32099. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32100. if (mesh === void 0) { mesh = null; }
  32101. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32102. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32103. _this.size = size;
  32104. _this.side = side;
  32105. return _this;
  32106. }
  32107. Plane.prototype._regenerateVertexData = function () {
  32108. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32109. };
  32110. Plane.prototype.copy = function (id) {
  32111. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32112. };
  32113. Plane.prototype.serialize = function () {
  32114. var serializationObject = _super.prototype.serialize.call(this);
  32115. serializationObject.size = this.size;
  32116. return serializationObject;
  32117. };
  32118. Plane.Parse = function (parsedPlane, scene) {
  32119. if (scene.getGeometryByID(parsedPlane.id)) {
  32120. return null; // null since geometry could be something else than a ground...
  32121. }
  32122. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32123. if (BABYLON.Tags) {
  32124. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32125. }
  32126. scene.pushGeometry(plane, true);
  32127. return plane;
  32128. };
  32129. return Plane;
  32130. }(_Primitive));
  32131. Primitives.Plane = Plane;
  32132. var TorusKnot = /** @class */ (function (_super) {
  32133. __extends(TorusKnot, _super);
  32134. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32135. if (mesh === void 0) { mesh = null; }
  32136. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32137. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32138. _this.radius = radius;
  32139. _this.tube = tube;
  32140. _this.radialSegments = radialSegments;
  32141. _this.tubularSegments = tubularSegments;
  32142. _this.p = p;
  32143. _this.q = q;
  32144. _this.side = side;
  32145. return _this;
  32146. }
  32147. TorusKnot.prototype._regenerateVertexData = function () {
  32148. 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 });
  32149. };
  32150. TorusKnot.prototype.copy = function (id) {
  32151. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32152. };
  32153. TorusKnot.prototype.serialize = function () {
  32154. var serializationObject = _super.prototype.serialize.call(this);
  32155. serializationObject.radius = this.radius;
  32156. serializationObject.tube = this.tube;
  32157. serializationObject.radialSegments = this.radialSegments;
  32158. serializationObject.tubularSegments = this.tubularSegments;
  32159. serializationObject.p = this.p;
  32160. serializationObject.q = this.q;
  32161. return serializationObject;
  32162. };
  32163. ;
  32164. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32165. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32166. return null; // null since geometry could be something else than a ground...
  32167. }
  32168. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32169. if (BABYLON.Tags) {
  32170. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32171. }
  32172. scene.pushGeometry(torusKnot, true);
  32173. return torusKnot;
  32174. };
  32175. return TorusKnot;
  32176. }(_Primitive));
  32177. Primitives.TorusKnot = TorusKnot;
  32178. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32179. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32180. })(BABYLON || (BABYLON = {}));
  32181. //# sourceMappingURL=babylon.geometry.js.map
  32182. var BABYLON;
  32183. (function (BABYLON) {
  32184. var PostProcessManager = /** @class */ (function () {
  32185. function PostProcessManager(scene) {
  32186. this._vertexBuffers = {};
  32187. this._scene = scene;
  32188. }
  32189. PostProcessManager.prototype._prepareBuffers = function () {
  32190. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32191. return;
  32192. }
  32193. // VBO
  32194. var vertices = [];
  32195. vertices.push(1, 1);
  32196. vertices.push(-1, 1);
  32197. vertices.push(-1, -1);
  32198. vertices.push(1, -1);
  32199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32200. this._buildIndexBuffer();
  32201. };
  32202. PostProcessManager.prototype._buildIndexBuffer = function () {
  32203. // Indices
  32204. var indices = [];
  32205. indices.push(0);
  32206. indices.push(1);
  32207. indices.push(2);
  32208. indices.push(0);
  32209. indices.push(2);
  32210. indices.push(3);
  32211. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32212. };
  32213. PostProcessManager.prototype._rebuild = function () {
  32214. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32215. if (!vb) {
  32216. return;
  32217. }
  32218. vb._rebuild();
  32219. this._buildIndexBuffer();
  32220. };
  32221. // Methods
  32222. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32223. if (sourceTexture === void 0) { sourceTexture = null; }
  32224. if (postProcesses === void 0) { postProcesses = null; }
  32225. var camera = this._scene.activeCamera;
  32226. if (!camera) {
  32227. return false;
  32228. }
  32229. var postProcesses = postProcesses || camera._postProcesses;
  32230. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32231. return false;
  32232. }
  32233. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32234. return true;
  32235. };
  32236. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32237. if (targetTexture === void 0) { targetTexture = null; }
  32238. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32239. var engine = this._scene.getEngine();
  32240. for (var index = 0; index < postProcesses.length; index++) {
  32241. if (index < postProcesses.length - 1) {
  32242. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32243. }
  32244. else {
  32245. if (targetTexture) {
  32246. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32247. }
  32248. else {
  32249. engine.restoreDefaultFramebuffer();
  32250. }
  32251. }
  32252. var pp = postProcesses[index];
  32253. var effect = pp.apply();
  32254. if (effect) {
  32255. pp.onBeforeRenderObservable.notifyObservers(effect);
  32256. // VBOs
  32257. this._prepareBuffers();
  32258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32259. // Draw order
  32260. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32261. pp.onAfterRenderObservable.notifyObservers(effect);
  32262. }
  32263. }
  32264. // Restore depth buffer
  32265. engine.setDepthBuffer(true);
  32266. engine.setDepthWrite(true);
  32267. };
  32268. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32269. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32270. var camera = this._scene.activeCamera;
  32271. if (!camera) {
  32272. return;
  32273. }
  32274. postProcesses = postProcesses || camera._postProcesses;
  32275. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32276. return;
  32277. }
  32278. var engine = this._scene.getEngine();
  32279. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32280. if (index < len - 1) {
  32281. postProcesses[index + 1].activate(camera, targetTexture);
  32282. }
  32283. else {
  32284. if (targetTexture) {
  32285. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32286. }
  32287. else {
  32288. engine.restoreDefaultFramebuffer();
  32289. }
  32290. }
  32291. if (doNotPresent) {
  32292. break;
  32293. }
  32294. var pp = postProcesses[index];
  32295. var effect = pp.apply();
  32296. if (effect) {
  32297. pp.onBeforeRenderObservable.notifyObservers(effect);
  32298. // VBOs
  32299. this._prepareBuffers();
  32300. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32301. // Draw order
  32302. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32303. pp.onAfterRenderObservable.notifyObservers(effect);
  32304. }
  32305. }
  32306. // Restore states
  32307. engine.setDepthBuffer(true);
  32308. engine.setDepthWrite(true);
  32309. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32310. };
  32311. PostProcessManager.prototype.dispose = function () {
  32312. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32313. if (buffer) {
  32314. buffer.dispose();
  32315. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32316. }
  32317. if (this._indexBuffer) {
  32318. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32319. this._indexBuffer = null;
  32320. }
  32321. };
  32322. return PostProcessManager;
  32323. }());
  32324. BABYLON.PostProcessManager = PostProcessManager;
  32325. })(BABYLON || (BABYLON = {}));
  32326. //# sourceMappingURL=babylon.postProcessManager.js.map
  32327. var BABYLON;
  32328. (function (BABYLON) {
  32329. /**
  32330. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32331. */
  32332. var PerformanceMonitor = /** @class */ (function () {
  32333. /**
  32334. * constructor
  32335. * @param frameSampleSize The number of samples required to saturate the sliding window
  32336. */
  32337. function PerformanceMonitor(frameSampleSize) {
  32338. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32339. this._enabled = true;
  32340. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32341. }
  32342. /**
  32343. * Samples current frame
  32344. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32345. */
  32346. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32347. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32348. if (!this._enabled)
  32349. return;
  32350. if (this._lastFrameTimeMs != null) {
  32351. var dt = timeMs - this._lastFrameTimeMs;
  32352. this._rollingFrameTime.add(dt);
  32353. }
  32354. this._lastFrameTimeMs = timeMs;
  32355. };
  32356. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32357. /**
  32358. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32359. * @return Average frame time in milliseconds
  32360. */
  32361. get: function () {
  32362. return this._rollingFrameTime.average;
  32363. },
  32364. enumerable: true,
  32365. configurable: true
  32366. });
  32367. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32368. /**
  32369. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32370. * @return Frame time variance in milliseconds squared
  32371. */
  32372. get: function () {
  32373. return this._rollingFrameTime.variance;
  32374. },
  32375. enumerable: true,
  32376. configurable: true
  32377. });
  32378. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32379. /**
  32380. * Returns the frame time of the most recent frame
  32381. * @return Frame time in milliseconds
  32382. */
  32383. get: function () {
  32384. return this._rollingFrameTime.history(0);
  32385. },
  32386. enumerable: true,
  32387. configurable: true
  32388. });
  32389. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32390. /**
  32391. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32392. * @return Framerate in frames per second
  32393. */
  32394. get: function () {
  32395. return 1000.0 / this._rollingFrameTime.average;
  32396. },
  32397. enumerable: true,
  32398. configurable: true
  32399. });
  32400. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32401. /**
  32402. * Returns the average framerate in frames per second using the most recent frame time
  32403. * @return Framerate in frames per second
  32404. */
  32405. get: function () {
  32406. var history = this._rollingFrameTime.history(0);
  32407. if (history === 0) {
  32408. return 0;
  32409. }
  32410. return 1000.0 / history;
  32411. },
  32412. enumerable: true,
  32413. configurable: true
  32414. });
  32415. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32416. /**
  32417. * Returns true if enough samples have been taken to completely fill the sliding window
  32418. * @return true if saturated
  32419. */
  32420. get: function () {
  32421. return this._rollingFrameTime.isSaturated();
  32422. },
  32423. enumerable: true,
  32424. configurable: true
  32425. });
  32426. /**
  32427. * Enables contributions to the sliding window sample set
  32428. */
  32429. PerformanceMonitor.prototype.enable = function () {
  32430. this._enabled = true;
  32431. };
  32432. /**
  32433. * Disables contributions to the sliding window sample set
  32434. * Samples will not be interpolated over the disabled period
  32435. */
  32436. PerformanceMonitor.prototype.disable = function () {
  32437. this._enabled = false;
  32438. //clear last sample to avoid interpolating over the disabled period when next enabled
  32439. this._lastFrameTimeMs = null;
  32440. };
  32441. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32442. /**
  32443. * Returns true if sampling is enabled
  32444. * @return true if enabled
  32445. */
  32446. get: function () {
  32447. return this._enabled;
  32448. },
  32449. enumerable: true,
  32450. configurable: true
  32451. });
  32452. /**
  32453. * Resets performance monitor
  32454. */
  32455. PerformanceMonitor.prototype.reset = function () {
  32456. //clear last sample to avoid interpolating over the disabled period when next enabled
  32457. this._lastFrameTimeMs = null;
  32458. //wipe record
  32459. this._rollingFrameTime.reset();
  32460. };
  32461. return PerformanceMonitor;
  32462. }());
  32463. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32464. /**
  32465. * RollingAverage
  32466. *
  32467. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32468. */
  32469. var RollingAverage = /** @class */ (function () {
  32470. /**
  32471. * constructor
  32472. * @param length The number of samples required to saturate the sliding window
  32473. */
  32474. function RollingAverage(length) {
  32475. this._samples = new Array(length);
  32476. this.reset();
  32477. }
  32478. /**
  32479. * Adds a sample to the sample set
  32480. * @param v The sample value
  32481. */
  32482. RollingAverage.prototype.add = function (v) {
  32483. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32484. var delta;
  32485. //we need to check if we've already wrapped round
  32486. if (this.isSaturated()) {
  32487. //remove bottom of stack from mean
  32488. var bottomValue = this._samples[this._pos];
  32489. delta = bottomValue - this.average;
  32490. this.average -= delta / (this._sampleCount - 1);
  32491. this._m2 -= delta * (bottomValue - this.average);
  32492. }
  32493. else {
  32494. this._sampleCount++;
  32495. }
  32496. //add new value to mean
  32497. delta = v - this.average;
  32498. this.average += delta / (this._sampleCount);
  32499. this._m2 += delta * (v - this.average);
  32500. //set the new variance
  32501. this.variance = this._m2 / (this._sampleCount - 1);
  32502. this._samples[this._pos] = v;
  32503. this._pos++;
  32504. this._pos %= this._samples.length; //positive wrap around
  32505. };
  32506. /**
  32507. * Returns previously added values or null if outside of history or outside the sliding window domain
  32508. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32509. * @return Value previously recorded with add() or null if outside of range
  32510. */
  32511. RollingAverage.prototype.history = function (i) {
  32512. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32513. return 0;
  32514. }
  32515. var i0 = this._wrapPosition(this._pos - 1.0);
  32516. return this._samples[this._wrapPosition(i0 - i)];
  32517. };
  32518. /**
  32519. * Returns true if enough samples have been taken to completely fill the sliding window
  32520. * @return true if sample-set saturated
  32521. */
  32522. RollingAverage.prototype.isSaturated = function () {
  32523. return this._sampleCount >= this._samples.length;
  32524. };
  32525. /**
  32526. * Resets the rolling average (equivalent to 0 samples taken so far)
  32527. */
  32528. RollingAverage.prototype.reset = function () {
  32529. this.average = 0;
  32530. this.variance = 0;
  32531. this._sampleCount = 0;
  32532. this._pos = 0;
  32533. this._m2 = 0;
  32534. };
  32535. /**
  32536. * Wraps a value around the sample range boundaries
  32537. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32538. * @return Wrapped position in sample range
  32539. */
  32540. RollingAverage.prototype._wrapPosition = function (i) {
  32541. var max = this._samples.length;
  32542. return ((i % max) + max) % max;
  32543. };
  32544. return RollingAverage;
  32545. }());
  32546. BABYLON.RollingAverage = RollingAverage;
  32547. })(BABYLON || (BABYLON = {}));
  32548. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32549. var BABYLON;
  32550. (function (BABYLON) {
  32551. /**
  32552. * This groups together the common properties used for image processing either in direct forward pass
  32553. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32554. * or not.
  32555. */
  32556. var ImageProcessingConfiguration = /** @class */ (function () {
  32557. function ImageProcessingConfiguration() {
  32558. /**
  32559. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32560. */
  32561. this.colorCurves = new BABYLON.ColorCurves();
  32562. this._colorCurvesEnabled = false;
  32563. this._colorGradingEnabled = false;
  32564. this._colorGradingWithGreenDepth = true;
  32565. this._colorGradingBGR = true;
  32566. this._exposure = 1.0;
  32567. this._toneMappingEnabled = false;
  32568. this._contrast = 1.0;
  32569. /**
  32570. * Vignette stretch size.
  32571. */
  32572. this.vignetteStretch = 0;
  32573. /**
  32574. * Vignette centre X Offset.
  32575. */
  32576. this.vignetteCentreX = 0;
  32577. /**
  32578. * Vignette centre Y Offset.
  32579. */
  32580. this.vignetteCentreY = 0;
  32581. /**
  32582. * Vignette weight or intensity of the vignette effect.
  32583. */
  32584. this.vignetteWeight = 1.5;
  32585. /**
  32586. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32587. * if vignetteEnabled is set to true.
  32588. */
  32589. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32590. /**
  32591. * Camera field of view used by the Vignette effect.
  32592. */
  32593. this.vignetteCameraFov = 0.5;
  32594. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32595. this._vignetteEnabled = false;
  32596. this._applyByPostProcess = false;
  32597. this._isEnabled = true;
  32598. /**
  32599. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32600. * @type {BABYLON.Observable}
  32601. */
  32602. this.onUpdateParameters = new BABYLON.Observable();
  32603. }
  32604. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32605. /**
  32606. * Gets wether the color curves effect is enabled.
  32607. */
  32608. get: function () {
  32609. return this._colorCurvesEnabled;
  32610. },
  32611. /**
  32612. * Sets wether the color curves effect is enabled.
  32613. */
  32614. set: function (value) {
  32615. if (this._colorCurvesEnabled === value) {
  32616. return;
  32617. }
  32618. this._colorCurvesEnabled = value;
  32619. this._updateParameters();
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32625. /**
  32626. * Gets wether the color grading effect is enabled.
  32627. */
  32628. get: function () {
  32629. return this._colorGradingEnabled;
  32630. },
  32631. /**
  32632. * Sets wether the color grading effect is enabled.
  32633. */
  32634. set: function (value) {
  32635. if (this._colorGradingEnabled === value) {
  32636. return;
  32637. }
  32638. this._colorGradingEnabled = value;
  32639. this._updateParameters();
  32640. },
  32641. enumerable: true,
  32642. configurable: true
  32643. });
  32644. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32645. /**
  32646. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32647. */
  32648. get: function () {
  32649. return this._colorGradingWithGreenDepth;
  32650. },
  32651. /**
  32652. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32653. */
  32654. set: function (value) {
  32655. if (this._colorGradingWithGreenDepth === value) {
  32656. return;
  32657. }
  32658. this._colorGradingWithGreenDepth = value;
  32659. this._updateParameters();
  32660. },
  32661. enumerable: true,
  32662. configurable: true
  32663. });
  32664. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32665. /**
  32666. * Gets wether the color grading texture contains BGR values.
  32667. */
  32668. get: function () {
  32669. return this._colorGradingBGR;
  32670. },
  32671. /**
  32672. * Sets wether the color grading texture contains BGR values.
  32673. */
  32674. set: function (value) {
  32675. if (this._colorGradingBGR === value) {
  32676. return;
  32677. }
  32678. this._colorGradingBGR = value;
  32679. this._updateParameters();
  32680. },
  32681. enumerable: true,
  32682. configurable: true
  32683. });
  32684. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32685. /**
  32686. * Gets the Exposure used in the effect.
  32687. */
  32688. get: function () {
  32689. return this._exposure;
  32690. },
  32691. /**
  32692. * Sets the Exposure used in the effect.
  32693. */
  32694. set: function (value) {
  32695. if (this._exposure === value) {
  32696. return;
  32697. }
  32698. this._exposure = value;
  32699. this._updateParameters();
  32700. },
  32701. enumerable: true,
  32702. configurable: true
  32703. });
  32704. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32705. /**
  32706. * Gets wether the tone mapping effect is enabled.
  32707. */
  32708. get: function () {
  32709. return this._toneMappingEnabled;
  32710. },
  32711. /**
  32712. * Sets wether the tone mapping effect is enabled.
  32713. */
  32714. set: function (value) {
  32715. if (this._toneMappingEnabled === value) {
  32716. return;
  32717. }
  32718. this._toneMappingEnabled = value;
  32719. this._updateParameters();
  32720. },
  32721. enumerable: true,
  32722. configurable: true
  32723. });
  32724. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32725. /**
  32726. * Gets the contrast used in the effect.
  32727. */
  32728. get: function () {
  32729. return this._contrast;
  32730. },
  32731. /**
  32732. * Sets the contrast used in the effect.
  32733. */
  32734. set: function (value) {
  32735. if (this._contrast === value) {
  32736. return;
  32737. }
  32738. this._contrast = value;
  32739. this._updateParameters();
  32740. },
  32741. enumerable: true,
  32742. configurable: true
  32743. });
  32744. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32745. /**
  32746. * Gets the vignette blend mode allowing different kind of effect.
  32747. */
  32748. get: function () {
  32749. return this._vignetteBlendMode;
  32750. },
  32751. /**
  32752. * Sets the vignette blend mode allowing different kind of effect.
  32753. */
  32754. set: function (value) {
  32755. if (this._vignetteBlendMode === value) {
  32756. return;
  32757. }
  32758. this._vignetteBlendMode = value;
  32759. this._updateParameters();
  32760. },
  32761. enumerable: true,
  32762. configurable: true
  32763. });
  32764. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32765. /**
  32766. * Gets wether the vignette effect is enabled.
  32767. */
  32768. get: function () {
  32769. return this._vignetteEnabled;
  32770. },
  32771. /**
  32772. * Sets wether the vignette effect is enabled.
  32773. */
  32774. set: function (value) {
  32775. if (this._vignetteEnabled === value) {
  32776. return;
  32777. }
  32778. this._vignetteEnabled = value;
  32779. this._updateParameters();
  32780. },
  32781. enumerable: true,
  32782. configurable: true
  32783. });
  32784. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32785. /**
  32786. * Gets wether the image processing is applied through a post process or not.
  32787. */
  32788. get: function () {
  32789. return this._applyByPostProcess;
  32790. },
  32791. /**
  32792. * Sets wether the image processing is applied through a post process or not.
  32793. */
  32794. set: function (value) {
  32795. if (this._applyByPostProcess === value) {
  32796. return;
  32797. }
  32798. this._applyByPostProcess = value;
  32799. this._updateParameters();
  32800. },
  32801. enumerable: true,
  32802. configurable: true
  32803. });
  32804. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32805. /**
  32806. * Gets wether the image processing is enabled or not.
  32807. */
  32808. get: function () {
  32809. return this._isEnabled;
  32810. },
  32811. /**
  32812. * Sets wether the image processing is enabled or not.
  32813. */
  32814. set: function (value) {
  32815. if (this._isEnabled === value) {
  32816. return;
  32817. }
  32818. this._isEnabled = value;
  32819. this._updateParameters();
  32820. },
  32821. enumerable: true,
  32822. configurable: true
  32823. });
  32824. /**
  32825. * Method called each time the image processing information changes requires to recompile the effect.
  32826. */
  32827. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32828. this.onUpdateParameters.notifyObservers(this);
  32829. };
  32830. ImageProcessingConfiguration.prototype.getClassName = function () {
  32831. return "ImageProcessingConfiguration";
  32832. };
  32833. /**
  32834. * Prepare the list of uniforms associated with the Image Processing effects.
  32835. * @param uniformsList The list of uniforms used in the effect
  32836. * @param defines the list of defines currently in use
  32837. */
  32838. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32839. if (defines.EXPOSURE) {
  32840. uniforms.push("exposureLinear");
  32841. }
  32842. if (defines.CONTRAST) {
  32843. uniforms.push("contrast");
  32844. }
  32845. if (defines.COLORGRADING) {
  32846. uniforms.push("colorTransformSettings");
  32847. }
  32848. if (defines.VIGNETTE) {
  32849. uniforms.push("vInverseScreenSize");
  32850. uniforms.push("vignetteSettings1");
  32851. uniforms.push("vignetteSettings2");
  32852. }
  32853. if (defines.COLORCURVES) {
  32854. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32855. }
  32856. };
  32857. /**
  32858. * Prepare the list of samplers associated with the Image Processing effects.
  32859. * @param uniformsList The list of uniforms used in the effect
  32860. * @param defines the list of defines currently in use
  32861. */
  32862. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32863. if (defines.COLORGRADING) {
  32864. samplersList.push("txColorTransform");
  32865. }
  32866. };
  32867. /**
  32868. * Prepare the list of defines associated to the shader.
  32869. * @param defines the list of defines to complete
  32870. */
  32871. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32872. if (forPostProcess === void 0) { forPostProcess = false; }
  32873. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32874. defines.VIGNETTE = false;
  32875. defines.TONEMAPPING = false;
  32876. defines.CONTRAST = false;
  32877. defines.EXPOSURE = false;
  32878. defines.COLORCURVES = false;
  32879. defines.COLORGRADING = false;
  32880. defines.COLORGRADING3D = false;
  32881. defines.IMAGEPROCESSING = false;
  32882. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32883. return;
  32884. }
  32885. defines.VIGNETTE = this.vignetteEnabled;
  32886. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32887. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32888. defines.TONEMAPPING = this.toneMappingEnabled;
  32889. defines.CONTRAST = (this.contrast !== 1.0);
  32890. defines.EXPOSURE = (this.exposure !== 1.0);
  32891. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32892. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32893. if (defines.COLORGRADING) {
  32894. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32895. }
  32896. else {
  32897. defines.COLORGRADING3D = false;
  32898. }
  32899. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32900. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32901. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32902. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32903. };
  32904. /**
  32905. * Returns true if all the image processing information are ready.
  32906. */
  32907. ImageProcessingConfiguration.prototype.isReady = function () {
  32908. // Color Grading texure can not be none blocking.
  32909. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32910. };
  32911. /**
  32912. * Binds the image processing to the shader.
  32913. * @param effect The effect to bind to
  32914. */
  32915. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32916. if (aspectRatio === void 0) { aspectRatio = 1; }
  32917. // Color Curves
  32918. if (this._colorCurvesEnabled && this.colorCurves) {
  32919. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32920. }
  32921. // Vignette
  32922. if (this._vignetteEnabled) {
  32923. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32924. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32925. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32926. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32927. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32928. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32929. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32930. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32931. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32932. var vignettePower = -2.0 * this.vignetteWeight;
  32933. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32934. }
  32935. // Exposure
  32936. effect.setFloat("exposureLinear", this.exposure);
  32937. // Contrast
  32938. effect.setFloat("contrast", this.contrast);
  32939. // Color transform settings
  32940. if (this.colorGradingTexture) {
  32941. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32942. var textureSize = this.colorGradingTexture.getSize().height;
  32943. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32944. 0.5 / textureSize, // textureOffset
  32945. textureSize, // textureSize
  32946. this.colorGradingTexture.level // weight
  32947. );
  32948. }
  32949. };
  32950. /**
  32951. * Clones the current image processing instance.
  32952. * @return The cloned image processing
  32953. */
  32954. ImageProcessingConfiguration.prototype.clone = function () {
  32955. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32956. };
  32957. /**
  32958. * Serializes the current image processing instance to a json representation.
  32959. * @return a JSON representation
  32960. */
  32961. ImageProcessingConfiguration.prototype.serialize = function () {
  32962. return BABYLON.SerializationHelper.Serialize(this);
  32963. };
  32964. /**
  32965. * Parses the image processing from a json representation.
  32966. * @param source the JSON source to parse
  32967. * @return The parsed image processing
  32968. */
  32969. ImageProcessingConfiguration.Parse = function (source) {
  32970. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32971. };
  32972. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32973. /**
  32974. * Used to apply the vignette as a mix with the pixel color.
  32975. */
  32976. get: function () {
  32977. return this._VIGNETTEMODE_MULTIPLY;
  32978. },
  32979. enumerable: true,
  32980. configurable: true
  32981. });
  32982. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32983. /**
  32984. * Used to apply the vignette as a replacement of the pixel color.
  32985. */
  32986. get: function () {
  32987. return this._VIGNETTEMODE_OPAQUE;
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. // Static constants associated to the image processing.
  32993. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32994. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32995. __decorate([
  32996. BABYLON.serializeAsColorCurves()
  32997. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32998. __decorate([
  32999. BABYLON.serialize()
  33000. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33001. __decorate([
  33002. BABYLON.serializeAsTexture()
  33003. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33004. __decorate([
  33005. BABYLON.serialize()
  33006. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33007. __decorate([
  33008. BABYLON.serialize()
  33009. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33010. __decorate([
  33011. BABYLON.serialize()
  33012. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33013. __decorate([
  33014. BABYLON.serialize()
  33015. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33016. __decorate([
  33017. BABYLON.serialize()
  33018. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33019. __decorate([
  33020. BABYLON.serialize()
  33021. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33022. __decorate([
  33023. BABYLON.serialize()
  33024. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33025. __decorate([
  33026. BABYLON.serialize()
  33027. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33028. __decorate([
  33029. BABYLON.serialize()
  33030. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33031. __decorate([
  33032. BABYLON.serialize()
  33033. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33034. __decorate([
  33035. BABYLON.serializeAsColor4()
  33036. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33037. __decorate([
  33038. BABYLON.serialize()
  33039. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33040. __decorate([
  33041. BABYLON.serialize()
  33042. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33043. __decorate([
  33044. BABYLON.serialize()
  33045. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33046. __decorate([
  33047. BABYLON.serialize()
  33048. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33049. __decorate([
  33050. BABYLON.serialize()
  33051. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33052. return ImageProcessingConfiguration;
  33053. }());
  33054. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33055. })(BABYLON || (BABYLON = {}));
  33056. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33057. var BABYLON;
  33058. (function (BABYLON) {
  33059. /**
  33060. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33061. * It can help converting any input color in a desired output one. This can then be used to create effects
  33062. * from sepia, black and white to sixties or futuristic rendering...
  33063. *
  33064. * The only supported format is currently 3dl.
  33065. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33066. */
  33067. var ColorGradingTexture = /** @class */ (function (_super) {
  33068. __extends(ColorGradingTexture, _super);
  33069. /**
  33070. * Instantiates a ColorGradingTexture from the following parameters.
  33071. *
  33072. * @param url The location of the color gradind data (currently only supporting 3dl)
  33073. * @param scene The scene the texture will be used in
  33074. */
  33075. function ColorGradingTexture(url, scene) {
  33076. var _this = _super.call(this, scene) || this;
  33077. if (!url) {
  33078. return _this;
  33079. }
  33080. _this._engine = scene.getEngine();
  33081. _this._textureMatrix = BABYLON.Matrix.Identity();
  33082. _this.name = url;
  33083. _this.url = url;
  33084. _this.hasAlpha = false;
  33085. _this.isCube = false;
  33086. _this.is3D = _this._engine.webGLVersion > 1;
  33087. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33088. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33089. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33090. _this.anisotropicFilteringLevel = 1;
  33091. _this._texture = _this._getFromCache(url, true);
  33092. if (!_this._texture) {
  33093. if (!scene.useDelayedTextureLoading) {
  33094. _this.loadTexture();
  33095. }
  33096. else {
  33097. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33098. }
  33099. }
  33100. return _this;
  33101. }
  33102. /**
  33103. * Returns the texture matrix used in most of the material.
  33104. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33105. */
  33106. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33107. return this._textureMatrix;
  33108. };
  33109. /**
  33110. * Occurs when the file being loaded is a .3dl LUT file.
  33111. */
  33112. ColorGradingTexture.prototype.load3dlTexture = function () {
  33113. var engine = this._engine;
  33114. var texture;
  33115. if (engine.webGLVersion === 1) {
  33116. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33117. }
  33118. else {
  33119. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33120. }
  33121. this._texture = texture;
  33122. var callback = function (text) {
  33123. if (typeof text !== "string") {
  33124. return;
  33125. }
  33126. var data = null;
  33127. var tempData = null;
  33128. var line;
  33129. var lines = text.split('\n');
  33130. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33131. var maxColor = 0;
  33132. for (var i = 0; i < lines.length; i++) {
  33133. line = lines[i];
  33134. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33135. continue;
  33136. if (line.indexOf('#') === 0)
  33137. continue;
  33138. var words = line.split(" ");
  33139. if (size === 0) {
  33140. // Number of space + one
  33141. size = words.length;
  33142. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33143. tempData = new Float32Array(size * size * size * 4);
  33144. continue;
  33145. }
  33146. if (size != 0) {
  33147. var r = Math.max(parseInt(words[0]), 0);
  33148. var g = Math.max(parseInt(words[1]), 0);
  33149. var b = Math.max(parseInt(words[2]), 0);
  33150. maxColor = Math.max(r, maxColor);
  33151. maxColor = Math.max(g, maxColor);
  33152. maxColor = Math.max(b, maxColor);
  33153. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33154. if (tempData) {
  33155. tempData[pixelStorageIndex + 0] = r;
  33156. tempData[pixelStorageIndex + 1] = g;
  33157. tempData[pixelStorageIndex + 2] = b;
  33158. }
  33159. pixelIndexSlice++;
  33160. if (pixelIndexSlice % size == 0) {
  33161. pixelIndexH++;
  33162. pixelIndexSlice = 0;
  33163. if (pixelIndexH % size == 0) {
  33164. pixelIndexW++;
  33165. pixelIndexH = 0;
  33166. }
  33167. }
  33168. }
  33169. }
  33170. if (tempData && data) {
  33171. for (var i = 0; i < tempData.length; i++) {
  33172. if (i > 0 && (i + 1) % 4 === 0) {
  33173. data[i] = 255;
  33174. }
  33175. else {
  33176. var value = tempData[i];
  33177. data[i] = (value / maxColor * 255);
  33178. }
  33179. }
  33180. }
  33181. if (texture.is3D) {
  33182. texture.updateSize(size, size, size);
  33183. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33184. }
  33185. else {
  33186. texture.updateSize(size * size, size);
  33187. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33188. }
  33189. };
  33190. BABYLON.Tools.LoadFile(this.url, callback);
  33191. return this._texture;
  33192. };
  33193. /**
  33194. * Starts the loading process of the texture.
  33195. */
  33196. ColorGradingTexture.prototype.loadTexture = function () {
  33197. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33198. this.load3dlTexture();
  33199. }
  33200. };
  33201. /**
  33202. * Clones the color gradind texture.
  33203. */
  33204. ColorGradingTexture.prototype.clone = function () {
  33205. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33206. // Base texture
  33207. newTexture.level = this.level;
  33208. return newTexture;
  33209. };
  33210. /**
  33211. * Called during delayed load for textures.
  33212. */
  33213. ColorGradingTexture.prototype.delayLoad = function () {
  33214. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33215. return;
  33216. }
  33217. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33218. this._texture = this._getFromCache(this.url, true);
  33219. if (!this._texture) {
  33220. this.loadTexture();
  33221. }
  33222. };
  33223. /**
  33224. * Parses a color grading texture serialized by Babylon.
  33225. * @param parsedTexture The texture information being parsedTexture
  33226. * @param scene The scene to load the texture in
  33227. * @param rootUrl The root url of the data assets to load
  33228. * @return A color gradind texture
  33229. */
  33230. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33231. var texture = null;
  33232. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33233. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33234. texture.name = parsedTexture.name;
  33235. texture.level = parsedTexture.level;
  33236. }
  33237. return texture;
  33238. };
  33239. /**
  33240. * Serializes the LUT texture to json format.
  33241. */
  33242. ColorGradingTexture.prototype.serialize = function () {
  33243. if (!this.name) {
  33244. return null;
  33245. }
  33246. var serializationObject = {};
  33247. serializationObject.name = this.name;
  33248. serializationObject.level = this.level;
  33249. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33250. return serializationObject;
  33251. };
  33252. /**
  33253. * Empty line regex stored for GC.
  33254. */
  33255. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33256. return ColorGradingTexture;
  33257. }(BABYLON.BaseTexture));
  33258. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33259. })(BABYLON || (BABYLON = {}));
  33260. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33261. var BABYLON;
  33262. (function (BABYLON) {
  33263. /**
  33264. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33265. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33266. * 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;
  33267. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33268. */
  33269. var ColorCurves = /** @class */ (function () {
  33270. function ColorCurves() {
  33271. this._dirty = true;
  33272. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33273. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33274. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33275. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33276. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33277. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33278. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33279. this._globalHue = 30;
  33280. this._globalDensity = 0;
  33281. this._globalSaturation = 0;
  33282. this._globalExposure = 0;
  33283. this._highlightsHue = 30;
  33284. this._highlightsDensity = 0;
  33285. this._highlightsSaturation = 0;
  33286. this._highlightsExposure = 0;
  33287. this._midtonesHue = 30;
  33288. this._midtonesDensity = 0;
  33289. this._midtonesSaturation = 0;
  33290. this._midtonesExposure = 0;
  33291. this._shadowsHue = 30;
  33292. this._shadowsDensity = 0;
  33293. this._shadowsSaturation = 0;
  33294. this._shadowsExposure = 0;
  33295. }
  33296. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33297. /**
  33298. * Gets the global Hue value.
  33299. * 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).
  33300. */
  33301. get: function () {
  33302. return this._globalHue;
  33303. },
  33304. /**
  33305. * Sets the global Hue value.
  33306. * 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).
  33307. */
  33308. set: function (value) {
  33309. this._globalHue = value;
  33310. this._dirty = true;
  33311. },
  33312. enumerable: true,
  33313. configurable: true
  33314. });
  33315. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33316. /**
  33317. * Gets the global Density value.
  33318. * 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.
  33319. * Values less than zero provide a filter of opposite hue.
  33320. */
  33321. get: function () {
  33322. return this._globalDensity;
  33323. },
  33324. /**
  33325. * Sets the global Density value.
  33326. * 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.
  33327. * Values less than zero provide a filter of opposite hue.
  33328. */
  33329. set: function (value) {
  33330. this._globalDensity = value;
  33331. this._dirty = true;
  33332. },
  33333. enumerable: true,
  33334. configurable: true
  33335. });
  33336. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33337. /**
  33338. * Gets the global Saturation value.
  33339. * 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.
  33340. */
  33341. get: function () {
  33342. return this._globalSaturation;
  33343. },
  33344. /**
  33345. * Sets the global Saturation value.
  33346. * 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.
  33347. */
  33348. set: function (value) {
  33349. this._globalSaturation = value;
  33350. this._dirty = true;
  33351. },
  33352. enumerable: true,
  33353. configurable: true
  33354. });
  33355. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33356. /**
  33357. * Gets the highlights Hue value.
  33358. * 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).
  33359. */
  33360. get: function () {
  33361. return this._highlightsHue;
  33362. },
  33363. /**
  33364. * Sets the highlights Hue value.
  33365. * 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).
  33366. */
  33367. set: function (value) {
  33368. this._highlightsHue = value;
  33369. this._dirty = true;
  33370. },
  33371. enumerable: true,
  33372. configurable: true
  33373. });
  33374. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33375. /**
  33376. * Gets the highlights Density value.
  33377. * 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.
  33378. * Values less than zero provide a filter of opposite hue.
  33379. */
  33380. get: function () {
  33381. return this._highlightsDensity;
  33382. },
  33383. /**
  33384. * Sets the highlights Density value.
  33385. * 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.
  33386. * Values less than zero provide a filter of opposite hue.
  33387. */
  33388. set: function (value) {
  33389. this._highlightsDensity = value;
  33390. this._dirty = true;
  33391. },
  33392. enumerable: true,
  33393. configurable: true
  33394. });
  33395. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33396. /**
  33397. * Gets the highlights Saturation value.
  33398. * 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.
  33399. */
  33400. get: function () {
  33401. return this._highlightsSaturation;
  33402. },
  33403. /**
  33404. * Sets the highlights Saturation value.
  33405. * 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.
  33406. */
  33407. set: function (value) {
  33408. this._highlightsSaturation = value;
  33409. this._dirty = true;
  33410. },
  33411. enumerable: true,
  33412. configurable: true
  33413. });
  33414. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33415. /**
  33416. * Gets the highlights Exposure value.
  33417. * 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.
  33418. */
  33419. get: function () {
  33420. return this._highlightsExposure;
  33421. },
  33422. /**
  33423. * Sets the highlights Exposure value.
  33424. * 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.
  33425. */
  33426. set: function (value) {
  33427. this._highlightsExposure = value;
  33428. this._dirty = true;
  33429. },
  33430. enumerable: true,
  33431. configurable: true
  33432. });
  33433. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33434. /**
  33435. * Gets the midtones Hue value.
  33436. * 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).
  33437. */
  33438. get: function () {
  33439. return this._midtonesHue;
  33440. },
  33441. /**
  33442. * Sets the midtones Hue value.
  33443. * 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).
  33444. */
  33445. set: function (value) {
  33446. this._midtonesHue = value;
  33447. this._dirty = true;
  33448. },
  33449. enumerable: true,
  33450. configurable: true
  33451. });
  33452. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33453. /**
  33454. * Gets the midtones Density value.
  33455. * 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.
  33456. * Values less than zero provide a filter of opposite hue.
  33457. */
  33458. get: function () {
  33459. return this._midtonesDensity;
  33460. },
  33461. /**
  33462. * Sets the midtones Density value.
  33463. * 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.
  33464. * Values less than zero provide a filter of opposite hue.
  33465. */
  33466. set: function (value) {
  33467. this._midtonesDensity = value;
  33468. this._dirty = true;
  33469. },
  33470. enumerable: true,
  33471. configurable: true
  33472. });
  33473. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33474. /**
  33475. * Gets the midtones Saturation value.
  33476. * 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.
  33477. */
  33478. get: function () {
  33479. return this._midtonesSaturation;
  33480. },
  33481. /**
  33482. * Sets the midtones Saturation value.
  33483. * 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.
  33484. */
  33485. set: function (value) {
  33486. this._midtonesSaturation = value;
  33487. this._dirty = true;
  33488. },
  33489. enumerable: true,
  33490. configurable: true
  33491. });
  33492. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33493. /**
  33494. * Gets the midtones Exposure value.
  33495. * 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.
  33496. */
  33497. get: function () {
  33498. return this._midtonesExposure;
  33499. },
  33500. /**
  33501. * Sets the midtones Exposure value.
  33502. * 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.
  33503. */
  33504. set: function (value) {
  33505. this._midtonesExposure = value;
  33506. this._dirty = true;
  33507. },
  33508. enumerable: true,
  33509. configurable: true
  33510. });
  33511. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33512. /**
  33513. * Gets the shadows Hue value.
  33514. * 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).
  33515. */
  33516. get: function () {
  33517. return this._shadowsHue;
  33518. },
  33519. /**
  33520. * Sets the shadows Hue value.
  33521. * 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).
  33522. */
  33523. set: function (value) {
  33524. this._shadowsHue = value;
  33525. this._dirty = true;
  33526. },
  33527. enumerable: true,
  33528. configurable: true
  33529. });
  33530. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33531. /**
  33532. * Gets the shadows Density value.
  33533. * 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.
  33534. * Values less than zero provide a filter of opposite hue.
  33535. */
  33536. get: function () {
  33537. return this._shadowsDensity;
  33538. },
  33539. /**
  33540. * Sets the shadows Density value.
  33541. * 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.
  33542. * Values less than zero provide a filter of opposite hue.
  33543. */
  33544. set: function (value) {
  33545. this._shadowsDensity = value;
  33546. this._dirty = true;
  33547. },
  33548. enumerable: true,
  33549. configurable: true
  33550. });
  33551. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33552. /**
  33553. * Gets the shadows Saturation value.
  33554. * 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.
  33555. */
  33556. get: function () {
  33557. return this._shadowsSaturation;
  33558. },
  33559. /**
  33560. * Sets the shadows Saturation value.
  33561. * 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.
  33562. */
  33563. set: function (value) {
  33564. this._shadowsSaturation = value;
  33565. this._dirty = true;
  33566. },
  33567. enumerable: true,
  33568. configurable: true
  33569. });
  33570. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33571. /**
  33572. * Gets the shadows Exposure value.
  33573. * 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.
  33574. */
  33575. get: function () {
  33576. return this._shadowsExposure;
  33577. },
  33578. /**
  33579. * Sets the shadows Exposure value.
  33580. * 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.
  33581. */
  33582. set: function (value) {
  33583. this._shadowsExposure = value;
  33584. this._dirty = true;
  33585. },
  33586. enumerable: true,
  33587. configurable: true
  33588. });
  33589. ColorCurves.prototype.getClassName = function () {
  33590. return "ColorCurves";
  33591. };
  33592. /**
  33593. * Binds the color curves to the shader.
  33594. * @param colorCurves The color curve to bind
  33595. * @param effect The effect to bind to
  33596. */
  33597. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33598. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33599. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33600. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33601. if (colorCurves._dirty) {
  33602. colorCurves._dirty = false;
  33603. // Fill in global info.
  33604. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33605. // Compute highlights info.
  33606. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33607. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33608. // Compute midtones info.
  33609. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33610. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33611. // Compute shadows info.
  33612. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33613. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33614. // Compute deltas (neutral is midtones).
  33615. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33616. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33617. }
  33618. if (effect) {
  33619. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33620. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33621. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33622. }
  33623. };
  33624. /**
  33625. * Prepare the list of uniforms associated with the ColorCurves effects.
  33626. * @param uniformsList The list of uniforms used in the effect
  33627. */
  33628. ColorCurves.PrepareUniforms = function (uniformsList) {
  33629. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33630. };
  33631. /**
  33632. * Returns color grading data based on a hue, density, saturation and exposure value.
  33633. * @param filterHue The hue of the color filter.
  33634. * @param filterDensity The density of the color filter.
  33635. * @param saturation The saturation.
  33636. * @param exposure The exposure.
  33637. * @param result The result data container.
  33638. */
  33639. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33640. if (hue == null) {
  33641. return;
  33642. }
  33643. hue = ColorCurves.clamp(hue, 0, 360);
  33644. density = ColorCurves.clamp(density, -100, 100);
  33645. saturation = ColorCurves.clamp(saturation, -100, 100);
  33646. exposure = ColorCurves.clamp(exposure, -100, 100);
  33647. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33648. // so that the maximum filter density is only 50% control. This provides fine control
  33649. // for small values and reasonable range.
  33650. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33651. density *= 0.5;
  33652. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33653. if (density < 0) {
  33654. density *= -1;
  33655. hue = (hue + 180) % 360;
  33656. }
  33657. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33658. result.scaleToRef(2, result);
  33659. result.a = 1 + 0.01 * saturation;
  33660. };
  33661. /**
  33662. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33663. * @param value The input slider value in range [-100,100].
  33664. * @returns Adjusted value.
  33665. */
  33666. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33667. value /= 100;
  33668. var x = Math.abs(value);
  33669. x = Math.pow(x, 2);
  33670. if (value < 0) {
  33671. x *= -1;
  33672. }
  33673. x *= 100;
  33674. return x;
  33675. };
  33676. /**
  33677. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33678. * @param hue The hue (H) input.
  33679. * @param saturation The saturation (S) input.
  33680. * @param brightness The brightness (B) input.
  33681. * @result An RGBA color represented as Vector4.
  33682. */
  33683. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33684. var h = ColorCurves.clamp(hue, 0, 360);
  33685. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33686. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33687. if (s === 0) {
  33688. result.r = v;
  33689. result.g = v;
  33690. result.b = v;
  33691. }
  33692. else {
  33693. // sector 0 to 5
  33694. h /= 60;
  33695. var i = Math.floor(h);
  33696. // fractional part of h
  33697. var f = h - i;
  33698. var p = v * (1 - s);
  33699. var q = v * (1 - s * f);
  33700. var t = v * (1 - s * (1 - f));
  33701. switch (i) {
  33702. case 0:
  33703. result.r = v;
  33704. result.g = t;
  33705. result.b = p;
  33706. break;
  33707. case 1:
  33708. result.r = q;
  33709. result.g = v;
  33710. result.b = p;
  33711. break;
  33712. case 2:
  33713. result.r = p;
  33714. result.g = v;
  33715. result.b = t;
  33716. break;
  33717. case 3:
  33718. result.r = p;
  33719. result.g = q;
  33720. result.b = v;
  33721. break;
  33722. case 4:
  33723. result.r = t;
  33724. result.g = p;
  33725. result.b = v;
  33726. break;
  33727. default:// case 5:
  33728. result.r = v;
  33729. result.g = p;
  33730. result.b = q;
  33731. break;
  33732. }
  33733. }
  33734. result.a = 1;
  33735. };
  33736. /**
  33737. * Returns a value clamped between min and max
  33738. * @param value The value to clamp
  33739. * @param min The minimum of value
  33740. * @param max The maximum of value
  33741. * @returns The clamped value.
  33742. */
  33743. ColorCurves.clamp = function (value, min, max) {
  33744. return Math.min(Math.max(value, min), max);
  33745. };
  33746. /**
  33747. * Clones the current color curve instance.
  33748. * @return The cloned curves
  33749. */
  33750. ColorCurves.prototype.clone = function () {
  33751. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33752. };
  33753. /**
  33754. * Serializes the current color curve instance to a json representation.
  33755. * @return a JSON representation
  33756. */
  33757. ColorCurves.prototype.serialize = function () {
  33758. return BABYLON.SerializationHelper.Serialize(this);
  33759. };
  33760. /**
  33761. * Parses the color curve from a json representation.
  33762. * @param source the JSON source to parse
  33763. * @return The parsed curves
  33764. */
  33765. ColorCurves.Parse = function (source) {
  33766. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33767. };
  33768. __decorate([
  33769. BABYLON.serialize()
  33770. ], ColorCurves.prototype, "_globalHue", void 0);
  33771. __decorate([
  33772. BABYLON.serialize()
  33773. ], ColorCurves.prototype, "_globalDensity", void 0);
  33774. __decorate([
  33775. BABYLON.serialize()
  33776. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33777. __decorate([
  33778. BABYLON.serialize()
  33779. ], ColorCurves.prototype, "_globalExposure", void 0);
  33780. __decorate([
  33781. BABYLON.serialize()
  33782. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33783. __decorate([
  33784. BABYLON.serialize()
  33785. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33786. __decorate([
  33787. BABYLON.serialize()
  33788. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33789. __decorate([
  33790. BABYLON.serialize()
  33791. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33792. __decorate([
  33793. BABYLON.serialize()
  33794. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33795. __decorate([
  33796. BABYLON.serialize()
  33797. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33798. __decorate([
  33799. BABYLON.serialize()
  33800. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33801. __decorate([
  33802. BABYLON.serialize()
  33803. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33804. return ColorCurves;
  33805. }());
  33806. BABYLON.ColorCurves = ColorCurves;
  33807. })(BABYLON || (BABYLON = {}));
  33808. //# sourceMappingURL=babylon.colorCurves.js.map
  33809. var BABYLON;
  33810. (function (BABYLON) {
  33811. var MaterialHelper = /** @class */ (function () {
  33812. function MaterialHelper() {
  33813. }
  33814. MaterialHelper.BindEyePosition = function (effect, scene) {
  33815. if (scene._forcedViewPosition) {
  33816. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  33817. return;
  33818. }
  33819. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33820. };
  33821. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  33822. defines._needUVs = true;
  33823. defines[key] = true;
  33824. if (texture.getTextureMatrix().isIdentity(true)) {
  33825. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  33826. if (texture.coordinatesIndex === 0) {
  33827. defines["MAINUV1"] = true;
  33828. }
  33829. else {
  33830. defines["MAINUV2"] = true;
  33831. }
  33832. }
  33833. else {
  33834. defines[key + "DIRECTUV"] = 0;
  33835. }
  33836. };
  33837. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  33838. var matrix = texture.getTextureMatrix();
  33839. if (!matrix.isIdentity(true)) {
  33840. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  33841. }
  33842. };
  33843. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  33844. if (defines._areMiscDirty) {
  33845. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  33846. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  33847. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  33848. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  33849. }
  33850. };
  33851. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  33852. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  33853. var changed = false;
  33854. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  33855. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  33856. changed = true;
  33857. }
  33858. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  33859. defines["ALPHATEST"] = !defines["ALPHATEST"];
  33860. changed = true;
  33861. }
  33862. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  33863. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  33864. changed = true;
  33865. }
  33866. if (defines["INSTANCES"] !== useInstances) {
  33867. defines["INSTANCES"] = useInstances;
  33868. changed = true;
  33869. }
  33870. if (changed) {
  33871. defines.markAsUnprocessed();
  33872. }
  33873. };
  33874. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  33875. if (useMorphTargets === void 0) { useMorphTargets = false; }
  33876. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  33877. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  33878. return false;
  33879. }
  33880. defines._normals = defines._needNormals;
  33881. defines._uvs = defines._needUVs;
  33882. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  33883. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33884. defines["TANGENT"] = true;
  33885. }
  33886. if (defines._needUVs) {
  33887. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  33888. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  33889. }
  33890. else {
  33891. defines["UV1"] = false;
  33892. defines["UV2"] = false;
  33893. }
  33894. if (useVertexColor) {
  33895. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  33896. defines["VERTEXCOLOR"] = hasVertexColors;
  33897. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  33898. }
  33899. if (useBones) {
  33900. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  33901. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  33902. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  33903. }
  33904. else {
  33905. defines["NUM_BONE_INFLUENCERS"] = 0;
  33906. defines["BonesPerMesh"] = 0;
  33907. }
  33908. }
  33909. if (useMorphTargets) {
  33910. var manager = mesh.morphTargetManager;
  33911. if (manager) {
  33912. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  33913. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  33914. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  33915. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  33916. }
  33917. else {
  33918. defines["MORPHTARGETS_TANGENT"] = false;
  33919. defines["MORPHTARGETS_NORMAL"] = false;
  33920. defines["MORPHTARGETS"] = false;
  33921. defines["NUM_MORPH_INFLUENCERS"] = 0;
  33922. }
  33923. }
  33924. return true;
  33925. };
  33926. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  33927. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  33928. if (disableLighting === void 0) { disableLighting = false; }
  33929. if (!defines._areLightsDirty) {
  33930. return defines._needNormals;
  33931. }
  33932. var lightIndex = 0;
  33933. var needNormals = false;
  33934. var needRebuild = false;
  33935. var lightmapMode = false;
  33936. var shadowEnabled = false;
  33937. var specularEnabled = false;
  33938. if (scene.lightsEnabled && !disableLighting) {
  33939. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  33940. var light = _a[_i];
  33941. needNormals = true;
  33942. if (defines["LIGHT" + lightIndex] === undefined) {
  33943. needRebuild = true;
  33944. }
  33945. defines["LIGHT" + lightIndex] = true;
  33946. defines["SPOTLIGHT" + lightIndex] = false;
  33947. defines["HEMILIGHT" + lightIndex] = false;
  33948. defines["POINTLIGHT" + lightIndex] = false;
  33949. defines["DIRLIGHT" + lightIndex] = false;
  33950. var type;
  33951. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  33952. type = "SPOTLIGHT" + lightIndex;
  33953. }
  33954. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  33955. type = "HEMILIGHT" + lightIndex;
  33956. }
  33957. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  33958. type = "POINTLIGHT" + lightIndex;
  33959. }
  33960. else {
  33961. type = "DIRLIGHT" + lightIndex;
  33962. }
  33963. defines[type] = true;
  33964. // Specular
  33965. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  33966. specularEnabled = true;
  33967. }
  33968. // Shadows
  33969. defines["SHADOW" + lightIndex] = false;
  33970. defines["SHADOWPCF" + lightIndex] = false;
  33971. defines["SHADOWESM" + lightIndex] = false;
  33972. defines["SHADOWCUBE" + lightIndex] = false;
  33973. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  33974. var shadowGenerator = light.getShadowGenerator();
  33975. if (shadowGenerator) {
  33976. shadowEnabled = true;
  33977. shadowGenerator.prepareDefines(defines, lightIndex);
  33978. }
  33979. }
  33980. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  33981. lightmapMode = true;
  33982. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  33983. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  33984. }
  33985. else {
  33986. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  33987. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  33988. }
  33989. lightIndex++;
  33990. if (lightIndex === maxSimultaneousLights)
  33991. break;
  33992. }
  33993. }
  33994. defines["SPECULARTERM"] = specularEnabled;
  33995. defines["SHADOWS"] = shadowEnabled;
  33996. // Resetting all other lights if any
  33997. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  33998. if (defines["LIGHT" + index] !== undefined) {
  33999. defines["LIGHT" + index] = false;
  34000. defines["HEMILIGHT" + lightIndex] = false;
  34001. defines["POINTLIGHT" + lightIndex] = false;
  34002. defines["DIRLIGHT" + lightIndex] = false;
  34003. defines["SPOTLIGHT" + lightIndex] = false;
  34004. defines["SHADOW" + lightIndex] = false;
  34005. }
  34006. }
  34007. var caps = scene.getEngine().getCaps();
  34008. if (defines["SHADOWFLOAT"] === undefined) {
  34009. needRebuild = true;
  34010. }
  34011. defines["SHADOWFLOAT"] = shadowEnabled &&
  34012. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34013. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34014. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34015. if (needRebuild) {
  34016. defines.rebuild();
  34017. }
  34018. return needNormals;
  34019. };
  34020. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34021. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34022. var uniformsList;
  34023. var uniformBuffersList = null;
  34024. if (uniformsListOrOptions.uniformsNames) {
  34025. var options = uniformsListOrOptions;
  34026. uniformsList = options.uniformsNames;
  34027. uniformBuffersList = options.uniformBuffersNames;
  34028. samplersList = options.samplers;
  34029. defines = options.defines;
  34030. maxSimultaneousLights = options.maxSimultaneousLights;
  34031. }
  34032. else {
  34033. uniformsList = uniformsListOrOptions;
  34034. if (!samplersList) {
  34035. samplersList = [];
  34036. }
  34037. }
  34038. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34039. if (!defines["LIGHT" + lightIndex]) {
  34040. break;
  34041. }
  34042. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34043. if (uniformBuffersList) {
  34044. uniformBuffersList.push("Light" + lightIndex);
  34045. }
  34046. samplersList.push("shadowSampler" + lightIndex);
  34047. }
  34048. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34049. uniformsList.push("morphTargetInfluences");
  34050. }
  34051. };
  34052. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34053. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34054. if (rank === void 0) { rank = 0; }
  34055. var lightFallbackRank = 0;
  34056. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34057. if (!defines["LIGHT" + lightIndex]) {
  34058. break;
  34059. }
  34060. if (lightIndex > 0) {
  34061. lightFallbackRank = rank + lightIndex;
  34062. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34063. }
  34064. if (!defines["SHADOWS"]) {
  34065. if (defines["SHADOW" + lightIndex]) {
  34066. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34067. }
  34068. if (defines["SHADOWPCF" + lightIndex]) {
  34069. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34070. }
  34071. if (defines["SHADOWESM" + lightIndex]) {
  34072. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34073. }
  34074. }
  34075. }
  34076. return lightFallbackRank++;
  34077. };
  34078. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34079. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34080. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34081. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34082. var manager = mesh.morphTargetManager;
  34083. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34084. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34085. for (var index = 0; index < influencers; index++) {
  34086. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34087. if (normal) {
  34088. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34089. }
  34090. if (tangent) {
  34091. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34092. }
  34093. if (attribs.length > maxAttributesCount) {
  34094. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34095. }
  34096. }
  34097. }
  34098. };
  34099. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34100. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34101. fallbacks.addCPUSkinningFallback(0, mesh);
  34102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34104. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34107. }
  34108. }
  34109. };
  34110. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34111. if (defines["INSTANCES"]) {
  34112. attribs.push("world0");
  34113. attribs.push("world1");
  34114. attribs.push("world2");
  34115. attribs.push("world3");
  34116. }
  34117. };
  34118. // Bindings
  34119. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34120. if (light.shadowEnabled && mesh.receiveShadows) {
  34121. var shadowGenerator = light.getShadowGenerator();
  34122. if (shadowGenerator) {
  34123. shadowGenerator.bindShadowLight(lightIndex, effect);
  34124. }
  34125. }
  34126. };
  34127. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34128. light.transferToEffect(effect, lightIndex + "");
  34129. };
  34130. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34131. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34132. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34133. var lightIndex = 0;
  34134. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34135. var light = _a[_i];
  34136. var scaledIntensity = light.getScaledIntensity();
  34137. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34138. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34139. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34140. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  34141. if (defines["SPECULARTERM"]) {
  34142. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34143. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  34144. }
  34145. // Shadows
  34146. if (scene.shadowsEnabled) {
  34147. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34148. }
  34149. light._uniformBuffer.update();
  34150. lightIndex++;
  34151. if (lightIndex === maxSimultaneousLights)
  34152. break;
  34153. }
  34154. };
  34155. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34156. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34157. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34158. effect.setColor3("vFogColor", scene.fogColor);
  34159. }
  34160. };
  34161. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34162. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34163. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34164. if (matrices && effect) {
  34165. effect.setMatrices("mBones", matrices);
  34166. }
  34167. }
  34168. };
  34169. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34170. var manager = abstractMesh.morphTargetManager;
  34171. if (!abstractMesh || !manager) {
  34172. return;
  34173. }
  34174. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34175. };
  34176. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34177. if (defines["LOGARITHMICDEPTH"]) {
  34178. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34179. }
  34180. };
  34181. MaterialHelper.BindClipPlane = function (effect, scene) {
  34182. if (scene.clipPlane) {
  34183. var clipPlane = scene.clipPlane;
  34184. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34185. }
  34186. };
  34187. return MaterialHelper;
  34188. }());
  34189. BABYLON.MaterialHelper = MaterialHelper;
  34190. })(BABYLON || (BABYLON = {}));
  34191. //# sourceMappingURL=babylon.materialHelper.js.map
  34192. var BABYLON;
  34193. (function (BABYLON) {
  34194. var PushMaterial = /** @class */ (function (_super) {
  34195. __extends(PushMaterial, _super);
  34196. function PushMaterial(name, scene) {
  34197. var _this = _super.call(this, name, scene) || this;
  34198. _this.storeEffectOnSubMeshes = true;
  34199. return _this;
  34200. }
  34201. PushMaterial.prototype.getEffect = function () {
  34202. return this._activeEffect;
  34203. };
  34204. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34205. if (!mesh) {
  34206. return false;
  34207. }
  34208. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34209. return true;
  34210. }
  34211. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34212. };
  34213. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34214. this._activeEffect.setMatrix("world", world);
  34215. };
  34216. PushMaterial.prototype.bind = function (world, mesh) {
  34217. if (!mesh) {
  34218. return;
  34219. }
  34220. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34221. };
  34222. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34223. if (effect === void 0) { effect = null; }
  34224. _super.prototype._afterBind.call(this, mesh);
  34225. this.getScene()._cachedEffect = effect;
  34226. };
  34227. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34228. if (visibility === void 0) { visibility = 1; }
  34229. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34230. };
  34231. return PushMaterial;
  34232. }(BABYLON.Material));
  34233. BABYLON.PushMaterial = PushMaterial;
  34234. })(BABYLON || (BABYLON = {}));
  34235. //# sourceMappingURL=babylon.pushMaterial.js.map
  34236. var BABYLON;
  34237. (function (BABYLON) {
  34238. var StandardMaterialDefines = /** @class */ (function (_super) {
  34239. __extends(StandardMaterialDefines, _super);
  34240. function StandardMaterialDefines() {
  34241. var _this = _super.call(this) || this;
  34242. _this.MAINUV1 = false;
  34243. _this.MAINUV2 = false;
  34244. _this.DIFFUSE = false;
  34245. _this.DIFFUSEDIRECTUV = 0;
  34246. _this.AMBIENT = false;
  34247. _this.AMBIENTDIRECTUV = 0;
  34248. _this.OPACITY = false;
  34249. _this.OPACITYDIRECTUV = 0;
  34250. _this.OPACITYRGB = false;
  34251. _this.REFLECTION = false;
  34252. _this.EMISSIVE = false;
  34253. _this.EMISSIVEDIRECTUV = 0;
  34254. _this.SPECULAR = false;
  34255. _this.SPECULARDIRECTUV = 0;
  34256. _this.BUMP = false;
  34257. _this.BUMPDIRECTUV = 0;
  34258. _this.PARALLAX = false;
  34259. _this.PARALLAXOCCLUSION = false;
  34260. _this.SPECULAROVERALPHA = false;
  34261. _this.CLIPPLANE = false;
  34262. _this.ALPHATEST = false;
  34263. _this.DEPTHPREPASS = false;
  34264. _this.ALPHAFROMDIFFUSE = false;
  34265. _this.POINTSIZE = false;
  34266. _this.FOG = false;
  34267. _this.SPECULARTERM = false;
  34268. _this.DIFFUSEFRESNEL = false;
  34269. _this.OPACITYFRESNEL = false;
  34270. _this.REFLECTIONFRESNEL = false;
  34271. _this.REFRACTIONFRESNEL = false;
  34272. _this.EMISSIVEFRESNEL = false;
  34273. _this.FRESNEL = false;
  34274. _this.NORMAL = false;
  34275. _this.UV1 = false;
  34276. _this.UV2 = false;
  34277. _this.VERTEXCOLOR = false;
  34278. _this.VERTEXALPHA = false;
  34279. _this.NUM_BONE_INFLUENCERS = 0;
  34280. _this.BonesPerMesh = 0;
  34281. _this.INSTANCES = false;
  34282. _this.GLOSSINESS = false;
  34283. _this.ROUGHNESS = false;
  34284. _this.EMISSIVEASILLUMINATION = false;
  34285. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34286. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34287. _this.LIGHTMAP = false;
  34288. _this.LIGHTMAPDIRECTUV = 0;
  34289. _this.USELIGHTMAPASSHADOWMAP = false;
  34290. _this.REFLECTIONMAP_3D = false;
  34291. _this.REFLECTIONMAP_SPHERICAL = false;
  34292. _this.REFLECTIONMAP_PLANAR = false;
  34293. _this.REFLECTIONMAP_CUBIC = false;
  34294. _this.REFLECTIONMAP_PROJECTION = false;
  34295. _this.REFLECTIONMAP_SKYBOX = false;
  34296. _this.REFLECTIONMAP_EXPLICIT = false;
  34297. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34298. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34299. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34300. _this.INVERTCUBICMAP = false;
  34301. _this.LOGARITHMICDEPTH = false;
  34302. _this.REFRACTION = false;
  34303. _this.REFRACTIONMAP_3D = false;
  34304. _this.REFLECTIONOVERALPHA = false;
  34305. _this.TWOSIDEDLIGHTING = false;
  34306. _this.SHADOWFLOAT = false;
  34307. _this.MORPHTARGETS = false;
  34308. _this.MORPHTARGETS_NORMAL = false;
  34309. _this.MORPHTARGETS_TANGENT = false;
  34310. _this.NUM_MORPH_INFLUENCERS = 0;
  34311. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34312. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34313. _this.IMAGEPROCESSING = false;
  34314. _this.VIGNETTE = false;
  34315. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34316. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34317. _this.TONEMAPPING = false;
  34318. _this.CONTRAST = false;
  34319. _this.COLORCURVES = false;
  34320. _this.COLORGRADING = false;
  34321. _this.COLORGRADING3D = false;
  34322. _this.SAMPLER3DGREENDEPTH = false;
  34323. _this.SAMPLER3DBGRMAP = false;
  34324. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34325. _this.EXPOSURE = false;
  34326. _this.rebuild();
  34327. return _this;
  34328. }
  34329. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34330. var modes = [
  34331. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34332. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34333. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34334. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34335. ];
  34336. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34337. var mode = modes_1[_i];
  34338. this[mode] = (mode === modeToEnable);
  34339. }
  34340. };
  34341. return StandardMaterialDefines;
  34342. }(BABYLON.MaterialDefines));
  34343. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34344. var StandardMaterial = /** @class */ (function (_super) {
  34345. __extends(StandardMaterial, _super);
  34346. function StandardMaterial(name, scene) {
  34347. var _this = _super.call(this, name, scene) || this;
  34348. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34349. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34350. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34351. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34352. _this.specularPower = 64;
  34353. _this._useAlphaFromDiffuseTexture = false;
  34354. _this._useEmissiveAsIllumination = false;
  34355. _this._linkEmissiveWithDiffuse = false;
  34356. _this._useSpecularOverAlpha = false;
  34357. _this._useReflectionOverAlpha = false;
  34358. _this._disableLighting = false;
  34359. _this._useParallax = false;
  34360. _this._useParallaxOcclusion = false;
  34361. _this.parallaxScaleBias = 0.05;
  34362. _this._roughness = 0;
  34363. _this.indexOfRefraction = 0.98;
  34364. _this.invertRefractionY = true;
  34365. _this._useLightmapAsShadowmap = false;
  34366. _this._useReflectionFresnelFromSpecular = false;
  34367. _this._useGlossinessFromSpecularMapAlpha = false;
  34368. _this._maxSimultaneousLights = 4;
  34369. /**
  34370. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34371. */
  34372. _this._invertNormalMapX = false;
  34373. /**
  34374. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34375. */
  34376. _this._invertNormalMapY = false;
  34377. /**
  34378. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34379. */
  34380. _this._twoSidedLighting = false;
  34381. _this._renderTargets = new BABYLON.SmartArray(16);
  34382. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34383. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34384. // Setup the default processing configuration to the scene.
  34385. _this._attachImageProcessingConfiguration(null);
  34386. _this.getRenderTargetTextures = function () {
  34387. _this._renderTargets.reset();
  34388. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34389. _this._renderTargets.push(_this._reflectionTexture);
  34390. }
  34391. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34392. _this._renderTargets.push(_this._refractionTexture);
  34393. }
  34394. return _this._renderTargets;
  34395. };
  34396. return _this;
  34397. }
  34398. ;
  34399. ;
  34400. ;
  34401. ;
  34402. ;
  34403. ;
  34404. ;
  34405. ;
  34406. ;
  34407. ;
  34408. ;
  34409. ;
  34410. ;
  34411. ;
  34412. ;
  34413. ;
  34414. ;
  34415. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34416. /**
  34417. * Gets the image processing configuration used either in this material.
  34418. */
  34419. get: function () {
  34420. return this._imageProcessingConfiguration;
  34421. },
  34422. /**
  34423. * Sets the Default image processing configuration used either in the this material.
  34424. *
  34425. * If sets to null, the scene one is in use.
  34426. */
  34427. set: function (value) {
  34428. this._attachImageProcessingConfiguration(value);
  34429. // Ensure the effect will be rebuilt.
  34430. this._markAllSubMeshesAsTexturesDirty();
  34431. },
  34432. enumerable: true,
  34433. configurable: true
  34434. });
  34435. /**
  34436. * Attaches a new image processing configuration to the Standard Material.
  34437. * @param configuration
  34438. */
  34439. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34440. var _this = this;
  34441. if (configuration === this._imageProcessingConfiguration) {
  34442. return;
  34443. }
  34444. // Detaches observer.
  34445. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34446. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34447. }
  34448. // Pick the scene configuration if needed.
  34449. if (!configuration) {
  34450. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34451. }
  34452. else {
  34453. this._imageProcessingConfiguration = configuration;
  34454. }
  34455. // Attaches observer.
  34456. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34457. _this._markAllSubMeshesAsImageProcessingDirty();
  34458. });
  34459. };
  34460. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34461. /**
  34462. * Gets wether the color curves effect is enabled.
  34463. */
  34464. get: function () {
  34465. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34466. },
  34467. /**
  34468. * Sets wether the color curves effect is enabled.
  34469. */
  34470. set: function (value) {
  34471. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34472. },
  34473. enumerable: true,
  34474. configurable: true
  34475. });
  34476. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34477. /**
  34478. * Gets wether the color grading effect is enabled.
  34479. */
  34480. get: function () {
  34481. return this.imageProcessingConfiguration.colorGradingEnabled;
  34482. },
  34483. /**
  34484. * Gets wether the color grading effect is enabled.
  34485. */
  34486. set: function (value) {
  34487. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34488. },
  34489. enumerable: true,
  34490. configurable: true
  34491. });
  34492. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34493. /**
  34494. * Gets wether tonemapping is enabled or not.
  34495. */
  34496. get: function () {
  34497. return this._imageProcessingConfiguration.toneMappingEnabled;
  34498. },
  34499. /**
  34500. * Sets wether tonemapping is enabled or not
  34501. */
  34502. set: function (value) {
  34503. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34504. },
  34505. enumerable: true,
  34506. configurable: true
  34507. });
  34508. ;
  34509. ;
  34510. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34511. /**
  34512. * The camera exposure used on this material.
  34513. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34514. * This corresponds to a photographic exposure.
  34515. */
  34516. get: function () {
  34517. return this._imageProcessingConfiguration.exposure;
  34518. },
  34519. /**
  34520. * The camera exposure used on this material.
  34521. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34522. * This corresponds to a photographic exposure.
  34523. */
  34524. set: function (value) {
  34525. this._imageProcessingConfiguration.exposure = value;
  34526. },
  34527. enumerable: true,
  34528. configurable: true
  34529. });
  34530. ;
  34531. ;
  34532. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34533. /**
  34534. * Gets The camera contrast used on this material.
  34535. */
  34536. get: function () {
  34537. return this._imageProcessingConfiguration.contrast;
  34538. },
  34539. /**
  34540. * Sets The camera contrast used on this material.
  34541. */
  34542. set: function (value) {
  34543. this._imageProcessingConfiguration.contrast = value;
  34544. },
  34545. enumerable: true,
  34546. configurable: true
  34547. });
  34548. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34549. /**
  34550. * Gets the Color Grading 2D Lookup Texture.
  34551. */
  34552. get: function () {
  34553. return this._imageProcessingConfiguration.colorGradingTexture;
  34554. },
  34555. /**
  34556. * Sets the Color Grading 2D Lookup Texture.
  34557. */
  34558. set: function (value) {
  34559. this._imageProcessingConfiguration.colorGradingTexture = value;
  34560. },
  34561. enumerable: true,
  34562. configurable: true
  34563. });
  34564. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34565. /**
  34566. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34567. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34568. * 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;
  34569. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34570. */
  34571. get: function () {
  34572. return this._imageProcessingConfiguration.colorCurves;
  34573. },
  34574. /**
  34575. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34576. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34577. * 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;
  34578. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34579. */
  34580. set: function (value) {
  34581. this._imageProcessingConfiguration.colorCurves = value;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. StandardMaterial.prototype.getClassName = function () {
  34587. return "StandardMaterial";
  34588. };
  34589. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34590. get: function () {
  34591. return this._useLogarithmicDepth;
  34592. },
  34593. set: function (value) {
  34594. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34595. this._markAllSubMeshesAsMiscDirty();
  34596. },
  34597. enumerable: true,
  34598. configurable: true
  34599. });
  34600. StandardMaterial.prototype.needAlphaBlending = function () {
  34601. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34602. };
  34603. StandardMaterial.prototype.needAlphaTesting = function () {
  34604. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34605. };
  34606. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34607. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34608. };
  34609. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34610. return this._diffuseTexture;
  34611. };
  34612. /**
  34613. * Child classes can use it to update shaders
  34614. */
  34615. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34616. if (useInstances === void 0) { useInstances = false; }
  34617. if (subMesh.effect && this.isFrozen) {
  34618. if (this._wasPreviouslyReady && subMesh.effect) {
  34619. return true;
  34620. }
  34621. }
  34622. if (!subMesh._materialDefines) {
  34623. subMesh._materialDefines = new StandardMaterialDefines();
  34624. }
  34625. var scene = this.getScene();
  34626. var defines = subMesh._materialDefines;
  34627. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34628. if (defines._renderId === scene.getRenderId()) {
  34629. return true;
  34630. }
  34631. }
  34632. var engine = scene.getEngine();
  34633. // Lights
  34634. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34635. // Textures
  34636. if (defines._areTexturesDirty) {
  34637. defines._needUVs = false;
  34638. defines.MAINUV1 = false;
  34639. defines.MAINUV2 = false;
  34640. if (scene.texturesEnabled) {
  34641. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34642. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34643. return false;
  34644. }
  34645. else {
  34646. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34647. }
  34648. }
  34649. else {
  34650. defines.DIFFUSE = false;
  34651. }
  34652. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34653. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34654. return false;
  34655. }
  34656. else {
  34657. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34658. }
  34659. }
  34660. else {
  34661. defines.AMBIENT = false;
  34662. }
  34663. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34664. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34665. return false;
  34666. }
  34667. else {
  34668. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34669. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34670. }
  34671. }
  34672. else {
  34673. defines.OPACITY = false;
  34674. }
  34675. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34676. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34677. return false;
  34678. }
  34679. else {
  34680. defines._needNormals = true;
  34681. defines.REFLECTION = true;
  34682. defines.ROUGHNESS = (this._roughness > 0);
  34683. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34684. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34685. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34686. switch (this._reflectionTexture.coordinatesMode) {
  34687. case BABYLON.Texture.CUBIC_MODE:
  34688. case BABYLON.Texture.INVCUBIC_MODE:
  34689. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34690. break;
  34691. case BABYLON.Texture.EXPLICIT_MODE:
  34692. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34693. break;
  34694. case BABYLON.Texture.PLANAR_MODE:
  34695. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34696. break;
  34697. case BABYLON.Texture.PROJECTION_MODE:
  34698. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34699. break;
  34700. case BABYLON.Texture.SKYBOX_MODE:
  34701. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34702. break;
  34703. case BABYLON.Texture.SPHERICAL_MODE:
  34704. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34705. break;
  34706. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34707. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34708. break;
  34709. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34710. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34711. break;
  34712. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34713. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34714. break;
  34715. }
  34716. }
  34717. }
  34718. else {
  34719. defines.REFLECTION = false;
  34720. }
  34721. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34722. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34723. return false;
  34724. }
  34725. else {
  34726. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34727. }
  34728. }
  34729. else {
  34730. defines.EMISSIVE = false;
  34731. }
  34732. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34733. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34734. return false;
  34735. }
  34736. else {
  34737. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34738. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34739. }
  34740. }
  34741. else {
  34742. defines.LIGHTMAP = false;
  34743. }
  34744. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34745. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34746. return false;
  34747. }
  34748. else {
  34749. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34750. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34751. }
  34752. }
  34753. else {
  34754. defines.SPECULAR = false;
  34755. }
  34756. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34757. // Bump texure can not be not blocking.
  34758. if (!this._bumpTexture.isReady()) {
  34759. return false;
  34760. }
  34761. else {
  34762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34763. defines.PARALLAX = this._useParallax;
  34764. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34765. }
  34766. }
  34767. else {
  34768. defines.BUMP = false;
  34769. }
  34770. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34771. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34772. return false;
  34773. }
  34774. else {
  34775. defines._needUVs = true;
  34776. defines.REFRACTION = true;
  34777. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34778. }
  34779. }
  34780. else {
  34781. defines.REFRACTION = false;
  34782. }
  34783. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34784. }
  34785. else {
  34786. defines.DIFFUSE = false;
  34787. defines.AMBIENT = false;
  34788. defines.OPACITY = false;
  34789. defines.REFLECTION = false;
  34790. defines.EMISSIVE = false;
  34791. defines.LIGHTMAP = false;
  34792. defines.BUMP = false;
  34793. defines.REFRACTION = false;
  34794. }
  34795. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34796. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34797. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34798. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34799. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34800. }
  34801. if (defines._areImageProcessingDirty) {
  34802. if (!this._imageProcessingConfiguration.isReady()) {
  34803. return false;
  34804. }
  34805. this._imageProcessingConfiguration.prepareDefines(defines);
  34806. }
  34807. if (defines._areFresnelDirty) {
  34808. if (StandardMaterial.FresnelEnabled) {
  34809. // Fresnel
  34810. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34811. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34812. this._reflectionFresnelParameters) {
  34813. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34814. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34815. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34816. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34817. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34818. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34819. defines._needNormals = true;
  34820. defines.FRESNEL = true;
  34821. }
  34822. }
  34823. else {
  34824. defines.FRESNEL = false;
  34825. }
  34826. }
  34827. // Misc.
  34828. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34829. // Attribs
  34830. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34831. // Values that need to be evaluated on every frame
  34832. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34833. // Get correct effect
  34834. if (defines.isDirty) {
  34835. defines.markAsProcessed();
  34836. scene.resetCachedMaterial();
  34837. // Fallbacks
  34838. var fallbacks = new BABYLON.EffectFallbacks();
  34839. if (defines.REFLECTION) {
  34840. fallbacks.addFallback(0, "REFLECTION");
  34841. }
  34842. if (defines.SPECULAR) {
  34843. fallbacks.addFallback(0, "SPECULAR");
  34844. }
  34845. if (defines.BUMP) {
  34846. fallbacks.addFallback(0, "BUMP");
  34847. }
  34848. if (defines.PARALLAX) {
  34849. fallbacks.addFallback(1, "PARALLAX");
  34850. }
  34851. if (defines.PARALLAXOCCLUSION) {
  34852. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34853. }
  34854. if (defines.SPECULAROVERALPHA) {
  34855. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34856. }
  34857. if (defines.FOG) {
  34858. fallbacks.addFallback(1, "FOG");
  34859. }
  34860. if (defines.POINTSIZE) {
  34861. fallbacks.addFallback(0, "POINTSIZE");
  34862. }
  34863. if (defines.LOGARITHMICDEPTH) {
  34864. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34865. }
  34866. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34867. if (defines.SPECULARTERM) {
  34868. fallbacks.addFallback(0, "SPECULARTERM");
  34869. }
  34870. if (defines.DIFFUSEFRESNEL) {
  34871. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34872. }
  34873. if (defines.OPACITYFRESNEL) {
  34874. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34875. }
  34876. if (defines.REFLECTIONFRESNEL) {
  34877. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34878. }
  34879. if (defines.EMISSIVEFRESNEL) {
  34880. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34881. }
  34882. if (defines.FRESNEL) {
  34883. fallbacks.addFallback(4, "FRESNEL");
  34884. }
  34885. //Attributes
  34886. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34887. if (defines.NORMAL) {
  34888. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34889. }
  34890. if (defines.UV1) {
  34891. attribs.push(BABYLON.VertexBuffer.UVKind);
  34892. }
  34893. if (defines.UV2) {
  34894. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34895. }
  34896. if (defines.VERTEXCOLOR) {
  34897. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34898. }
  34899. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34900. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34901. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34902. var shaderName = "default";
  34903. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34904. "vFogInfos", "vFogColor", "pointSize",
  34905. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34906. "mBones",
  34907. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34908. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34909. "logarithmicDepthConstant", "vTangentSpaceParams"
  34910. ];
  34911. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34912. var uniformBuffers = ["Material", "Scene"];
  34913. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34914. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34915. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34916. uniformsNames: uniforms,
  34917. uniformBuffersNames: uniformBuffers,
  34918. samplers: samplers,
  34919. defines: defines,
  34920. maxSimultaneousLights: this._maxSimultaneousLights
  34921. });
  34922. if (this.customShaderNameResolve) {
  34923. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34924. }
  34925. var join = defines.toString();
  34926. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34927. attributes: attribs,
  34928. uniformsNames: uniforms,
  34929. uniformBuffersNames: uniformBuffers,
  34930. samplers: samplers,
  34931. defines: join,
  34932. fallbacks: fallbacks,
  34933. onCompiled: this.onCompiled,
  34934. onError: this.onError,
  34935. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34936. }, engine), defines);
  34937. this.buildUniformLayout();
  34938. }
  34939. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34940. return false;
  34941. }
  34942. defines._renderId = scene.getRenderId();
  34943. this._wasPreviouslyReady = true;
  34944. return true;
  34945. };
  34946. StandardMaterial.prototype.buildUniformLayout = function () {
  34947. // Order is important !
  34948. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34949. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34950. this._uniformBuffer.addUniform("opacityParts", 4);
  34951. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34952. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34953. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34954. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34955. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34956. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34957. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34958. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34959. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34960. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34961. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34962. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34963. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34964. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34965. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34966. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34967. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34968. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34969. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34970. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34971. this._uniformBuffer.addUniform("specularMatrix", 16);
  34972. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34973. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34974. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34975. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34976. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34977. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34978. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34979. this._uniformBuffer.addUniform("pointSize", 1);
  34980. this._uniformBuffer.create();
  34981. };
  34982. StandardMaterial.prototype.unbind = function () {
  34983. if (this._activeEffect) {
  34984. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34985. this._activeEffect.setTexture("reflection2DSampler", null);
  34986. }
  34987. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34988. this._activeEffect.setTexture("refraction2DSampler", null);
  34989. }
  34990. }
  34991. _super.prototype.unbind.call(this);
  34992. };
  34993. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34994. var scene = this.getScene();
  34995. var defines = subMesh._materialDefines;
  34996. if (!defines) {
  34997. return;
  34998. }
  34999. var effect = subMesh.effect;
  35000. if (!effect) {
  35001. return;
  35002. }
  35003. this._activeEffect = effect;
  35004. // Matrices
  35005. this.bindOnlyWorldMatrix(world);
  35006. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35007. // Bones
  35008. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35009. if (mustRebind) {
  35010. this._uniformBuffer.bindToEffect(effect, "Material");
  35011. this.bindViewProjection(effect);
  35012. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35013. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35014. // Fresnel
  35015. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35016. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35017. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35018. }
  35019. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35020. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35021. }
  35022. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35023. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35024. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35025. }
  35026. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35027. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35028. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35029. }
  35030. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35031. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35032. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35033. }
  35034. }
  35035. // Textures
  35036. if (scene.texturesEnabled) {
  35037. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35038. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35039. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35040. }
  35041. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35042. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35043. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35044. }
  35045. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35046. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35047. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35048. }
  35049. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35050. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35051. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35052. }
  35053. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35054. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35055. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35056. }
  35057. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35058. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35059. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35060. }
  35061. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35062. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35063. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35064. }
  35065. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35066. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35067. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35068. if (scene._mirroredCameraPosition) {
  35069. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35070. }
  35071. else {
  35072. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35073. }
  35074. }
  35075. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35076. var depth = 1.0;
  35077. if (!this._refractionTexture.isCube) {
  35078. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35079. if (this._refractionTexture.depth) {
  35080. depth = this._refractionTexture.depth;
  35081. }
  35082. }
  35083. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35084. }
  35085. }
  35086. // Point size
  35087. if (this.pointsCloud) {
  35088. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35089. }
  35090. if (defines.SPECULARTERM) {
  35091. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35092. }
  35093. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35094. // Diffuse
  35095. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35096. }
  35097. // Textures
  35098. if (scene.texturesEnabled) {
  35099. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35100. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35101. }
  35102. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35103. effect.setTexture("ambientSampler", this._ambientTexture);
  35104. }
  35105. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35106. effect.setTexture("opacitySampler", this._opacityTexture);
  35107. }
  35108. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35109. if (this._reflectionTexture.isCube) {
  35110. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35111. }
  35112. else {
  35113. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35114. }
  35115. }
  35116. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35117. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35118. }
  35119. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35120. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35121. }
  35122. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35123. effect.setTexture("specularSampler", this._specularTexture);
  35124. }
  35125. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35126. effect.setTexture("bumpSampler", this._bumpTexture);
  35127. }
  35128. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35129. var depth = 1.0;
  35130. if (this._refractionTexture.isCube) {
  35131. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35132. }
  35133. else {
  35134. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35135. }
  35136. }
  35137. }
  35138. // Clip plane
  35139. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35140. // Colors
  35141. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35142. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35143. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35144. }
  35145. if (mustRebind || !this.isFrozen) {
  35146. // Lights
  35147. if (scene.lightsEnabled && !this._disableLighting) {
  35148. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35149. }
  35150. // View
  35151. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35152. this.bindView(effect);
  35153. }
  35154. // Fog
  35155. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35156. // Morph targets
  35157. if (defines.NUM_MORPH_INFLUENCERS) {
  35158. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35159. }
  35160. // Log. depth
  35161. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35162. // image processing
  35163. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35164. this._imageProcessingConfiguration.bind(this._activeEffect);
  35165. }
  35166. }
  35167. this._uniformBuffer.update();
  35168. this._afterBind(mesh, this._activeEffect);
  35169. };
  35170. StandardMaterial.prototype.getAnimatables = function () {
  35171. var results = [];
  35172. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35173. results.push(this._diffuseTexture);
  35174. }
  35175. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35176. results.push(this._ambientTexture);
  35177. }
  35178. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35179. results.push(this._opacityTexture);
  35180. }
  35181. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35182. results.push(this._reflectionTexture);
  35183. }
  35184. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35185. results.push(this._emissiveTexture);
  35186. }
  35187. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35188. results.push(this._specularTexture);
  35189. }
  35190. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35191. results.push(this._bumpTexture);
  35192. }
  35193. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35194. results.push(this._lightmapTexture);
  35195. }
  35196. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35197. results.push(this._refractionTexture);
  35198. }
  35199. return results;
  35200. };
  35201. StandardMaterial.prototype.getActiveTextures = function () {
  35202. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35203. if (this._diffuseTexture) {
  35204. activeTextures.push(this._diffuseTexture);
  35205. }
  35206. if (this._ambientTexture) {
  35207. activeTextures.push(this._ambientTexture);
  35208. }
  35209. if (this._opacityTexture) {
  35210. activeTextures.push(this._opacityTexture);
  35211. }
  35212. if (this._reflectionTexture) {
  35213. activeTextures.push(this._reflectionTexture);
  35214. }
  35215. if (this._emissiveTexture) {
  35216. activeTextures.push(this._emissiveTexture);
  35217. }
  35218. if (this._specularTexture) {
  35219. activeTextures.push(this._specularTexture);
  35220. }
  35221. if (this._bumpTexture) {
  35222. activeTextures.push(this._bumpTexture);
  35223. }
  35224. if (this._lightmapTexture) {
  35225. activeTextures.push(this._lightmapTexture);
  35226. }
  35227. if (this._refractionTexture) {
  35228. activeTextures.push(this._refractionTexture);
  35229. }
  35230. return activeTextures;
  35231. };
  35232. StandardMaterial.prototype.hasTexture = function (texture) {
  35233. if (_super.prototype.hasTexture.call(this, texture)) {
  35234. return true;
  35235. }
  35236. if (this._diffuseTexture === texture) {
  35237. return true;
  35238. }
  35239. if (this._ambientTexture === texture) {
  35240. return true;
  35241. }
  35242. if (this._opacityTexture === texture) {
  35243. return true;
  35244. }
  35245. if (this._reflectionTexture === texture) {
  35246. return true;
  35247. }
  35248. if (this._emissiveTexture === texture) {
  35249. return true;
  35250. }
  35251. if (this._specularTexture === texture) {
  35252. return true;
  35253. }
  35254. if (this._bumpTexture === texture) {
  35255. return true;
  35256. }
  35257. if (this._lightmapTexture === texture) {
  35258. return true;
  35259. }
  35260. if (this._refractionTexture === texture) {
  35261. return true;
  35262. }
  35263. return false;
  35264. };
  35265. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35266. if (forceDisposeTextures) {
  35267. if (this._diffuseTexture) {
  35268. this._diffuseTexture.dispose();
  35269. }
  35270. if (this._ambientTexture) {
  35271. this._ambientTexture.dispose();
  35272. }
  35273. if (this._opacityTexture) {
  35274. this._opacityTexture.dispose();
  35275. }
  35276. if (this._reflectionTexture) {
  35277. this._reflectionTexture.dispose();
  35278. }
  35279. if (this._emissiveTexture) {
  35280. this._emissiveTexture.dispose();
  35281. }
  35282. if (this._specularTexture) {
  35283. this._specularTexture.dispose();
  35284. }
  35285. if (this._bumpTexture) {
  35286. this._bumpTexture.dispose();
  35287. }
  35288. if (this._lightmapTexture) {
  35289. this._lightmapTexture.dispose();
  35290. }
  35291. if (this._refractionTexture) {
  35292. this._refractionTexture.dispose();
  35293. }
  35294. }
  35295. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35296. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35297. }
  35298. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35299. };
  35300. StandardMaterial.prototype.clone = function (name) {
  35301. var _this = this;
  35302. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35303. result.name = name;
  35304. result.id = name;
  35305. return result;
  35306. };
  35307. StandardMaterial.prototype.serialize = function () {
  35308. return BABYLON.SerializationHelper.Serialize(this);
  35309. };
  35310. // Statics
  35311. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35312. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35313. };
  35314. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35315. get: function () {
  35316. return StandardMaterial._DiffuseTextureEnabled;
  35317. },
  35318. set: function (value) {
  35319. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35320. return;
  35321. }
  35322. StandardMaterial._DiffuseTextureEnabled = value;
  35323. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35329. get: function () {
  35330. return StandardMaterial._AmbientTextureEnabled;
  35331. },
  35332. set: function (value) {
  35333. if (StandardMaterial._AmbientTextureEnabled === value) {
  35334. return;
  35335. }
  35336. StandardMaterial._AmbientTextureEnabled = value;
  35337. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35338. },
  35339. enumerable: true,
  35340. configurable: true
  35341. });
  35342. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35343. get: function () {
  35344. return StandardMaterial._OpacityTextureEnabled;
  35345. },
  35346. set: function (value) {
  35347. if (StandardMaterial._OpacityTextureEnabled === value) {
  35348. return;
  35349. }
  35350. StandardMaterial._OpacityTextureEnabled = value;
  35351. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35352. },
  35353. enumerable: true,
  35354. configurable: true
  35355. });
  35356. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35357. get: function () {
  35358. return StandardMaterial._ReflectionTextureEnabled;
  35359. },
  35360. set: function (value) {
  35361. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35362. return;
  35363. }
  35364. StandardMaterial._ReflectionTextureEnabled = value;
  35365. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35366. },
  35367. enumerable: true,
  35368. configurable: true
  35369. });
  35370. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35371. get: function () {
  35372. return StandardMaterial._EmissiveTextureEnabled;
  35373. },
  35374. set: function (value) {
  35375. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35376. return;
  35377. }
  35378. StandardMaterial._EmissiveTextureEnabled = value;
  35379. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35380. },
  35381. enumerable: true,
  35382. configurable: true
  35383. });
  35384. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35385. get: function () {
  35386. return StandardMaterial._SpecularTextureEnabled;
  35387. },
  35388. set: function (value) {
  35389. if (StandardMaterial._SpecularTextureEnabled === value) {
  35390. return;
  35391. }
  35392. StandardMaterial._SpecularTextureEnabled = value;
  35393. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35394. },
  35395. enumerable: true,
  35396. configurable: true
  35397. });
  35398. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35399. get: function () {
  35400. return StandardMaterial._BumpTextureEnabled;
  35401. },
  35402. set: function (value) {
  35403. if (StandardMaterial._BumpTextureEnabled === value) {
  35404. return;
  35405. }
  35406. StandardMaterial._BumpTextureEnabled = value;
  35407. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35408. },
  35409. enumerable: true,
  35410. configurable: true
  35411. });
  35412. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35413. get: function () {
  35414. return StandardMaterial._LightmapTextureEnabled;
  35415. },
  35416. set: function (value) {
  35417. if (StandardMaterial._LightmapTextureEnabled === value) {
  35418. return;
  35419. }
  35420. StandardMaterial._LightmapTextureEnabled = value;
  35421. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35427. get: function () {
  35428. return StandardMaterial._RefractionTextureEnabled;
  35429. },
  35430. set: function (value) {
  35431. if (StandardMaterial._RefractionTextureEnabled === value) {
  35432. return;
  35433. }
  35434. StandardMaterial._RefractionTextureEnabled = value;
  35435. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35436. },
  35437. enumerable: true,
  35438. configurable: true
  35439. });
  35440. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35441. get: function () {
  35442. return StandardMaterial._ColorGradingTextureEnabled;
  35443. },
  35444. set: function (value) {
  35445. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35446. return;
  35447. }
  35448. StandardMaterial._ColorGradingTextureEnabled = value;
  35449. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35455. get: function () {
  35456. return StandardMaterial._FresnelEnabled;
  35457. },
  35458. set: function (value) {
  35459. if (StandardMaterial._FresnelEnabled === value) {
  35460. return;
  35461. }
  35462. StandardMaterial._FresnelEnabled = value;
  35463. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35464. },
  35465. enumerable: true,
  35466. configurable: true
  35467. });
  35468. // Flags used to enable or disable a type of texture for all Standard Materials
  35469. StandardMaterial._DiffuseTextureEnabled = true;
  35470. StandardMaterial._AmbientTextureEnabled = true;
  35471. StandardMaterial._OpacityTextureEnabled = true;
  35472. StandardMaterial._ReflectionTextureEnabled = true;
  35473. StandardMaterial._EmissiveTextureEnabled = true;
  35474. StandardMaterial._SpecularTextureEnabled = true;
  35475. StandardMaterial._BumpTextureEnabled = true;
  35476. StandardMaterial._LightmapTextureEnabled = true;
  35477. StandardMaterial._RefractionTextureEnabled = true;
  35478. StandardMaterial._ColorGradingTextureEnabled = true;
  35479. StandardMaterial._FresnelEnabled = true;
  35480. __decorate([
  35481. BABYLON.serializeAsTexture("diffuseTexture")
  35482. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35483. __decorate([
  35484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35485. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35486. __decorate([
  35487. BABYLON.serializeAsTexture("ambientTexture")
  35488. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35489. __decorate([
  35490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35491. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35492. __decorate([
  35493. BABYLON.serializeAsTexture("opacityTexture")
  35494. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35495. __decorate([
  35496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35497. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35498. __decorate([
  35499. BABYLON.serializeAsTexture("reflectionTexture")
  35500. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35501. __decorate([
  35502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35503. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35504. __decorate([
  35505. BABYLON.serializeAsTexture("emissiveTexture")
  35506. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35507. __decorate([
  35508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35509. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35510. __decorate([
  35511. BABYLON.serializeAsTexture("specularTexture")
  35512. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35513. __decorate([
  35514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35515. ], StandardMaterial.prototype, "specularTexture", void 0);
  35516. __decorate([
  35517. BABYLON.serializeAsTexture("bumpTexture")
  35518. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35519. __decorate([
  35520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35521. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35522. __decorate([
  35523. BABYLON.serializeAsTexture("lightmapTexture")
  35524. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35525. __decorate([
  35526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35527. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35528. __decorate([
  35529. BABYLON.serializeAsTexture("refractionTexture")
  35530. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35531. __decorate([
  35532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35533. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35534. __decorate([
  35535. BABYLON.serializeAsColor3("ambient")
  35536. ], StandardMaterial.prototype, "ambientColor", void 0);
  35537. __decorate([
  35538. BABYLON.serializeAsColor3("diffuse")
  35539. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35540. __decorate([
  35541. BABYLON.serializeAsColor3("specular")
  35542. ], StandardMaterial.prototype, "specularColor", void 0);
  35543. __decorate([
  35544. BABYLON.serializeAsColor3("emissive")
  35545. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35546. __decorate([
  35547. BABYLON.serialize()
  35548. ], StandardMaterial.prototype, "specularPower", void 0);
  35549. __decorate([
  35550. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35551. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35552. __decorate([
  35553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35554. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35555. __decorate([
  35556. BABYLON.serialize("useEmissiveAsIllumination")
  35557. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35558. __decorate([
  35559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35560. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35561. __decorate([
  35562. BABYLON.serialize("linkEmissiveWithDiffuse")
  35563. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35564. __decorate([
  35565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35566. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35567. __decorate([
  35568. BABYLON.serialize("useSpecularOverAlpha")
  35569. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35570. __decorate([
  35571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35572. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35573. __decorate([
  35574. BABYLON.serialize("useReflectionOverAlpha")
  35575. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35576. __decorate([
  35577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35578. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35579. __decorate([
  35580. BABYLON.serialize("disableLighting")
  35581. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35582. __decorate([
  35583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35584. ], StandardMaterial.prototype, "disableLighting", void 0);
  35585. __decorate([
  35586. BABYLON.serialize("useParallax")
  35587. ], StandardMaterial.prototype, "_useParallax", void 0);
  35588. __decorate([
  35589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35590. ], StandardMaterial.prototype, "useParallax", void 0);
  35591. __decorate([
  35592. BABYLON.serialize("useParallaxOcclusion")
  35593. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35594. __decorate([
  35595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35596. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35597. __decorate([
  35598. BABYLON.serialize()
  35599. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35600. __decorate([
  35601. BABYLON.serialize("roughness")
  35602. ], StandardMaterial.prototype, "_roughness", void 0);
  35603. __decorate([
  35604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35605. ], StandardMaterial.prototype, "roughness", void 0);
  35606. __decorate([
  35607. BABYLON.serialize()
  35608. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35609. __decorate([
  35610. BABYLON.serialize()
  35611. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35612. __decorate([
  35613. BABYLON.serialize("useLightmapAsShadowmap")
  35614. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35615. __decorate([
  35616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35617. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35618. __decorate([
  35619. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35620. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35621. __decorate([
  35622. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35623. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35624. __decorate([
  35625. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35626. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35627. __decorate([
  35628. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35629. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35630. __decorate([
  35631. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35632. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35633. __decorate([
  35634. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35635. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35636. __decorate([
  35637. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35638. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35639. __decorate([
  35640. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35641. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35642. __decorate([
  35643. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35644. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35645. __decorate([
  35646. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35647. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35648. __decorate([
  35649. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35650. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35651. __decorate([
  35652. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35653. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35654. __decorate([
  35655. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35656. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35657. __decorate([
  35658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35659. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35660. __decorate([
  35661. BABYLON.serialize("maxSimultaneousLights")
  35662. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35663. __decorate([
  35664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35665. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35666. __decorate([
  35667. BABYLON.serialize("invertNormalMapX")
  35668. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35669. __decorate([
  35670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35671. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35672. __decorate([
  35673. BABYLON.serialize("invertNormalMapY")
  35674. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35675. __decorate([
  35676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35677. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35678. __decorate([
  35679. BABYLON.serialize("twoSidedLighting")
  35680. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35681. __decorate([
  35682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35683. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35684. __decorate([
  35685. BABYLON.serialize()
  35686. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35687. return StandardMaterial;
  35688. }(BABYLON.PushMaterial));
  35689. BABYLON.StandardMaterial = StandardMaterial;
  35690. })(BABYLON || (BABYLON = {}));
  35691. //# sourceMappingURL=babylon.standardMaterial.js.map
  35692. var BABYLON;
  35693. (function (BABYLON) {
  35694. var PBRMaterialDefines = /** @class */ (function (_super) {
  35695. __extends(PBRMaterialDefines, _super);
  35696. function PBRMaterialDefines() {
  35697. var _this = _super.call(this) || this;
  35698. _this.PBR = true;
  35699. _this.MAINUV1 = false;
  35700. _this.MAINUV2 = false;
  35701. _this.UV1 = false;
  35702. _this.UV2 = false;
  35703. _this.ALBEDO = false;
  35704. _this.ALBEDODIRECTUV = 0;
  35705. _this.VERTEXCOLOR = false;
  35706. _this.AMBIENT = false;
  35707. _this.AMBIENTDIRECTUV = 0;
  35708. _this.AMBIENTINGRAYSCALE = false;
  35709. _this.OPACITY = false;
  35710. _this.VERTEXALPHA = false;
  35711. _this.OPACITYDIRECTUV = 0;
  35712. _this.OPACITYRGB = false;
  35713. _this.ALPHATEST = false;
  35714. _this.DEPTHPREPASS = false;
  35715. _this.ALPHABLEND = false;
  35716. _this.ALPHAFROMALBEDO = false;
  35717. _this.ALPHATESTVALUE = 0.5;
  35718. _this.SPECULAROVERALPHA = false;
  35719. _this.RADIANCEOVERALPHA = false;
  35720. _this.ALPHAFRESNEL = false;
  35721. _this.LINEARALPHAFRESNEL = false;
  35722. _this.PREMULTIPLYALPHA = false;
  35723. _this.EMISSIVE = false;
  35724. _this.EMISSIVEDIRECTUV = 0;
  35725. _this.REFLECTIVITY = false;
  35726. _this.REFLECTIVITYDIRECTUV = 0;
  35727. _this.SPECULARTERM = false;
  35728. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35729. _this.MICROSURFACEAUTOMATIC = false;
  35730. _this.LODBASEDMICROSFURACE = false;
  35731. _this.MICROSURFACEMAP = false;
  35732. _this.MICROSURFACEMAPDIRECTUV = 0;
  35733. _this.METALLICWORKFLOW = false;
  35734. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35735. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35736. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35737. _this.AOSTOREINMETALMAPRED = false;
  35738. _this.ENVIRONMENTBRDF = false;
  35739. _this.NORMAL = false;
  35740. _this.TANGENT = false;
  35741. _this.BUMP = false;
  35742. _this.BUMPDIRECTUV = 0;
  35743. _this.PARALLAX = false;
  35744. _this.PARALLAXOCCLUSION = false;
  35745. _this.NORMALXYSCALE = true;
  35746. _this.LIGHTMAP = false;
  35747. _this.LIGHTMAPDIRECTUV = 0;
  35748. _this.USELIGHTMAPASSHADOWMAP = false;
  35749. _this.REFLECTION = false;
  35750. _this.REFLECTIONMAP_3D = false;
  35751. _this.REFLECTIONMAP_SPHERICAL = false;
  35752. _this.REFLECTIONMAP_PLANAR = false;
  35753. _this.REFLECTIONMAP_CUBIC = false;
  35754. _this.REFLECTIONMAP_PROJECTION = false;
  35755. _this.REFLECTIONMAP_SKYBOX = false;
  35756. _this.REFLECTIONMAP_EXPLICIT = false;
  35757. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35758. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35759. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35760. _this.INVERTCUBICMAP = false;
  35761. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35762. _this.USESPHERICALINVERTEX = false;
  35763. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35764. _this.LODINREFLECTIONALPHA = false;
  35765. _this.GAMMAREFLECTION = false;
  35766. _this.RADIANCEOCCLUSION = false;
  35767. _this.HORIZONOCCLUSION = false;
  35768. _this.REFRACTION = false;
  35769. _this.REFRACTIONMAP_3D = false;
  35770. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35771. _this.LODINREFRACTIONALPHA = false;
  35772. _this.GAMMAREFRACTION = false;
  35773. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35774. _this.INSTANCES = false;
  35775. _this.NUM_BONE_INFLUENCERS = 0;
  35776. _this.BonesPerMesh = 0;
  35777. _this.NONUNIFORMSCALING = false;
  35778. _this.MORPHTARGETS = false;
  35779. _this.MORPHTARGETS_NORMAL = false;
  35780. _this.MORPHTARGETS_TANGENT = false;
  35781. _this.NUM_MORPH_INFLUENCERS = 0;
  35782. _this.IMAGEPROCESSING = false;
  35783. _this.VIGNETTE = false;
  35784. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35785. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35786. _this.TONEMAPPING = false;
  35787. _this.CONTRAST = false;
  35788. _this.COLORCURVES = false;
  35789. _this.COLORGRADING = false;
  35790. _this.COLORGRADING3D = false;
  35791. _this.SAMPLER3DGREENDEPTH = false;
  35792. _this.SAMPLER3DBGRMAP = false;
  35793. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35794. _this.EXPOSURE = false;
  35795. _this.USEPHYSICALLIGHTFALLOFF = false;
  35796. _this.TWOSIDEDLIGHTING = false;
  35797. _this.SHADOWFLOAT = false;
  35798. _this.CLIPPLANE = false;
  35799. _this.POINTSIZE = false;
  35800. _this.FOG = false;
  35801. _this.LOGARITHMICDEPTH = false;
  35802. _this.FORCENORMALFORWARD = false;
  35803. _this.rebuild();
  35804. return _this;
  35805. }
  35806. PBRMaterialDefines.prototype.reset = function () {
  35807. _super.prototype.reset.call(this);
  35808. this.ALPHATESTVALUE = 0.5;
  35809. this.PBR = true;
  35810. };
  35811. return PBRMaterialDefines;
  35812. }(BABYLON.MaterialDefines));
  35813. /**
  35814. * The Physically based material base class of BJS.
  35815. *
  35816. * This offers the main features of a standard PBR material.
  35817. * For more information, please refer to the documentation :
  35818. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35819. */
  35820. var PBRBaseMaterial = /** @class */ (function (_super) {
  35821. __extends(PBRBaseMaterial, _super);
  35822. /**
  35823. * Instantiates a new PBRMaterial instance.
  35824. *
  35825. * @param name The material name
  35826. * @param scene The scene the material will be use in.
  35827. */
  35828. function PBRBaseMaterial(name, scene) {
  35829. var _this = _super.call(this, name, scene) || this;
  35830. /**
  35831. * Intensity of the direct lights e.g. the four lights available in your scene.
  35832. * This impacts both the direct diffuse and specular highlights.
  35833. */
  35834. _this._directIntensity = 1.0;
  35835. /**
  35836. * Intensity of the emissive part of the material.
  35837. * This helps controlling the emissive effect without modifying the emissive color.
  35838. */
  35839. _this._emissiveIntensity = 1.0;
  35840. /**
  35841. * Intensity of the environment e.g. how much the environment will light the object
  35842. * either through harmonics for rough material or through the refelction for shiny ones.
  35843. */
  35844. _this._environmentIntensity = 1.0;
  35845. /**
  35846. * This is a special control allowing the reduction of the specular highlights coming from the
  35847. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35848. */
  35849. _this._specularIntensity = 1.0;
  35850. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35851. /**
  35852. * Debug Control allowing disabling the bump map on this material.
  35853. */
  35854. _this._disableBumpMap = false;
  35855. /**
  35856. * AKA Occlusion Texture Intensity in other nomenclature.
  35857. */
  35858. _this._ambientTextureStrength = 1.0;
  35859. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35860. /**
  35861. * AKA Diffuse Color in other nomenclature.
  35862. */
  35863. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35864. /**
  35865. * AKA Specular Color in other nomenclature.
  35866. */
  35867. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35868. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35869. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35870. /**
  35871. * AKA Glossiness in other nomenclature.
  35872. */
  35873. _this._microSurface = 0.9;
  35874. /**
  35875. * source material index of refraction (IOR)' / 'destination material IOR.
  35876. */
  35877. _this._indexOfRefraction = 0.66;
  35878. /**
  35879. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35880. */
  35881. _this._invertRefractionY = false;
  35882. /**
  35883. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35884. * Materials half opaque for instance using refraction could benefit from this control.
  35885. */
  35886. _this._linkRefractionWithTransparency = false;
  35887. _this._useLightmapAsShadowmap = false;
  35888. /**
  35889. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35890. * makes the reflect vector face the model (under horizon).
  35891. */
  35892. _this._useHorizonOcclusion = true;
  35893. /**
  35894. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35895. * too much the area relying on ambient texture to define their ambient occlusion.
  35896. */
  35897. _this._useRadianceOcclusion = true;
  35898. /**
  35899. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35900. */
  35901. _this._useAlphaFromAlbedoTexture = false;
  35902. /**
  35903. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35904. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35905. */
  35906. _this._useSpecularOverAlpha = true;
  35907. /**
  35908. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35909. */
  35910. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35911. /**
  35912. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35913. */
  35914. _this._useRoughnessFromMetallicTextureAlpha = true;
  35915. /**
  35916. * Specifies if the metallic texture contains the roughness information in its green channel.
  35917. */
  35918. _this._useRoughnessFromMetallicTextureGreen = false;
  35919. /**
  35920. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35921. */
  35922. _this._useMetallnessFromMetallicTextureBlue = false;
  35923. /**
  35924. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35925. */
  35926. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35927. /**
  35928. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35929. */
  35930. _this._useAmbientInGrayScale = false;
  35931. /**
  35932. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35933. * The material will try to infer what glossiness each pixel should be.
  35934. */
  35935. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35936. /**
  35937. * BJS is using an harcoded light falloff based on a manually sets up range.
  35938. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35939. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35940. */
  35941. _this._usePhysicalLightFalloff = true;
  35942. /**
  35943. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35944. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35945. */
  35946. _this._useRadianceOverAlpha = true;
  35947. /**
  35948. * Allows using the bump map in parallax mode.
  35949. */
  35950. _this._useParallax = false;
  35951. /**
  35952. * Allows using the bump map in parallax occlusion mode.
  35953. */
  35954. _this._useParallaxOcclusion = false;
  35955. /**
  35956. * Controls the scale bias of the parallax mode.
  35957. */
  35958. _this._parallaxScaleBias = 0.05;
  35959. /**
  35960. * If sets to true, disables all the lights affecting the material.
  35961. */
  35962. _this._disableLighting = false;
  35963. /**
  35964. * Number of Simultaneous lights allowed on the material.
  35965. */
  35966. _this._maxSimultaneousLights = 4;
  35967. /**
  35968. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35969. */
  35970. _this._invertNormalMapX = false;
  35971. /**
  35972. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35973. */
  35974. _this._invertNormalMapY = false;
  35975. /**
  35976. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35977. */
  35978. _this._twoSidedLighting = false;
  35979. /**
  35980. * Defines the alpha limits in alpha test mode.
  35981. */
  35982. _this._alphaCutOff = 0.4;
  35983. /**
  35984. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35985. */
  35986. _this._forceAlphaTest = false;
  35987. /**
  35988. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35989. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  35990. */
  35991. _this._useAlphaFresnel = false;
  35992. /**
  35993. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35994. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  35995. */
  35996. _this._useLinearAlphaFresnel = false;
  35997. /**
  35998. * The transparency mode of the material.
  35999. */
  36000. _this._transparencyMode = null;
  36001. /**
  36002. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36003. * from cos thetav and roughness:
  36004. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36005. */
  36006. _this._environmentBRDFTexture = null;
  36007. /**
  36008. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36009. */
  36010. _this._forceIrradianceInFragment = false;
  36011. /**
  36012. * Force normal to face away from face.
  36013. */
  36014. _this._forceNormalForward = false;
  36015. _this._renderTargets = new BABYLON.SmartArray(16);
  36016. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36017. // Setup the default processing configuration to the scene.
  36018. _this._attachImageProcessingConfiguration(null);
  36019. _this.getRenderTargetTextures = function () {
  36020. _this._renderTargets.reset();
  36021. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36022. _this._renderTargets.push(_this._reflectionTexture);
  36023. }
  36024. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36025. _this._renderTargets.push(_this._refractionTexture);
  36026. }
  36027. return _this._renderTargets;
  36028. };
  36029. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36030. return _this;
  36031. }
  36032. /**
  36033. * Attaches a new image processing configuration to the PBR Material.
  36034. * @param configuration
  36035. */
  36036. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36037. var _this = this;
  36038. if (configuration === this._imageProcessingConfiguration) {
  36039. return;
  36040. }
  36041. // Detaches observer.
  36042. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36043. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36044. }
  36045. // Pick the scene configuration if needed.
  36046. if (!configuration) {
  36047. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36048. }
  36049. else {
  36050. this._imageProcessingConfiguration = configuration;
  36051. }
  36052. // Attaches observer.
  36053. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36054. _this._markAllSubMeshesAsImageProcessingDirty();
  36055. });
  36056. };
  36057. PBRBaseMaterial.prototype.getClassName = function () {
  36058. return "PBRBaseMaterial";
  36059. };
  36060. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36061. get: function () {
  36062. return this._useLogarithmicDepth;
  36063. },
  36064. set: function (value) {
  36065. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36066. },
  36067. enumerable: true,
  36068. configurable: true
  36069. });
  36070. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36071. /**
  36072. * Gets the current transparency mode.
  36073. */
  36074. get: function () {
  36075. return this._transparencyMode;
  36076. },
  36077. /**
  36078. * Sets the transparency mode of the material.
  36079. */
  36080. set: function (value) {
  36081. if (this._transparencyMode === value) {
  36082. return;
  36083. }
  36084. this._transparencyMode = value;
  36085. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36086. this._markAllSubMeshesAsTexturesDirty();
  36087. },
  36088. enumerable: true,
  36089. configurable: true
  36090. });
  36091. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36092. /**
  36093. * Returns true if alpha blending should be disabled.
  36094. */
  36095. get: function () {
  36096. return (this._linkRefractionWithTransparency ||
  36097. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36098. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36099. },
  36100. enumerable: true,
  36101. configurable: true
  36102. });
  36103. /**
  36104. * Specifies whether or not this material should be rendered in alpha blend mode.
  36105. */
  36106. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36107. if (this._disableAlphaBlending) {
  36108. return false;
  36109. }
  36110. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36111. };
  36112. /**
  36113. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36114. */
  36115. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36116. if (this._disableAlphaBlending) {
  36117. return false;
  36118. }
  36119. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36120. };
  36121. /**
  36122. * Specifies whether or not this material should be rendered in alpha test mode.
  36123. */
  36124. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36125. if (this._forceAlphaTest) {
  36126. return true;
  36127. }
  36128. if (this._linkRefractionWithTransparency) {
  36129. return false;
  36130. }
  36131. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36132. };
  36133. /**
  36134. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36135. */
  36136. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36137. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36138. };
  36139. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36140. return this._albedoTexture;
  36141. };
  36142. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36143. var _this = this;
  36144. if (subMesh.effect && this.isFrozen) {
  36145. if (this._wasPreviouslyReady) {
  36146. return true;
  36147. }
  36148. }
  36149. if (!subMesh._materialDefines) {
  36150. subMesh._materialDefines = new PBRMaterialDefines();
  36151. }
  36152. var scene = this.getScene();
  36153. var defines = subMesh._materialDefines;
  36154. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36155. if (defines._renderId === scene.getRenderId()) {
  36156. return true;
  36157. }
  36158. }
  36159. var engine = scene.getEngine();
  36160. // Lights
  36161. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36162. defines._needNormals = true;
  36163. // Textures
  36164. if (defines._areTexturesDirty) {
  36165. defines._needUVs = false;
  36166. if (scene.texturesEnabled) {
  36167. if (scene.getEngine().getCaps().textureLOD) {
  36168. defines.LODBASEDMICROSFURACE = true;
  36169. }
  36170. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36171. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36172. return false;
  36173. }
  36174. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36175. }
  36176. else {
  36177. defines.ALBEDO = false;
  36178. }
  36179. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36180. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36181. return false;
  36182. }
  36183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36184. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36185. }
  36186. else {
  36187. defines.AMBIENT = false;
  36188. }
  36189. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36190. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36191. return false;
  36192. }
  36193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36194. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36195. }
  36196. else {
  36197. defines.OPACITY = false;
  36198. }
  36199. var reflectionTexture = this._getReflectionTexture();
  36200. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36201. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36202. return false;
  36203. }
  36204. defines.REFLECTION = true;
  36205. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36206. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36207. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36208. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36209. defines.INVERTCUBICMAP = true;
  36210. }
  36211. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36212. switch (reflectionTexture.coordinatesMode) {
  36213. case BABYLON.Texture.CUBIC_MODE:
  36214. case BABYLON.Texture.INVCUBIC_MODE:
  36215. defines.REFLECTIONMAP_CUBIC = true;
  36216. break;
  36217. case BABYLON.Texture.EXPLICIT_MODE:
  36218. defines.REFLECTIONMAP_EXPLICIT = true;
  36219. break;
  36220. case BABYLON.Texture.PLANAR_MODE:
  36221. defines.REFLECTIONMAP_PLANAR = true;
  36222. break;
  36223. case BABYLON.Texture.PROJECTION_MODE:
  36224. defines.REFLECTIONMAP_PROJECTION = true;
  36225. break;
  36226. case BABYLON.Texture.SKYBOX_MODE:
  36227. defines.REFLECTIONMAP_SKYBOX = true;
  36228. break;
  36229. case BABYLON.Texture.SPHERICAL_MODE:
  36230. defines.REFLECTIONMAP_SPHERICAL = true;
  36231. break;
  36232. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36233. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36234. break;
  36235. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36236. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36237. break;
  36238. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36239. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36240. break;
  36241. }
  36242. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36243. if (reflectionTexture.sphericalPolynomial) {
  36244. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36245. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36246. defines.USESPHERICALINVERTEX = false;
  36247. }
  36248. else {
  36249. defines.USESPHERICALINVERTEX = true;
  36250. }
  36251. }
  36252. }
  36253. }
  36254. else {
  36255. defines.REFLECTION = false;
  36256. defines.REFLECTIONMAP_3D = false;
  36257. defines.REFLECTIONMAP_SPHERICAL = false;
  36258. defines.REFLECTIONMAP_PLANAR = false;
  36259. defines.REFLECTIONMAP_CUBIC = false;
  36260. defines.REFLECTIONMAP_PROJECTION = false;
  36261. defines.REFLECTIONMAP_SKYBOX = false;
  36262. defines.REFLECTIONMAP_EXPLICIT = false;
  36263. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36264. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36265. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36266. defines.INVERTCUBICMAP = false;
  36267. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36268. defines.USESPHERICALINVERTEX = false;
  36269. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36270. defines.LODINREFLECTIONALPHA = false;
  36271. defines.GAMMAREFLECTION = false;
  36272. }
  36273. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36274. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36275. return false;
  36276. }
  36277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36278. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36279. }
  36280. else {
  36281. defines.LIGHTMAP = false;
  36282. }
  36283. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36284. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36285. return false;
  36286. }
  36287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36288. }
  36289. else {
  36290. defines.EMISSIVE = false;
  36291. }
  36292. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36293. if (this._metallicTexture) {
  36294. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36295. return false;
  36296. }
  36297. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36298. defines.METALLICWORKFLOW = true;
  36299. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36300. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36301. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36302. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36303. }
  36304. else if (this._reflectivityTexture) {
  36305. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36306. return false;
  36307. }
  36308. defines.METALLICWORKFLOW = false;
  36309. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36310. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36311. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36312. }
  36313. else {
  36314. defines.METALLICWORKFLOW = false;
  36315. defines.REFLECTIVITY = false;
  36316. }
  36317. if (this._microSurfaceTexture) {
  36318. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36319. return false;
  36320. }
  36321. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36322. }
  36323. else {
  36324. defines.MICROSURFACEMAP = false;
  36325. }
  36326. }
  36327. else {
  36328. defines.REFLECTIVITY = false;
  36329. defines.MICROSURFACEMAP = false;
  36330. }
  36331. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36332. // Bump texure can not be none blocking.
  36333. if (!this._bumpTexture.isReady()) {
  36334. return false;
  36335. }
  36336. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36337. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36338. defines.PARALLAX = true;
  36339. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36340. }
  36341. else {
  36342. defines.PARALLAX = false;
  36343. }
  36344. }
  36345. else {
  36346. defines.BUMP = false;
  36347. }
  36348. var refractionTexture = this._getRefractionTexture();
  36349. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36350. if (!refractionTexture.isReadyOrNotBlocking()) {
  36351. return false;
  36352. }
  36353. defines.REFRACTION = true;
  36354. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36355. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36356. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36357. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36358. if (this._linkRefractionWithTransparency) {
  36359. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36360. }
  36361. }
  36362. else {
  36363. defines.REFRACTION = false;
  36364. }
  36365. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36366. // This is blocking.
  36367. if (!this._environmentBRDFTexture.isReady()) {
  36368. return false;
  36369. }
  36370. defines.ENVIRONMENTBRDF = true;
  36371. }
  36372. else {
  36373. defines.ENVIRONMENTBRDF = false;
  36374. }
  36375. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36376. defines.ALPHAFROMALBEDO = true;
  36377. }
  36378. else {
  36379. defines.ALPHAFROMALBEDO = false;
  36380. }
  36381. }
  36382. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36383. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36384. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36385. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36386. defines.METALLICWORKFLOW = true;
  36387. }
  36388. else {
  36389. defines.METALLICWORKFLOW = false;
  36390. }
  36391. if (!this.backFaceCulling && this._twoSidedLighting) {
  36392. defines.TWOSIDEDLIGHTING = true;
  36393. }
  36394. else {
  36395. defines.TWOSIDEDLIGHTING = false;
  36396. }
  36397. defines.ALPHATESTVALUE = this._alphaCutOff;
  36398. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36399. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36400. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36401. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36402. }
  36403. if (defines._areImageProcessingDirty) {
  36404. if (!this._imageProcessingConfiguration.isReady()) {
  36405. return false;
  36406. }
  36407. this._imageProcessingConfiguration.prepareDefines(defines);
  36408. }
  36409. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36410. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36411. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36412. // Misc.
  36413. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36414. // Values that need to be evaluated on every frame
  36415. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36416. // Attribs
  36417. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36418. var bufferMesh = null;
  36419. if (mesh instanceof BABYLON.InstancedMesh) {
  36420. bufferMesh = mesh.sourceMesh;
  36421. }
  36422. else if (mesh instanceof BABYLON.Mesh) {
  36423. bufferMesh = mesh;
  36424. }
  36425. if (bufferMesh) {
  36426. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36427. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36428. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36429. var normals = normalVertexBuffer.getData();
  36430. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36431. var strideSize = normalVertexBuffer.getStrideSize();
  36432. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36433. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36434. defines.NORMAL = false;
  36435. }
  36436. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36437. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36438. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36439. var tangents = tangentVertexBuffer.getData();
  36440. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36441. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36442. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36443. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36444. defines.TANGENT = false;
  36445. }
  36446. }
  36447. }
  36448. else {
  36449. if (!scene.getEngine().getCaps().standardDerivatives) {
  36450. bufferMesh.createNormals(true);
  36451. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36452. }
  36453. }
  36454. }
  36455. }
  36456. // Get correct effect
  36457. if (defines.isDirty) {
  36458. defines.markAsProcessed();
  36459. scene.resetCachedMaterial();
  36460. // Fallbacks
  36461. var fallbacks = new BABYLON.EffectFallbacks();
  36462. var fallbackRank = 0;
  36463. if (defines.USESPHERICALINVERTEX) {
  36464. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36465. }
  36466. if (defines.FOG) {
  36467. fallbacks.addFallback(fallbackRank, "FOG");
  36468. }
  36469. if (defines.POINTSIZE) {
  36470. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36471. }
  36472. if (defines.LOGARITHMICDEPTH) {
  36473. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36474. }
  36475. if (defines.PARALLAX) {
  36476. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36477. }
  36478. if (defines.PARALLAXOCCLUSION) {
  36479. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36480. }
  36481. if (defines.ENVIRONMENTBRDF) {
  36482. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36483. }
  36484. if (defines.TANGENT) {
  36485. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36486. }
  36487. if (defines.BUMP) {
  36488. fallbacks.addFallback(fallbackRank++, "BUMP");
  36489. }
  36490. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36491. if (defines.SPECULARTERM) {
  36492. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36493. }
  36494. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36495. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36496. }
  36497. if (defines.LIGHTMAP) {
  36498. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36499. }
  36500. if (defines.NORMAL) {
  36501. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36502. }
  36503. if (defines.AMBIENT) {
  36504. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36505. }
  36506. if (defines.EMISSIVE) {
  36507. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36508. }
  36509. if (defines.VERTEXCOLOR) {
  36510. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36511. }
  36512. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36513. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36514. }
  36515. if (defines.MORPHTARGETS) {
  36516. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36517. }
  36518. //Attributes
  36519. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36520. if (defines.NORMAL) {
  36521. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36522. }
  36523. if (defines.TANGENT) {
  36524. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36525. }
  36526. if (defines.UV1) {
  36527. attribs.push(BABYLON.VertexBuffer.UVKind);
  36528. }
  36529. if (defines.UV2) {
  36530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36531. }
  36532. if (defines.VERTEXCOLOR) {
  36533. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36534. }
  36535. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36536. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36537. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36538. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36539. "vFogInfos", "vFogColor", "pointSize",
  36540. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36541. "mBones",
  36542. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36543. "vLightingIntensity",
  36544. "logarithmicDepthConstant",
  36545. "vSphericalX", "vSphericalY", "vSphericalZ",
  36546. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36547. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36548. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36549. "vTangentSpaceParams"
  36550. ];
  36551. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36552. "bumpSampler", "lightmapSampler", "opacitySampler",
  36553. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36554. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36555. "microSurfaceSampler", "environmentBrdfSampler"];
  36556. var uniformBuffers = ["Material", "Scene"];
  36557. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36558. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36559. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36560. uniformsNames: uniforms,
  36561. uniformBuffersNames: uniformBuffers,
  36562. samplers: samplers,
  36563. defines: defines,
  36564. maxSimultaneousLights: this._maxSimultaneousLights
  36565. });
  36566. var onCompiled = function (effect) {
  36567. if (_this.onCompiled) {
  36568. _this.onCompiled(effect);
  36569. }
  36570. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36571. };
  36572. var join = defines.toString();
  36573. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36574. attributes: attribs,
  36575. uniformsNames: uniforms,
  36576. uniformBuffersNames: uniformBuffers,
  36577. samplers: samplers,
  36578. defines: join,
  36579. fallbacks: fallbacks,
  36580. onCompiled: onCompiled,
  36581. onError: this.onError,
  36582. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36583. }, engine), defines);
  36584. this.buildUniformLayout();
  36585. }
  36586. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36587. return false;
  36588. }
  36589. defines._renderId = scene.getRenderId();
  36590. this._wasPreviouslyReady = true;
  36591. return true;
  36592. };
  36593. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36594. // Order is important !
  36595. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36596. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36597. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36598. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36599. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36600. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36601. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36602. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36603. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36604. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36605. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36606. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36607. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36608. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36609. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36610. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36611. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36612. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36613. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36614. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36615. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36616. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36617. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36618. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36619. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36620. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36621. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36622. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36623. this._uniformBuffer.addUniform("pointSize", 1);
  36624. this._uniformBuffer.create();
  36625. };
  36626. PBRBaseMaterial.prototype.unbind = function () {
  36627. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36628. this._uniformBuffer.setTexture("reflectionSampler", null);
  36629. }
  36630. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36631. this._uniformBuffer.setTexture("refractionSampler", null);
  36632. }
  36633. _super.prototype.unbind.call(this);
  36634. };
  36635. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36636. this._activeEffect.setMatrix("world", world);
  36637. };
  36638. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36639. var scene = this.getScene();
  36640. var defines = subMesh._materialDefines;
  36641. if (!defines) {
  36642. return;
  36643. }
  36644. var effect = subMesh.effect;
  36645. if (!effect) {
  36646. return;
  36647. }
  36648. this._activeEffect = effect;
  36649. // Matrices
  36650. this.bindOnlyWorldMatrix(world);
  36651. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36652. // Bones
  36653. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36654. var reflectionTexture = null;
  36655. if (mustRebind) {
  36656. this._uniformBuffer.bindToEffect(effect, "Material");
  36657. this.bindViewProjection(effect);
  36658. reflectionTexture = this._getReflectionTexture();
  36659. var refractionTexture = this._getRefractionTexture();
  36660. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36661. // Texture uniforms
  36662. if (scene.texturesEnabled) {
  36663. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36664. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36665. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36666. }
  36667. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36668. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36669. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36670. }
  36671. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36672. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36673. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36674. }
  36675. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36676. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36677. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36678. var polynomials = reflectionTexture.sphericalPolynomial;
  36679. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36680. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36681. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36682. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36683. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36684. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36685. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36686. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36687. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36688. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36689. }
  36690. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36691. }
  36692. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36693. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36694. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36695. }
  36696. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36697. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36698. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36699. }
  36700. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36701. if (this._metallicTexture) {
  36702. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36703. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36704. }
  36705. else if (this._reflectivityTexture) {
  36706. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36707. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36708. }
  36709. if (this._microSurfaceTexture) {
  36710. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36711. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36712. }
  36713. }
  36714. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36715. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36716. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36717. if (scene._mirroredCameraPosition) {
  36718. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36719. }
  36720. else {
  36721. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36722. }
  36723. }
  36724. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36725. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36726. var depth = 1.0;
  36727. if (!refractionTexture.isCube) {
  36728. if (refractionTexture.depth) {
  36729. depth = refractionTexture.depth;
  36730. }
  36731. }
  36732. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36733. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36734. }
  36735. }
  36736. // Point size
  36737. if (this.pointsCloud) {
  36738. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36739. }
  36740. // Colors
  36741. if (defines.METALLICWORKFLOW) {
  36742. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36743. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36744. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36745. }
  36746. else {
  36747. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36748. }
  36749. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36750. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36751. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36752. // Misc
  36753. this._lightingInfos.x = this._directIntensity;
  36754. this._lightingInfos.y = this._emissiveIntensity;
  36755. this._lightingInfos.z = this._environmentIntensity;
  36756. this._lightingInfos.w = this._specularIntensity;
  36757. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36758. }
  36759. // Textures
  36760. if (scene.texturesEnabled) {
  36761. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36762. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36763. }
  36764. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36765. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36766. }
  36767. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36768. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36769. }
  36770. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36771. if (defines.LODBASEDMICROSFURACE) {
  36772. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36773. }
  36774. else {
  36775. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36776. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36777. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36778. }
  36779. }
  36780. if (defines.ENVIRONMENTBRDF) {
  36781. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36782. }
  36783. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36784. if (defines.LODBASEDMICROSFURACE) {
  36785. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36786. }
  36787. else {
  36788. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36789. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36790. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36791. }
  36792. }
  36793. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36794. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36795. }
  36796. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36797. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36798. }
  36799. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36800. if (this._metallicTexture) {
  36801. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36802. }
  36803. else if (this._reflectivityTexture) {
  36804. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36805. }
  36806. if (this._microSurfaceTexture) {
  36807. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36808. }
  36809. }
  36810. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36811. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36812. }
  36813. }
  36814. // Clip plane
  36815. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36816. // Colors
  36817. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36818. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36819. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36820. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36821. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36822. }
  36823. if (mustRebind || !this.isFrozen) {
  36824. // Lights
  36825. if (scene.lightsEnabled && !this._disableLighting) {
  36826. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36827. }
  36828. // View
  36829. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36830. this.bindView(effect);
  36831. }
  36832. // Fog
  36833. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36834. // Morph targets
  36835. if (defines.NUM_MORPH_INFLUENCERS) {
  36836. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36837. }
  36838. // image processing
  36839. this._imageProcessingConfiguration.bind(this._activeEffect);
  36840. // Log. depth
  36841. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36842. }
  36843. this._uniformBuffer.update();
  36844. this._afterBind(mesh);
  36845. };
  36846. PBRBaseMaterial.prototype.getAnimatables = function () {
  36847. var results = [];
  36848. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36849. results.push(this._albedoTexture);
  36850. }
  36851. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36852. results.push(this._ambientTexture);
  36853. }
  36854. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36855. results.push(this._opacityTexture);
  36856. }
  36857. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36858. results.push(this._reflectionTexture);
  36859. }
  36860. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36861. results.push(this._emissiveTexture);
  36862. }
  36863. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36864. results.push(this._metallicTexture);
  36865. }
  36866. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36867. results.push(this._reflectivityTexture);
  36868. }
  36869. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36870. results.push(this._bumpTexture);
  36871. }
  36872. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36873. results.push(this._lightmapTexture);
  36874. }
  36875. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36876. results.push(this._refractionTexture);
  36877. }
  36878. return results;
  36879. };
  36880. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36881. if (this._reflectionTexture) {
  36882. return this._reflectionTexture;
  36883. }
  36884. return this.getScene().environmentTexture;
  36885. };
  36886. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36887. if (this._refractionTexture) {
  36888. return this._refractionTexture;
  36889. }
  36890. if (this._linkRefractionWithTransparency) {
  36891. return this.getScene().environmentTexture;
  36892. }
  36893. return null;
  36894. };
  36895. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36896. if (forceDisposeTextures) {
  36897. if (this._albedoTexture) {
  36898. this._albedoTexture.dispose();
  36899. }
  36900. if (this._ambientTexture) {
  36901. this._ambientTexture.dispose();
  36902. }
  36903. if (this._opacityTexture) {
  36904. this._opacityTexture.dispose();
  36905. }
  36906. if (this._reflectionTexture) {
  36907. this._reflectionTexture.dispose();
  36908. }
  36909. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36910. this._environmentBRDFTexture.dispose();
  36911. }
  36912. if (this._emissiveTexture) {
  36913. this._emissiveTexture.dispose();
  36914. }
  36915. if (this._metallicTexture) {
  36916. this._metallicTexture.dispose();
  36917. }
  36918. if (this._reflectivityTexture) {
  36919. this._reflectivityTexture.dispose();
  36920. }
  36921. if (this._bumpTexture) {
  36922. this._bumpTexture.dispose();
  36923. }
  36924. if (this._lightmapTexture) {
  36925. this._lightmapTexture.dispose();
  36926. }
  36927. if (this._refractionTexture) {
  36928. this._refractionTexture.dispose();
  36929. }
  36930. }
  36931. this._renderTargets.dispose();
  36932. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36933. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36934. }
  36935. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36936. };
  36937. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36938. __decorate([
  36939. BABYLON.serializeAsImageProcessingConfiguration()
  36940. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36941. __decorate([
  36942. BABYLON.serialize()
  36943. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36944. __decorate([
  36945. BABYLON.serialize()
  36946. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36947. return PBRBaseMaterial;
  36948. }(BABYLON.PushMaterial));
  36949. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36950. })(BABYLON || (BABYLON = {}));
  36951. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36952. var BABYLON;
  36953. (function (BABYLON) {
  36954. var Internals;
  36955. (function (Internals) {
  36956. /**
  36957. * The Physically based simple base material of BJS.
  36958. *
  36959. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36960. * It is used as the base class for both the specGloss and metalRough conventions.
  36961. */
  36962. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36963. __extends(PBRBaseSimpleMaterial, _super);
  36964. /**
  36965. * Instantiates a new PBRMaterial instance.
  36966. *
  36967. * @param name The material name
  36968. * @param scene The scene the material will be use in.
  36969. */
  36970. function PBRBaseSimpleMaterial(name, scene) {
  36971. var _this = _super.call(this, name, scene) || this;
  36972. /**
  36973. * Number of Simultaneous lights allowed on the material.
  36974. */
  36975. _this.maxSimultaneousLights = 4;
  36976. /**
  36977. * If sets to true, disables all the lights affecting the material.
  36978. */
  36979. _this.disableLighting = false;
  36980. /**
  36981. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36982. */
  36983. _this.invertNormalMapX = false;
  36984. /**
  36985. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36986. */
  36987. _this.invertNormalMapY = false;
  36988. /**
  36989. * Emissivie color used to self-illuminate the model.
  36990. */
  36991. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36992. /**
  36993. * Occlusion Channel Strenght.
  36994. */
  36995. _this.occlusionStrength = 1.0;
  36996. _this.useLightmapAsShadowmap = false;
  36997. _this._useAlphaFromAlbedoTexture = true;
  36998. _this._useAmbientInGrayScale = true;
  36999. return _this;
  37000. }
  37001. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37002. /**
  37003. * Gets the current double sided mode.
  37004. */
  37005. get: function () {
  37006. return this._twoSidedLighting;
  37007. },
  37008. /**
  37009. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37010. */
  37011. set: function (value) {
  37012. if (this._twoSidedLighting === value) {
  37013. return;
  37014. }
  37015. this._twoSidedLighting = value;
  37016. this.backFaceCulling = !value;
  37017. this._markAllSubMeshesAsTexturesDirty();
  37018. },
  37019. enumerable: true,
  37020. configurable: true
  37021. });
  37022. /**
  37023. * Return the active textures of the material.
  37024. */
  37025. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37026. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37027. if (this.environmentTexture) {
  37028. activeTextures.push(this.environmentTexture);
  37029. }
  37030. if (this.normalTexture) {
  37031. activeTextures.push(this.normalTexture);
  37032. }
  37033. if (this.emissiveTexture) {
  37034. activeTextures.push(this.emissiveTexture);
  37035. }
  37036. if (this.occlusionTexture) {
  37037. activeTextures.push(this.occlusionTexture);
  37038. }
  37039. if (this.lightmapTexture) {
  37040. activeTextures.push(this.lightmapTexture);
  37041. }
  37042. return activeTextures;
  37043. };
  37044. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37045. if (_super.prototype.hasTexture.call(this, texture)) {
  37046. return true;
  37047. }
  37048. if (this.lightmapTexture === texture) {
  37049. return true;
  37050. }
  37051. return false;
  37052. };
  37053. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37054. return "PBRBaseSimpleMaterial";
  37055. };
  37056. __decorate([
  37057. BABYLON.serialize(),
  37058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37059. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37060. __decorate([
  37061. BABYLON.serialize(),
  37062. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37063. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37064. __decorate([
  37065. BABYLON.serializeAsTexture(),
  37066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37067. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37068. __decorate([
  37069. BABYLON.serialize(),
  37070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37071. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37072. __decorate([
  37073. BABYLON.serialize(),
  37074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37075. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37076. __decorate([
  37077. BABYLON.serializeAsTexture(),
  37078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37079. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37080. __decorate([
  37081. BABYLON.serializeAsColor3("emissive"),
  37082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37083. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37084. __decorate([
  37085. BABYLON.serializeAsTexture(),
  37086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37087. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37088. __decorate([
  37089. BABYLON.serialize(),
  37090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37091. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37092. __decorate([
  37093. BABYLON.serializeAsTexture(),
  37094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37095. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37096. __decorate([
  37097. BABYLON.serialize(),
  37098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37099. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37100. __decorate([
  37101. BABYLON.serialize()
  37102. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37103. __decorate([
  37104. BABYLON.serializeAsTexture(),
  37105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37106. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37107. __decorate([
  37108. BABYLON.serialize(),
  37109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37110. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37111. return PBRBaseSimpleMaterial;
  37112. }(BABYLON.PBRBaseMaterial));
  37113. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37114. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37115. })(BABYLON || (BABYLON = {}));
  37116. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37117. var BABYLON;
  37118. (function (BABYLON) {
  37119. /**
  37120. * The Physically based material of BJS.
  37121. *
  37122. * This offers the main features of a standard PBR material.
  37123. * For more information, please refer to the documentation :
  37124. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37125. */
  37126. var PBRMaterial = /** @class */ (function (_super) {
  37127. __extends(PBRMaterial, _super);
  37128. /**
  37129. * Instantiates a new PBRMaterial instance.
  37130. *
  37131. * @param name The material name
  37132. * @param scene The scene the material will be use in.
  37133. */
  37134. function PBRMaterial(name, scene) {
  37135. var _this = _super.call(this, name, scene) || this;
  37136. /**
  37137. * Intensity of the direct lights e.g. the four lights available in your scene.
  37138. * This impacts both the direct diffuse and specular highlights.
  37139. */
  37140. _this.directIntensity = 1.0;
  37141. /**
  37142. * Intensity of the emissive part of the material.
  37143. * This helps controlling the emissive effect without modifying the emissive color.
  37144. */
  37145. _this.emissiveIntensity = 1.0;
  37146. /**
  37147. * Intensity of the environment e.g. how much the environment will light the object
  37148. * either through harmonics for rough material or through the refelction for shiny ones.
  37149. */
  37150. _this.environmentIntensity = 1.0;
  37151. /**
  37152. * This is a special control allowing the reduction of the specular highlights coming from the
  37153. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37154. */
  37155. _this.specularIntensity = 1.0;
  37156. /**
  37157. * Debug Control allowing disabling the bump map on this material.
  37158. */
  37159. _this.disableBumpMap = false;
  37160. /**
  37161. * AKA Occlusion Texture Intensity in other nomenclature.
  37162. */
  37163. _this.ambientTextureStrength = 1.0;
  37164. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37165. /**
  37166. * AKA Diffuse Color in other nomenclature.
  37167. */
  37168. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37169. /**
  37170. * AKA Specular Color in other nomenclature.
  37171. */
  37172. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37173. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37174. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37175. /**
  37176. * AKA Glossiness in other nomenclature.
  37177. */
  37178. _this.microSurface = 1.0;
  37179. /**
  37180. * source material index of refraction (IOR)' / 'destination material IOR.
  37181. */
  37182. _this.indexOfRefraction = 0.66;
  37183. /**
  37184. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37185. */
  37186. _this.invertRefractionY = false;
  37187. /**
  37188. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37189. * Materials half opaque for instance using refraction could benefit from this control.
  37190. */
  37191. _this.linkRefractionWithTransparency = false;
  37192. _this.useLightmapAsShadowmap = false;
  37193. /**
  37194. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37195. */
  37196. _this.useAlphaFromAlbedoTexture = false;
  37197. /**
  37198. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37199. */
  37200. _this.forceAlphaTest = false;
  37201. /**
  37202. * Defines the alpha limits in alpha test mode.
  37203. */
  37204. _this.alphaCutOff = 0.4;
  37205. /**
  37206. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37207. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37208. */
  37209. _this.useSpecularOverAlpha = true;
  37210. /**
  37211. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37212. */
  37213. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37214. /**
  37215. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37216. */
  37217. _this.useRoughnessFromMetallicTextureAlpha = true;
  37218. /**
  37219. * Specifies if the metallic texture contains the roughness information in its green channel.
  37220. */
  37221. _this.useRoughnessFromMetallicTextureGreen = false;
  37222. /**
  37223. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37224. */
  37225. _this.useMetallnessFromMetallicTextureBlue = false;
  37226. /**
  37227. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37228. */
  37229. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37230. /**
  37231. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37232. */
  37233. _this.useAmbientInGrayScale = false;
  37234. /**
  37235. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37236. * The material will try to infer what glossiness each pixel should be.
  37237. */
  37238. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37239. /**
  37240. * BJS is using an harcoded light falloff based on a manually sets up range.
  37241. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37242. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37243. */
  37244. _this.usePhysicalLightFalloff = true;
  37245. /**
  37246. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37247. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37248. */
  37249. _this.useRadianceOverAlpha = true;
  37250. /**
  37251. * Allows using the bump map in parallax mode.
  37252. */
  37253. _this.useParallax = false;
  37254. /**
  37255. * Allows using the bump map in parallax occlusion mode.
  37256. */
  37257. _this.useParallaxOcclusion = false;
  37258. /**
  37259. * Controls the scale bias of the parallax mode.
  37260. */
  37261. _this.parallaxScaleBias = 0.05;
  37262. /**
  37263. * If sets to true, disables all the lights affecting the material.
  37264. */
  37265. _this.disableLighting = false;
  37266. /**
  37267. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37268. */
  37269. _this.forceIrradianceInFragment = false;
  37270. /**
  37271. * Number of Simultaneous lights allowed on the material.
  37272. */
  37273. _this.maxSimultaneousLights = 4;
  37274. /**
  37275. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37276. */
  37277. _this.invertNormalMapX = false;
  37278. /**
  37279. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37280. */
  37281. _this.invertNormalMapY = false;
  37282. /**
  37283. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37284. */
  37285. _this.twoSidedLighting = false;
  37286. /**
  37287. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37288. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37289. */
  37290. _this.useAlphaFresnel = false;
  37291. /**
  37292. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37293. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37294. */
  37295. _this.useLinearAlphaFresnel = false;
  37296. /**
  37297. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37298. * And/Or occlude the blended part.
  37299. */
  37300. _this.environmentBRDFTexture = null;
  37301. /**
  37302. * Force normal to face away from face.
  37303. */
  37304. _this.forceNormalForward = false;
  37305. /**
  37306. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37307. * makes the reflect vector face the model (under horizon).
  37308. */
  37309. _this.useHorizonOcclusion = true;
  37310. /**
  37311. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37312. * too much the area relying on ambient texture to define their ambient occlusion.
  37313. */
  37314. _this.useRadianceOcclusion = true;
  37315. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37316. return _this;
  37317. }
  37318. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37319. /**
  37320. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37321. */
  37322. get: function () {
  37323. return this._PBRMATERIAL_OPAQUE;
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37329. /**
  37330. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37331. */
  37332. get: function () {
  37333. return this._PBRMATERIAL_ALPHATEST;
  37334. },
  37335. enumerable: true,
  37336. configurable: true
  37337. });
  37338. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37339. /**
  37340. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37341. */
  37342. get: function () {
  37343. return this._PBRMATERIAL_ALPHABLEND;
  37344. },
  37345. enumerable: true,
  37346. configurable: true
  37347. });
  37348. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37349. /**
  37350. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37351. * They are also discarded below the alpha cutoff threshold to improve performances.
  37352. */
  37353. get: function () {
  37354. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37355. },
  37356. enumerable: true,
  37357. configurable: true
  37358. });
  37359. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37360. /**
  37361. * Gets the image processing configuration used either in this material.
  37362. */
  37363. get: function () {
  37364. return this._imageProcessingConfiguration;
  37365. },
  37366. /**
  37367. * Sets the Default image processing configuration used either in the this material.
  37368. *
  37369. * If sets to null, the scene one is in use.
  37370. */
  37371. set: function (value) {
  37372. this._attachImageProcessingConfiguration(value);
  37373. // Ensure the effect will be rebuilt.
  37374. this._markAllSubMeshesAsTexturesDirty();
  37375. },
  37376. enumerable: true,
  37377. configurable: true
  37378. });
  37379. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37380. /**
  37381. * Gets wether the color curves effect is enabled.
  37382. */
  37383. get: function () {
  37384. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37385. },
  37386. /**
  37387. * Sets wether the color curves effect is enabled.
  37388. */
  37389. set: function (value) {
  37390. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37391. },
  37392. enumerable: true,
  37393. configurable: true
  37394. });
  37395. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37396. /**
  37397. * Gets wether the color grading effect is enabled.
  37398. */
  37399. get: function () {
  37400. return this.imageProcessingConfiguration.colorGradingEnabled;
  37401. },
  37402. /**
  37403. * Gets wether the color grading effect is enabled.
  37404. */
  37405. set: function (value) {
  37406. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37407. },
  37408. enumerable: true,
  37409. configurable: true
  37410. });
  37411. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37412. /**
  37413. * Gets wether tonemapping is enabled or not.
  37414. */
  37415. get: function () {
  37416. return this._imageProcessingConfiguration.toneMappingEnabled;
  37417. },
  37418. /**
  37419. * Sets wether tonemapping is enabled or not
  37420. */
  37421. set: function (value) {
  37422. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37423. },
  37424. enumerable: true,
  37425. configurable: true
  37426. });
  37427. ;
  37428. ;
  37429. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37430. /**
  37431. * The camera exposure used on this material.
  37432. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37433. * This corresponds to a photographic exposure.
  37434. */
  37435. get: function () {
  37436. return this._imageProcessingConfiguration.exposure;
  37437. },
  37438. /**
  37439. * The camera exposure used on this material.
  37440. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37441. * This corresponds to a photographic exposure.
  37442. */
  37443. set: function (value) {
  37444. this._imageProcessingConfiguration.exposure = value;
  37445. },
  37446. enumerable: true,
  37447. configurable: true
  37448. });
  37449. ;
  37450. ;
  37451. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37452. /**
  37453. * Gets The camera contrast used on this material.
  37454. */
  37455. get: function () {
  37456. return this._imageProcessingConfiguration.contrast;
  37457. },
  37458. /**
  37459. * Sets The camera contrast used on this material.
  37460. */
  37461. set: function (value) {
  37462. this._imageProcessingConfiguration.contrast = value;
  37463. },
  37464. enumerable: true,
  37465. configurable: true
  37466. });
  37467. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37468. /**
  37469. * Gets the Color Grading 2D Lookup Texture.
  37470. */
  37471. get: function () {
  37472. return this._imageProcessingConfiguration.colorGradingTexture;
  37473. },
  37474. /**
  37475. * Sets the Color Grading 2D Lookup Texture.
  37476. */
  37477. set: function (value) {
  37478. this._imageProcessingConfiguration.colorGradingTexture = value;
  37479. },
  37480. enumerable: true,
  37481. configurable: true
  37482. });
  37483. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37484. /**
  37485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37487. * 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;
  37488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37489. */
  37490. get: function () {
  37491. return this._imageProcessingConfiguration.colorCurves;
  37492. },
  37493. /**
  37494. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37495. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37496. * 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;
  37497. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37498. */
  37499. set: function (value) {
  37500. this._imageProcessingConfiguration.colorCurves = value;
  37501. },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. PBRMaterial.prototype.getClassName = function () {
  37506. return "PBRMaterial";
  37507. };
  37508. PBRMaterial.prototype.getActiveTextures = function () {
  37509. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37510. if (this._albedoTexture) {
  37511. activeTextures.push(this._albedoTexture);
  37512. }
  37513. if (this._ambientTexture) {
  37514. activeTextures.push(this._ambientTexture);
  37515. }
  37516. if (this._opacityTexture) {
  37517. activeTextures.push(this._opacityTexture);
  37518. }
  37519. if (this._reflectionTexture) {
  37520. activeTextures.push(this._reflectionTexture);
  37521. }
  37522. if (this._emissiveTexture) {
  37523. activeTextures.push(this._emissiveTexture);
  37524. }
  37525. if (this._reflectivityTexture) {
  37526. activeTextures.push(this._reflectivityTexture);
  37527. }
  37528. if (this._metallicTexture) {
  37529. activeTextures.push(this._metallicTexture);
  37530. }
  37531. if (this._microSurfaceTexture) {
  37532. activeTextures.push(this._microSurfaceTexture);
  37533. }
  37534. if (this._bumpTexture) {
  37535. activeTextures.push(this._bumpTexture);
  37536. }
  37537. if (this._lightmapTexture) {
  37538. activeTextures.push(this._lightmapTexture);
  37539. }
  37540. if (this._refractionTexture) {
  37541. activeTextures.push(this._refractionTexture);
  37542. }
  37543. return activeTextures;
  37544. };
  37545. PBRMaterial.prototype.hasTexture = function (texture) {
  37546. if (_super.prototype.hasTexture.call(this, texture)) {
  37547. return true;
  37548. }
  37549. if (this._albedoTexture === texture) {
  37550. return true;
  37551. }
  37552. if (this._ambientTexture === texture) {
  37553. return true;
  37554. }
  37555. if (this._opacityTexture === texture) {
  37556. return true;
  37557. }
  37558. if (this._reflectionTexture === texture) {
  37559. return true;
  37560. }
  37561. if (this._reflectivityTexture === texture) {
  37562. return true;
  37563. }
  37564. if (this._metallicTexture === texture) {
  37565. return true;
  37566. }
  37567. if (this._microSurfaceTexture === texture) {
  37568. return true;
  37569. }
  37570. if (this._bumpTexture === texture) {
  37571. return true;
  37572. }
  37573. if (this._lightmapTexture === texture) {
  37574. return true;
  37575. }
  37576. if (this._refractionTexture === texture) {
  37577. return true;
  37578. }
  37579. return false;
  37580. };
  37581. PBRMaterial.prototype.clone = function (name) {
  37582. var _this = this;
  37583. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37584. clone.id = name;
  37585. clone.name = name;
  37586. return clone;
  37587. };
  37588. PBRMaterial.prototype.serialize = function () {
  37589. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37590. serializationObject.customType = "BABYLON.PBRMaterial";
  37591. return serializationObject;
  37592. };
  37593. // Statics
  37594. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37595. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37596. };
  37597. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37598. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37599. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37600. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37601. __decorate([
  37602. BABYLON.serialize(),
  37603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37604. ], PBRMaterial.prototype, "directIntensity", void 0);
  37605. __decorate([
  37606. BABYLON.serialize(),
  37607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37608. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37609. __decorate([
  37610. BABYLON.serialize(),
  37611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37612. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37613. __decorate([
  37614. BABYLON.serialize(),
  37615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37616. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37617. __decorate([
  37618. BABYLON.serialize(),
  37619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37620. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37621. __decorate([
  37622. BABYLON.serializeAsTexture(),
  37623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37624. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37625. __decorate([
  37626. BABYLON.serializeAsTexture(),
  37627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37628. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37629. __decorate([
  37630. BABYLON.serialize(),
  37631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37632. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37633. __decorate([
  37634. BABYLON.serializeAsTexture(),
  37635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37636. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37637. __decorate([
  37638. BABYLON.serializeAsTexture(),
  37639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37640. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37641. __decorate([
  37642. BABYLON.serializeAsTexture(),
  37643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37644. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37645. __decorate([
  37646. BABYLON.serializeAsTexture(),
  37647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37648. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37649. __decorate([
  37650. BABYLON.serializeAsTexture(),
  37651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37652. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37653. __decorate([
  37654. BABYLON.serialize(),
  37655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37656. ], PBRMaterial.prototype, "metallic", void 0);
  37657. __decorate([
  37658. BABYLON.serialize(),
  37659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37660. ], PBRMaterial.prototype, "roughness", void 0);
  37661. __decorate([
  37662. BABYLON.serializeAsTexture(),
  37663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37664. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37665. __decorate([
  37666. BABYLON.serializeAsTexture(),
  37667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37668. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37669. __decorate([
  37670. BABYLON.serializeAsTexture(),
  37671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37672. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37673. __decorate([
  37674. BABYLON.serializeAsTexture(),
  37675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37676. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37677. __decorate([
  37678. BABYLON.serializeAsColor3("ambient"),
  37679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37680. ], PBRMaterial.prototype, "ambientColor", void 0);
  37681. __decorate([
  37682. BABYLON.serializeAsColor3("albedo"),
  37683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37684. ], PBRMaterial.prototype, "albedoColor", void 0);
  37685. __decorate([
  37686. BABYLON.serializeAsColor3("reflectivity"),
  37687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37688. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37689. __decorate([
  37690. BABYLON.serializeAsColor3("reflection"),
  37691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37692. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37693. __decorate([
  37694. BABYLON.serializeAsColor3("emissive"),
  37695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37696. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37697. __decorate([
  37698. BABYLON.serialize(),
  37699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37700. ], PBRMaterial.prototype, "microSurface", void 0);
  37701. __decorate([
  37702. BABYLON.serialize(),
  37703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37704. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37705. __decorate([
  37706. BABYLON.serialize(),
  37707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37708. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37709. __decorate([
  37710. BABYLON.serialize(),
  37711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37712. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37713. __decorate([
  37714. BABYLON.serialize(),
  37715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37716. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37717. __decorate([
  37718. BABYLON.serialize(),
  37719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37720. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37721. __decorate([
  37722. BABYLON.serialize(),
  37723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37724. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37725. __decorate([
  37726. BABYLON.serialize(),
  37727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37728. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37729. __decorate([
  37730. BABYLON.serialize(),
  37731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37732. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37733. __decorate([
  37734. BABYLON.serialize(),
  37735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37736. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37737. __decorate([
  37738. BABYLON.serialize(),
  37739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37740. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37741. __decorate([
  37742. BABYLON.serialize(),
  37743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37744. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37745. __decorate([
  37746. BABYLON.serialize(),
  37747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37748. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37749. __decorate([
  37750. BABYLON.serialize(),
  37751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37752. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37753. __decorate([
  37754. BABYLON.serialize(),
  37755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37756. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37757. __decorate([
  37758. BABYLON.serialize(),
  37759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37760. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37761. __decorate([
  37762. BABYLON.serialize(),
  37763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37764. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37765. __decorate([
  37766. BABYLON.serialize(),
  37767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37768. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37769. __decorate([
  37770. BABYLON.serialize(),
  37771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37772. ], PBRMaterial.prototype, "useParallax", void 0);
  37773. __decorate([
  37774. BABYLON.serialize(),
  37775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37776. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37777. __decorate([
  37778. BABYLON.serialize(),
  37779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37780. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37781. __decorate([
  37782. BABYLON.serialize(),
  37783. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37784. ], PBRMaterial.prototype, "disableLighting", void 0);
  37785. __decorate([
  37786. BABYLON.serialize(),
  37787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37788. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37789. __decorate([
  37790. BABYLON.serialize(),
  37791. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37792. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37793. __decorate([
  37794. BABYLON.serialize(),
  37795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37796. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37797. __decorate([
  37798. BABYLON.serialize(),
  37799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37800. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37801. __decorate([
  37802. BABYLON.serialize(),
  37803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37804. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37805. __decorate([
  37806. BABYLON.serialize(),
  37807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37808. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37809. __decorate([
  37810. BABYLON.serialize(),
  37811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37812. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37813. __decorate([
  37814. BABYLON.serializeAsTexture(),
  37815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37816. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37817. __decorate([
  37818. BABYLON.serialize(),
  37819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37820. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37821. __decorate([
  37822. BABYLON.serialize(),
  37823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37824. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37825. __decorate([
  37826. BABYLON.serialize(),
  37827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37828. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37829. return PBRMaterial;
  37830. }(BABYLON.PBRBaseMaterial));
  37831. BABYLON.PBRMaterial = PBRMaterial;
  37832. })(BABYLON || (BABYLON = {}));
  37833. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37834. var BABYLON;
  37835. (function (BABYLON) {
  37836. /**
  37837. * The PBR material of BJS following the metal roughness convention.
  37838. *
  37839. * This fits to the PBR convention in the GLTF definition:
  37840. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37841. */
  37842. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37843. __extends(PBRMetallicRoughnessMaterial, _super);
  37844. /**
  37845. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37846. *
  37847. * @param name The material name
  37848. * @param scene The scene the material will be use in.
  37849. */
  37850. function PBRMetallicRoughnessMaterial(name, scene) {
  37851. var _this = _super.call(this, name, scene) || this;
  37852. _this._useRoughnessFromMetallicTextureAlpha = false;
  37853. _this._useRoughnessFromMetallicTextureGreen = true;
  37854. _this._useMetallnessFromMetallicTextureBlue = true;
  37855. return _this;
  37856. }
  37857. /**
  37858. * Return the currrent class name of the material.
  37859. */
  37860. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37861. return "PBRMetallicRoughnessMaterial";
  37862. };
  37863. /**
  37864. * Return the active textures of the material.
  37865. */
  37866. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37867. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37868. if (this.baseTexture) {
  37869. activeTextures.push(this.baseTexture);
  37870. }
  37871. if (this.metallicRoughnessTexture) {
  37872. activeTextures.push(this.metallicRoughnessTexture);
  37873. }
  37874. return activeTextures;
  37875. };
  37876. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37877. if (_super.prototype.hasTexture.call(this, texture)) {
  37878. return true;
  37879. }
  37880. if (this.baseTexture === texture) {
  37881. return true;
  37882. }
  37883. if (this.metallicRoughnessTexture === texture) {
  37884. return true;
  37885. }
  37886. return false;
  37887. };
  37888. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37889. var _this = this;
  37890. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37891. clone.id = name;
  37892. clone.name = name;
  37893. return clone;
  37894. };
  37895. /**
  37896. * Serialize the material to a parsable JSON object.
  37897. */
  37898. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37899. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37900. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37901. return serializationObject;
  37902. };
  37903. /**
  37904. * Parses a JSON object correponding to the serialize function.
  37905. */
  37906. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37907. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37908. };
  37909. __decorate([
  37910. BABYLON.serializeAsColor3(),
  37911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37912. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37913. __decorate([
  37914. BABYLON.serializeAsTexture(),
  37915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37916. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37917. __decorate([
  37918. BABYLON.serialize(),
  37919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37920. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37921. __decorate([
  37922. BABYLON.serialize(),
  37923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37924. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37925. __decorate([
  37926. BABYLON.serializeAsTexture(),
  37927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37928. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37929. return PBRMetallicRoughnessMaterial;
  37930. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37931. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37932. })(BABYLON || (BABYLON = {}));
  37933. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37934. var BABYLON;
  37935. (function (BABYLON) {
  37936. /**
  37937. * The PBR material of BJS following the specular glossiness convention.
  37938. *
  37939. * This fits to the PBR convention in the GLTF definition:
  37940. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37941. */
  37942. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37943. __extends(PBRSpecularGlossinessMaterial, _super);
  37944. /**
  37945. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37946. *
  37947. * @param name The material name
  37948. * @param scene The scene the material will be use in.
  37949. */
  37950. function PBRSpecularGlossinessMaterial(name, scene) {
  37951. var _this = _super.call(this, name, scene) || this;
  37952. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37953. return _this;
  37954. }
  37955. /**
  37956. * Return the currrent class name of the material.
  37957. */
  37958. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37959. return "PBRSpecularGlossinessMaterial";
  37960. };
  37961. /**
  37962. * Return the active textures of the material.
  37963. */
  37964. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37965. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37966. if (this.diffuseTexture) {
  37967. activeTextures.push(this.diffuseTexture);
  37968. }
  37969. if (this.specularGlossinessTexture) {
  37970. activeTextures.push(this.specularGlossinessTexture);
  37971. }
  37972. return activeTextures;
  37973. };
  37974. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37975. if (_super.prototype.hasTexture.call(this, texture)) {
  37976. return true;
  37977. }
  37978. if (this.diffuseTexture === texture) {
  37979. return true;
  37980. }
  37981. if (this.specularGlossinessTexture === texture) {
  37982. return true;
  37983. }
  37984. return false;
  37985. };
  37986. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37987. var _this = this;
  37988. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37989. clone.id = name;
  37990. clone.name = name;
  37991. return clone;
  37992. };
  37993. /**
  37994. * Serialize the material to a parsable JSON object.
  37995. */
  37996. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37997. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37998. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37999. return serializationObject;
  38000. };
  38001. /**
  38002. * Parses a JSON object correponding to the serialize function.
  38003. */
  38004. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38005. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38006. };
  38007. __decorate([
  38008. BABYLON.serializeAsColor3("diffuse"),
  38009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38010. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38011. __decorate([
  38012. BABYLON.serializeAsTexture(),
  38013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38014. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38015. __decorate([
  38016. BABYLON.serializeAsColor3("specular"),
  38017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38018. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38019. __decorate([
  38020. BABYLON.serialize(),
  38021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38022. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38023. __decorate([
  38024. BABYLON.serializeAsTexture(),
  38025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38026. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38027. return PBRSpecularGlossinessMaterial;
  38028. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38029. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38030. })(BABYLON || (BABYLON = {}));
  38031. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38032. var BABYLON;
  38033. (function (BABYLON) {
  38034. BABYLON.CameraInputTypes = {};
  38035. var CameraInputsManager = /** @class */ (function () {
  38036. function CameraInputsManager(camera) {
  38037. this.attached = {};
  38038. this.camera = camera;
  38039. this.checkInputs = function () { };
  38040. }
  38041. CameraInputsManager.prototype.add = function (input) {
  38042. var type = input.getSimpleName();
  38043. if (this.attached[type]) {
  38044. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38045. return;
  38046. }
  38047. this.attached[type] = input;
  38048. input.camera = this.camera;
  38049. //for checkInputs, we are dynamically creating a function
  38050. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38051. if (input.checkInputs) {
  38052. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38053. }
  38054. if (this.attachedElement) {
  38055. input.attachControl(this.attachedElement);
  38056. }
  38057. };
  38058. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38059. for (var cam in this.attached) {
  38060. var input = this.attached[cam];
  38061. if (input === inputToRemove) {
  38062. input.detachControl(this.attachedElement);
  38063. input.camera = null;
  38064. delete this.attached[cam];
  38065. this.rebuildInputCheck();
  38066. }
  38067. }
  38068. };
  38069. CameraInputsManager.prototype.removeByType = function (inputType) {
  38070. for (var cam in this.attached) {
  38071. var input = this.attached[cam];
  38072. if (input.getClassName() === inputType) {
  38073. input.detachControl(this.attachedElement);
  38074. input.camera = null;
  38075. delete this.attached[cam];
  38076. this.rebuildInputCheck();
  38077. }
  38078. }
  38079. };
  38080. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38081. var current = this.checkInputs;
  38082. return function () {
  38083. current();
  38084. fn();
  38085. };
  38086. };
  38087. CameraInputsManager.prototype.attachInput = function (input) {
  38088. if (this.attachedElement) {
  38089. input.attachControl(this.attachedElement, this.noPreventDefault);
  38090. }
  38091. };
  38092. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38093. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38094. if (this.attachedElement) {
  38095. return;
  38096. }
  38097. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38098. this.attachedElement = element;
  38099. this.noPreventDefault = noPreventDefault;
  38100. for (var cam in this.attached) {
  38101. this.attached[cam].attachControl(element, noPreventDefault);
  38102. }
  38103. };
  38104. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38105. if (disconnect === void 0) { disconnect = false; }
  38106. if (this.attachedElement !== element) {
  38107. return;
  38108. }
  38109. for (var cam in this.attached) {
  38110. this.attached[cam].detachControl(element);
  38111. if (disconnect) {
  38112. this.attached[cam].camera = null;
  38113. }
  38114. }
  38115. this.attachedElement = null;
  38116. };
  38117. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38118. this.checkInputs = function () { };
  38119. for (var cam in this.attached) {
  38120. var input = this.attached[cam];
  38121. if (input.checkInputs) {
  38122. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38123. }
  38124. }
  38125. };
  38126. CameraInputsManager.prototype.clear = function () {
  38127. if (this.attachedElement) {
  38128. this.detachElement(this.attachedElement, true);
  38129. }
  38130. this.attached = {};
  38131. this.attachedElement = null;
  38132. this.checkInputs = function () { };
  38133. };
  38134. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38135. var inputs = {};
  38136. for (var cam in this.attached) {
  38137. var input = this.attached[cam];
  38138. var res = BABYLON.SerializationHelper.Serialize(input);
  38139. inputs[input.getClassName()] = res;
  38140. }
  38141. serializedCamera.inputsmgr = inputs;
  38142. };
  38143. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38144. var parsedInputs = parsedCamera.inputsmgr;
  38145. if (parsedInputs) {
  38146. this.clear();
  38147. for (var n in parsedInputs) {
  38148. var construct = BABYLON.CameraInputTypes[n];
  38149. if (construct) {
  38150. var parsedinput = parsedInputs[n];
  38151. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38152. this.add(input);
  38153. }
  38154. }
  38155. }
  38156. else {
  38157. //2016-03-08 this part is for managing backward compatibility
  38158. for (var n in this.attached) {
  38159. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38160. if (construct) {
  38161. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38162. this.remove(this.attached[n]);
  38163. this.add(input);
  38164. }
  38165. }
  38166. }
  38167. };
  38168. return CameraInputsManager;
  38169. }());
  38170. BABYLON.CameraInputsManager = CameraInputsManager;
  38171. })(BABYLON || (BABYLON = {}));
  38172. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38173. var BABYLON;
  38174. (function (BABYLON) {
  38175. var FreeCameraMouseInput = /** @class */ (function () {
  38176. function FreeCameraMouseInput(touchEnabled) {
  38177. if (touchEnabled === void 0) { touchEnabled = true; }
  38178. this.touchEnabled = touchEnabled;
  38179. this.buttons = [0, 1, 2];
  38180. this.angularSensibility = 2000.0;
  38181. this.previousPosition = null;
  38182. }
  38183. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38184. var _this = this;
  38185. var engine = this.camera.getEngine();
  38186. if (!this._pointerInput) {
  38187. this._pointerInput = function (p, s) {
  38188. var evt = p.event;
  38189. if (engine.isInVRExclusivePointerMode) {
  38190. return;
  38191. }
  38192. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38193. return;
  38194. }
  38195. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38196. return;
  38197. }
  38198. var srcElement = (evt.srcElement || evt.target);
  38199. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38200. try {
  38201. srcElement.setPointerCapture(evt.pointerId);
  38202. }
  38203. catch (e) {
  38204. //Nothing to do with the error. Execution will continue.
  38205. }
  38206. _this.previousPosition = {
  38207. x: evt.clientX,
  38208. y: evt.clientY
  38209. };
  38210. if (!noPreventDefault) {
  38211. evt.preventDefault();
  38212. element.focus();
  38213. }
  38214. }
  38215. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38216. try {
  38217. srcElement.releasePointerCapture(evt.pointerId);
  38218. }
  38219. catch (e) {
  38220. //Nothing to do with the error.
  38221. }
  38222. _this.previousPosition = null;
  38223. if (!noPreventDefault) {
  38224. evt.preventDefault();
  38225. }
  38226. }
  38227. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38228. if (!_this.previousPosition || engine.isPointerLock) {
  38229. return;
  38230. }
  38231. var offsetX = evt.clientX - _this.previousPosition.x;
  38232. var offsetY = evt.clientY - _this.previousPosition.y;
  38233. if (_this.camera.getScene().useRightHandedSystem) {
  38234. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38235. }
  38236. else {
  38237. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38238. }
  38239. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38240. _this.previousPosition = {
  38241. x: evt.clientX,
  38242. y: evt.clientY
  38243. };
  38244. if (!noPreventDefault) {
  38245. evt.preventDefault();
  38246. }
  38247. }
  38248. };
  38249. }
  38250. this._onMouseMove = function (evt) {
  38251. if (!engine.isPointerLock) {
  38252. return;
  38253. }
  38254. if (engine.isInVRExclusivePointerMode) {
  38255. return;
  38256. }
  38257. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38258. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38259. if (_this.camera.getScene().useRightHandedSystem) {
  38260. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38261. }
  38262. else {
  38263. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38264. }
  38265. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38266. _this.previousPosition = null;
  38267. if (!noPreventDefault) {
  38268. evt.preventDefault();
  38269. }
  38270. };
  38271. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38272. element.addEventListener("mousemove", this._onMouseMove, false);
  38273. };
  38274. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38275. if (this._observer && element) {
  38276. this.camera.getScene().onPointerObservable.remove(this._observer);
  38277. if (this._onMouseMove) {
  38278. element.removeEventListener("mousemove", this._onMouseMove);
  38279. }
  38280. this._observer = null;
  38281. this._onMouseMove = null;
  38282. this.previousPosition = null;
  38283. }
  38284. };
  38285. FreeCameraMouseInput.prototype.getClassName = function () {
  38286. return "FreeCameraMouseInput";
  38287. };
  38288. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38289. return "mouse";
  38290. };
  38291. __decorate([
  38292. BABYLON.serialize()
  38293. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38294. __decorate([
  38295. BABYLON.serialize()
  38296. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38297. return FreeCameraMouseInput;
  38298. }());
  38299. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38300. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38301. })(BABYLON || (BABYLON = {}));
  38302. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38303. var BABYLON;
  38304. (function (BABYLON) {
  38305. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38306. function FreeCameraKeyboardMoveInput() {
  38307. this._keys = new Array();
  38308. this.keysUp = [38];
  38309. this.keysDown = [40];
  38310. this.keysLeft = [37];
  38311. this.keysRight = [39];
  38312. }
  38313. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38314. var _this = this;
  38315. if (this._onCanvasBlurObserver) {
  38316. return;
  38317. }
  38318. this._scene = this.camera.getScene();
  38319. this._engine = this._scene.getEngine();
  38320. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38321. _this._keys = [];
  38322. });
  38323. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38324. var evt = info.event;
  38325. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38326. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38327. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38328. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38329. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38330. var index = _this._keys.indexOf(evt.keyCode);
  38331. if (index === -1) {
  38332. _this._keys.push(evt.keyCode);
  38333. }
  38334. if (!noPreventDefault) {
  38335. evt.preventDefault();
  38336. }
  38337. }
  38338. }
  38339. else {
  38340. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38341. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38342. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38343. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38344. var index = _this._keys.indexOf(evt.keyCode);
  38345. if (index >= 0) {
  38346. _this._keys.splice(index, 1);
  38347. }
  38348. if (!noPreventDefault) {
  38349. evt.preventDefault();
  38350. }
  38351. }
  38352. }
  38353. });
  38354. };
  38355. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38356. if (this._scene) {
  38357. if (this._onKeyboardObserver) {
  38358. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38359. }
  38360. if (this._onCanvasBlurObserver) {
  38361. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38362. }
  38363. this._onKeyboardObserver = null;
  38364. this._onCanvasBlurObserver = null;
  38365. }
  38366. this._keys = [];
  38367. };
  38368. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38369. if (this._onKeyboardObserver) {
  38370. var camera = this.camera;
  38371. // Keyboard
  38372. for (var index = 0; index < this._keys.length; index++) {
  38373. var keyCode = this._keys[index];
  38374. var speed = camera._computeLocalCameraSpeed();
  38375. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38376. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38377. }
  38378. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38379. camera._localDirection.copyFromFloats(0, 0, speed);
  38380. }
  38381. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38382. camera._localDirection.copyFromFloats(speed, 0, 0);
  38383. }
  38384. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38385. camera._localDirection.copyFromFloats(0, 0, -speed);
  38386. }
  38387. if (camera.getScene().useRightHandedSystem) {
  38388. camera._localDirection.z *= -1;
  38389. }
  38390. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38391. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38392. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38393. }
  38394. }
  38395. };
  38396. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38397. return "FreeCameraKeyboardMoveInput";
  38398. };
  38399. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38400. this._keys = [];
  38401. };
  38402. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38403. return "keyboard";
  38404. };
  38405. __decorate([
  38406. BABYLON.serialize()
  38407. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38408. __decorate([
  38409. BABYLON.serialize()
  38410. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38411. __decorate([
  38412. BABYLON.serialize()
  38413. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38414. __decorate([
  38415. BABYLON.serialize()
  38416. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38417. return FreeCameraKeyboardMoveInput;
  38418. }());
  38419. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38420. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38421. })(BABYLON || (BABYLON = {}));
  38422. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38423. var BABYLON;
  38424. (function (BABYLON) {
  38425. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38426. __extends(FreeCameraInputsManager, _super);
  38427. function FreeCameraInputsManager(camera) {
  38428. return _super.call(this, camera) || this;
  38429. }
  38430. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38431. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38432. return this;
  38433. };
  38434. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38435. if (touchEnabled === void 0) { touchEnabled = true; }
  38436. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38437. return this;
  38438. };
  38439. FreeCameraInputsManager.prototype.addGamepad = function () {
  38440. this.add(new BABYLON.FreeCameraGamepadInput());
  38441. return this;
  38442. };
  38443. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38444. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38445. return this;
  38446. };
  38447. FreeCameraInputsManager.prototype.addTouch = function () {
  38448. this.add(new BABYLON.FreeCameraTouchInput());
  38449. return this;
  38450. };
  38451. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38452. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38453. return this;
  38454. };
  38455. return FreeCameraInputsManager;
  38456. }(BABYLON.CameraInputsManager));
  38457. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38458. })(BABYLON || (BABYLON = {}));
  38459. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38460. var BABYLON;
  38461. (function (BABYLON) {
  38462. var TargetCamera = /** @class */ (function (_super) {
  38463. __extends(TargetCamera, _super);
  38464. function TargetCamera(name, position, scene) {
  38465. var _this = _super.call(this, name, position, scene) || this;
  38466. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38467. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38468. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38469. _this.speed = 2.0;
  38470. _this.noRotationConstraint = false;
  38471. _this.lockedTarget = null;
  38472. _this._currentTarget = BABYLON.Vector3.Zero();
  38473. _this._viewMatrix = BABYLON.Matrix.Zero();
  38474. _this._camMatrix = BABYLON.Matrix.Zero();
  38475. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38476. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38477. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38478. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38479. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38480. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38481. _this._tempMatrix = BABYLON.Matrix.Zero();
  38482. return _this;
  38483. }
  38484. TargetCamera.prototype.getFrontPosition = function (distance) {
  38485. var direction = this.getTarget().subtract(this.position);
  38486. direction.normalize();
  38487. direction.scaleInPlace(distance);
  38488. return this.globalPosition.add(direction);
  38489. };
  38490. TargetCamera.prototype._getLockedTargetPosition = function () {
  38491. if (!this.lockedTarget) {
  38492. return null;
  38493. }
  38494. if (this.lockedTarget.absolutePosition) {
  38495. this.lockedTarget.computeWorldMatrix();
  38496. }
  38497. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38498. };
  38499. TargetCamera.prototype.storeState = function () {
  38500. this._storedPosition = this.position.clone();
  38501. this._storedRotation = this.rotation.clone();
  38502. if (this.rotationQuaternion) {
  38503. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38504. }
  38505. return _super.prototype.storeState.call(this);
  38506. };
  38507. /**
  38508. * Restored camera state. You must call storeState() first
  38509. */
  38510. TargetCamera.prototype._restoreStateValues = function () {
  38511. if (!_super.prototype._restoreStateValues.call(this)) {
  38512. return false;
  38513. }
  38514. this.position = this._storedPosition.clone();
  38515. this.rotation = this._storedRotation.clone();
  38516. if (this.rotationQuaternion) {
  38517. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38518. }
  38519. this.cameraDirection.copyFromFloats(0, 0, 0);
  38520. this.cameraRotation.copyFromFloats(0, 0);
  38521. return true;
  38522. };
  38523. // Cache
  38524. TargetCamera.prototype._initCache = function () {
  38525. _super.prototype._initCache.call(this);
  38526. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38527. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38528. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38529. };
  38530. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38531. if (!ignoreParentClass) {
  38532. _super.prototype._updateCache.call(this);
  38533. }
  38534. var lockedTargetPosition = this._getLockedTargetPosition();
  38535. if (!lockedTargetPosition) {
  38536. this._cache.lockedTarget = null;
  38537. }
  38538. else {
  38539. if (!this._cache.lockedTarget) {
  38540. this._cache.lockedTarget = lockedTargetPosition.clone();
  38541. }
  38542. else {
  38543. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38544. }
  38545. }
  38546. this._cache.rotation.copyFrom(this.rotation);
  38547. if (this.rotationQuaternion)
  38548. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38549. };
  38550. // Synchronized
  38551. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38552. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38553. return false;
  38554. }
  38555. var lockedTargetPosition = this._getLockedTargetPosition();
  38556. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38557. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38558. };
  38559. // Methods
  38560. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38561. var engine = this.getEngine();
  38562. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38563. };
  38564. // Target
  38565. TargetCamera.prototype.setTarget = function (target) {
  38566. this.upVector.normalize();
  38567. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38568. this._camMatrix.invert();
  38569. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38570. var vDir = target.subtract(this.position);
  38571. if (vDir.x >= 0.0) {
  38572. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38573. }
  38574. else {
  38575. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38576. }
  38577. this.rotation.z = 0;
  38578. if (isNaN(this.rotation.x)) {
  38579. this.rotation.x = 0;
  38580. }
  38581. if (isNaN(this.rotation.y)) {
  38582. this.rotation.y = 0;
  38583. }
  38584. if (isNaN(this.rotation.z)) {
  38585. this.rotation.z = 0;
  38586. }
  38587. if (this.rotationQuaternion) {
  38588. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38589. }
  38590. };
  38591. /**
  38592. * Return the current target position of the camera. This value is expressed in local space.
  38593. */
  38594. TargetCamera.prototype.getTarget = function () {
  38595. return this._currentTarget;
  38596. };
  38597. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38598. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38599. };
  38600. TargetCamera.prototype._updatePosition = function () {
  38601. if (this.parent) {
  38602. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38603. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38604. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38605. return;
  38606. }
  38607. this.position.addInPlace(this.cameraDirection);
  38608. };
  38609. TargetCamera.prototype._checkInputs = function () {
  38610. var needToMove = this._decideIfNeedsToMove();
  38611. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38612. // Move
  38613. if (needToMove) {
  38614. this._updatePosition();
  38615. }
  38616. // Rotate
  38617. if (needToRotate) {
  38618. this.rotation.x += this.cameraRotation.x;
  38619. this.rotation.y += this.cameraRotation.y;
  38620. //rotate, if quaternion is set and rotation was used
  38621. if (this.rotationQuaternion) {
  38622. var len = this.rotation.lengthSquared();
  38623. if (len) {
  38624. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38625. }
  38626. }
  38627. if (!this.noRotationConstraint) {
  38628. var limit = (Math.PI / 2) * 0.95;
  38629. if (this.rotation.x > limit)
  38630. this.rotation.x = limit;
  38631. if (this.rotation.x < -limit)
  38632. this.rotation.x = -limit;
  38633. }
  38634. }
  38635. // Inertia
  38636. if (needToMove) {
  38637. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38638. this.cameraDirection.x = 0;
  38639. }
  38640. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38641. this.cameraDirection.y = 0;
  38642. }
  38643. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38644. this.cameraDirection.z = 0;
  38645. }
  38646. this.cameraDirection.scaleInPlace(this.inertia);
  38647. }
  38648. if (needToRotate) {
  38649. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38650. this.cameraRotation.x = 0;
  38651. }
  38652. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38653. this.cameraRotation.y = 0;
  38654. }
  38655. this.cameraRotation.scaleInPlace(this.inertia);
  38656. }
  38657. _super.prototype._checkInputs.call(this);
  38658. };
  38659. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38660. if (this.rotationQuaternion) {
  38661. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38662. }
  38663. else {
  38664. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38665. }
  38666. //update the up vector!
  38667. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38668. };
  38669. TargetCamera.prototype._getViewMatrix = function () {
  38670. if (this.lockedTarget) {
  38671. this.setTarget(this._getLockedTargetPosition());
  38672. }
  38673. // Compute
  38674. this._updateCameraRotationMatrix();
  38675. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38676. // Computing target and final matrix
  38677. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38678. if (this.getScene().useRightHandedSystem) {
  38679. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38680. }
  38681. else {
  38682. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38683. }
  38684. return this._viewMatrix;
  38685. };
  38686. /**
  38687. * @override
  38688. * Override Camera.createRigCamera
  38689. */
  38690. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38691. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38692. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38693. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38694. if (!this.rotationQuaternion) {
  38695. this.rotationQuaternion = new BABYLON.Quaternion();
  38696. }
  38697. rigCamera._cameraRigParams = {};
  38698. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38699. }
  38700. return rigCamera;
  38701. }
  38702. return null;
  38703. };
  38704. /**
  38705. * @override
  38706. * Override Camera._updateRigCameras
  38707. */
  38708. TargetCamera.prototype._updateRigCameras = function () {
  38709. var camLeft = this._rigCameras[0];
  38710. var camRight = this._rigCameras[1];
  38711. switch (this.cameraRigMode) {
  38712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38715. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38716. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38717. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38718. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38719. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38720. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38721. camLeft.setTarget(this.getTarget());
  38722. camRight.setTarget(this.getTarget());
  38723. break;
  38724. case BABYLON.Camera.RIG_MODE_VR:
  38725. if (camLeft.rotationQuaternion) {
  38726. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38727. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38728. }
  38729. else {
  38730. camLeft.rotation.copyFrom(this.rotation);
  38731. camRight.rotation.copyFrom(this.rotation);
  38732. }
  38733. camLeft.position.copyFrom(this.position);
  38734. camRight.position.copyFrom(this.position);
  38735. break;
  38736. }
  38737. _super.prototype._updateRigCameras.call(this);
  38738. };
  38739. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38740. if (!this._rigCamTransformMatrix) {
  38741. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38742. }
  38743. var target = this.getTarget();
  38744. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38745. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38746. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38747. };
  38748. TargetCamera.prototype.getClassName = function () {
  38749. return "TargetCamera";
  38750. };
  38751. __decorate([
  38752. BABYLON.serializeAsVector3()
  38753. ], TargetCamera.prototype, "rotation", void 0);
  38754. __decorate([
  38755. BABYLON.serialize()
  38756. ], TargetCamera.prototype, "speed", void 0);
  38757. __decorate([
  38758. BABYLON.serializeAsMeshReference("lockedTargetId")
  38759. ], TargetCamera.prototype, "lockedTarget", void 0);
  38760. return TargetCamera;
  38761. }(BABYLON.Camera));
  38762. BABYLON.TargetCamera = TargetCamera;
  38763. })(BABYLON || (BABYLON = {}));
  38764. //# sourceMappingURL=babylon.targetCamera.js.map
  38765. var BABYLON;
  38766. (function (BABYLON) {
  38767. var FreeCamera = /** @class */ (function (_super) {
  38768. __extends(FreeCamera, _super);
  38769. function FreeCamera(name, position, scene) {
  38770. var _this = _super.call(this, name, position, scene) || this;
  38771. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38772. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  38773. _this.checkCollisions = false;
  38774. _this.applyGravity = false;
  38775. _this._needMoveForGravity = false;
  38776. _this._oldPosition = BABYLON.Vector3.Zero();
  38777. _this._diffPosition = BABYLON.Vector3.Zero();
  38778. _this._newPosition = BABYLON.Vector3.Zero();
  38779. // Collisions
  38780. _this._collisionMask = -1;
  38781. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38782. if (collidedMesh === void 0) { collidedMesh = null; }
  38783. //TODO move this to the collision coordinator!
  38784. if (_this.getScene().workerCollisions)
  38785. newPosition.multiplyInPlace(_this._collider._radius);
  38786. var updatePosition = function (newPos) {
  38787. _this._newPosition.copyFrom(newPos);
  38788. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38789. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38790. _this.position.addInPlace(_this._diffPosition);
  38791. if (_this.onCollide && collidedMesh) {
  38792. _this.onCollide(collidedMesh);
  38793. }
  38794. }
  38795. };
  38796. updatePosition(newPosition);
  38797. };
  38798. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38799. _this.inputs.addKeyboard().addMouse();
  38800. return _this;
  38801. }
  38802. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38803. //-- begin properties for backward compatibility for inputs
  38804. get: function () {
  38805. var mouse = this.inputs.attached["mouse"];
  38806. if (mouse)
  38807. return mouse.angularSensibility;
  38808. return 0;
  38809. },
  38810. set: function (value) {
  38811. var mouse = this.inputs.attached["mouse"];
  38812. if (mouse)
  38813. mouse.angularSensibility = value;
  38814. },
  38815. enumerable: true,
  38816. configurable: true
  38817. });
  38818. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38819. get: function () {
  38820. var keyboard = this.inputs.attached["keyboard"];
  38821. if (keyboard)
  38822. return keyboard.keysUp;
  38823. return [];
  38824. },
  38825. set: function (value) {
  38826. var keyboard = this.inputs.attached["keyboard"];
  38827. if (keyboard)
  38828. keyboard.keysUp = value;
  38829. },
  38830. enumerable: true,
  38831. configurable: true
  38832. });
  38833. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38834. get: function () {
  38835. var keyboard = this.inputs.attached["keyboard"];
  38836. if (keyboard)
  38837. return keyboard.keysDown;
  38838. return [];
  38839. },
  38840. set: function (value) {
  38841. var keyboard = this.inputs.attached["keyboard"];
  38842. if (keyboard)
  38843. keyboard.keysDown = value;
  38844. },
  38845. enumerable: true,
  38846. configurable: true
  38847. });
  38848. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38849. get: function () {
  38850. var keyboard = this.inputs.attached["keyboard"];
  38851. if (keyboard)
  38852. return keyboard.keysLeft;
  38853. return [];
  38854. },
  38855. set: function (value) {
  38856. var keyboard = this.inputs.attached["keyboard"];
  38857. if (keyboard)
  38858. keyboard.keysLeft = value;
  38859. },
  38860. enumerable: true,
  38861. configurable: true
  38862. });
  38863. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38864. get: function () {
  38865. var keyboard = this.inputs.attached["keyboard"];
  38866. if (keyboard)
  38867. return keyboard.keysRight;
  38868. return [];
  38869. },
  38870. set: function (value) {
  38871. var keyboard = this.inputs.attached["keyboard"];
  38872. if (keyboard)
  38873. keyboard.keysRight = value;
  38874. },
  38875. enumerable: true,
  38876. configurable: true
  38877. });
  38878. // Controls
  38879. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38880. this.inputs.attachElement(element, noPreventDefault);
  38881. };
  38882. FreeCamera.prototype.detachControl = function (element) {
  38883. this.inputs.detachElement(element);
  38884. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38885. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38886. };
  38887. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38888. get: function () {
  38889. return this._collisionMask;
  38890. },
  38891. set: function (mask) {
  38892. this._collisionMask = !isNaN(mask) ? mask : -1;
  38893. },
  38894. enumerable: true,
  38895. configurable: true
  38896. });
  38897. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38898. var globalPosition;
  38899. if (this.parent) {
  38900. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38901. }
  38902. else {
  38903. globalPosition = this.position;
  38904. }
  38905. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38906. this._oldPosition.addInPlace(this.ellipsoidOffset);
  38907. if (!this._collider) {
  38908. this._collider = new BABYLON.Collider();
  38909. }
  38910. this._collider._radius = this.ellipsoid;
  38911. this._collider.collisionMask = this._collisionMask;
  38912. //no need for clone, as long as gravity is not on.
  38913. var actualDisplacement = displacement;
  38914. //add gravity to the direction to prevent the dual-collision checking
  38915. if (this.applyGravity) {
  38916. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38917. actualDisplacement = displacement.add(this.getScene().gravity);
  38918. }
  38919. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38920. };
  38921. FreeCamera.prototype._checkInputs = function () {
  38922. if (!this._localDirection) {
  38923. this._localDirection = BABYLON.Vector3.Zero();
  38924. this._transformedDirection = BABYLON.Vector3.Zero();
  38925. }
  38926. this.inputs.checkInputs();
  38927. _super.prototype._checkInputs.call(this);
  38928. };
  38929. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38930. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38931. };
  38932. FreeCamera.prototype._updatePosition = function () {
  38933. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38934. this._collideWithWorld(this.cameraDirection);
  38935. }
  38936. else {
  38937. _super.prototype._updatePosition.call(this);
  38938. }
  38939. };
  38940. FreeCamera.prototype.dispose = function () {
  38941. this.inputs.clear();
  38942. _super.prototype.dispose.call(this);
  38943. };
  38944. FreeCamera.prototype.getClassName = function () {
  38945. return "FreeCamera";
  38946. };
  38947. __decorate([
  38948. BABYLON.serializeAsVector3()
  38949. ], FreeCamera.prototype, "ellipsoid", void 0);
  38950. __decorate([
  38951. BABYLON.serializeAsVector3()
  38952. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  38953. __decorate([
  38954. BABYLON.serialize()
  38955. ], FreeCamera.prototype, "checkCollisions", void 0);
  38956. __decorate([
  38957. BABYLON.serialize()
  38958. ], FreeCamera.prototype, "applyGravity", void 0);
  38959. return FreeCamera;
  38960. }(BABYLON.TargetCamera));
  38961. BABYLON.FreeCamera = FreeCamera;
  38962. })(BABYLON || (BABYLON = {}));
  38963. //# sourceMappingURL=babylon.freeCamera.js.map
  38964. var BABYLON;
  38965. (function (BABYLON) {
  38966. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38967. function ArcRotateCameraKeyboardMoveInput() {
  38968. this._keys = new Array();
  38969. this.keysUp = [38];
  38970. this.keysDown = [40];
  38971. this.keysLeft = [37];
  38972. this.keysRight = [39];
  38973. this.keysReset = [220];
  38974. this.panningSensibility = 50.0;
  38975. this.zoomingSensibility = 25.0;
  38976. this.useAltToZoom = true;
  38977. }
  38978. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38979. var _this = this;
  38980. if (this._onCanvasBlurObserver) {
  38981. return;
  38982. }
  38983. this._scene = this.camera.getScene();
  38984. this._engine = this._scene.getEngine();
  38985. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38986. _this._keys = [];
  38987. });
  38988. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38989. var evt = info.event;
  38990. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38991. _this._ctrlPressed = evt.ctrlKey;
  38992. _this._altPressed = evt.altKey;
  38993. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38994. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38995. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38996. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38997. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38998. var index = _this._keys.indexOf(evt.keyCode);
  38999. if (index === -1) {
  39000. _this._keys.push(evt.keyCode);
  39001. }
  39002. if (evt.preventDefault) {
  39003. if (!noPreventDefault) {
  39004. evt.preventDefault();
  39005. }
  39006. }
  39007. }
  39008. }
  39009. else {
  39010. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39011. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39012. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39013. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39014. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39015. var index = _this._keys.indexOf(evt.keyCode);
  39016. if (index >= 0) {
  39017. _this._keys.splice(index, 1);
  39018. }
  39019. if (evt.preventDefault) {
  39020. if (!noPreventDefault) {
  39021. evt.preventDefault();
  39022. }
  39023. }
  39024. }
  39025. }
  39026. });
  39027. };
  39028. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39029. if (this._scene) {
  39030. if (this._onKeyboardObserver) {
  39031. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39032. }
  39033. if (this._onCanvasBlurObserver) {
  39034. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39035. }
  39036. this._onKeyboardObserver = null;
  39037. this._onCanvasBlurObserver = null;
  39038. }
  39039. this._keys = [];
  39040. };
  39041. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39042. if (this._onKeyboardObserver) {
  39043. var camera = this.camera;
  39044. for (var index = 0; index < this._keys.length; index++) {
  39045. var keyCode = this._keys[index];
  39046. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39047. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39048. camera.inertialPanningX -= 1 / this.panningSensibility;
  39049. }
  39050. else {
  39051. camera.inertialAlphaOffset -= 0.01;
  39052. }
  39053. }
  39054. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39055. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39056. camera.inertialPanningY += 1 / this.panningSensibility;
  39057. }
  39058. else if (this._altPressed && this.useAltToZoom) {
  39059. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39060. }
  39061. else {
  39062. camera.inertialBetaOffset -= 0.01;
  39063. }
  39064. }
  39065. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39066. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39067. camera.inertialPanningX += 1 / this.panningSensibility;
  39068. }
  39069. else {
  39070. camera.inertialAlphaOffset += 0.01;
  39071. }
  39072. }
  39073. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39074. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39075. camera.inertialPanningY -= 1 / this.panningSensibility;
  39076. }
  39077. else if (this._altPressed && this.useAltToZoom) {
  39078. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39079. }
  39080. else {
  39081. camera.inertialBetaOffset += 0.01;
  39082. }
  39083. }
  39084. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39085. camera.restoreState();
  39086. }
  39087. }
  39088. }
  39089. };
  39090. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39091. return "ArcRotateCameraKeyboardMoveInput";
  39092. };
  39093. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39094. return "keyboard";
  39095. };
  39096. __decorate([
  39097. BABYLON.serialize()
  39098. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39099. __decorate([
  39100. BABYLON.serialize()
  39101. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39102. __decorate([
  39103. BABYLON.serialize()
  39104. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39105. __decorate([
  39106. BABYLON.serialize()
  39107. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39108. __decorate([
  39109. BABYLON.serialize()
  39110. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39111. __decorate([
  39112. BABYLON.serialize()
  39113. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39114. __decorate([
  39115. BABYLON.serialize()
  39116. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39117. __decorate([
  39118. BABYLON.serialize()
  39119. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39120. return ArcRotateCameraKeyboardMoveInput;
  39121. }());
  39122. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39123. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39124. })(BABYLON || (BABYLON = {}));
  39125. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39126. var BABYLON;
  39127. (function (BABYLON) {
  39128. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39129. function ArcRotateCameraMouseWheelInput() {
  39130. this.wheelPrecision = 3.0;
  39131. /**
  39132. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39133. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39134. */
  39135. this.wheelDeltaPercentage = 0;
  39136. }
  39137. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39138. var _this = this;
  39139. this._wheel = function (p, s) {
  39140. //sanity check - this should be a PointerWheel event.
  39141. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39142. return;
  39143. var event = p.event;
  39144. var delta = 0;
  39145. if (event.wheelDelta) {
  39146. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39147. }
  39148. else if (event.detail) {
  39149. delta = -event.detail / _this.wheelPrecision;
  39150. }
  39151. if (delta)
  39152. _this.camera.inertialRadiusOffset += delta;
  39153. if (event.preventDefault) {
  39154. if (!noPreventDefault) {
  39155. event.preventDefault();
  39156. }
  39157. }
  39158. };
  39159. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39160. };
  39161. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39162. if (this._observer && element) {
  39163. this.camera.getScene().onPointerObservable.remove(this._observer);
  39164. this._observer = null;
  39165. this._wheel = null;
  39166. }
  39167. };
  39168. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39169. return "ArcRotateCameraMouseWheelInput";
  39170. };
  39171. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39172. return "mousewheel";
  39173. };
  39174. __decorate([
  39175. BABYLON.serialize()
  39176. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39177. __decorate([
  39178. BABYLON.serialize()
  39179. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39180. return ArcRotateCameraMouseWheelInput;
  39181. }());
  39182. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39183. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39184. })(BABYLON || (BABYLON = {}));
  39185. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39186. var BABYLON;
  39187. (function (BABYLON) {
  39188. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39189. function ArcRotateCameraPointersInput() {
  39190. this.buttons = [0, 1, 2];
  39191. this.angularSensibilityX = 1000.0;
  39192. this.angularSensibilityY = 1000.0;
  39193. this.pinchPrecision = 12.0;
  39194. /**
  39195. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39196. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39197. */
  39198. this.pinchDeltaPercentage = 0;
  39199. this.panningSensibility = 1000.0;
  39200. this.multiTouchPanning = true;
  39201. this.multiTouchPanAndZoom = true;
  39202. this._isPanClick = false;
  39203. this.pinchInwards = true;
  39204. }
  39205. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39206. var _this = this;
  39207. var engine = this.camera.getEngine();
  39208. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39209. var pointA = null;
  39210. var pointB = null;
  39211. var previousPinchSquaredDistance = 0;
  39212. var initialDistance = 0;
  39213. var twoFingerActivityCount = 0;
  39214. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39215. this._pointerInput = function (p, s) {
  39216. var evt = p.event;
  39217. var isTouch = p.event.pointerType === "touch";
  39218. if (engine.isInVRExclusivePointerMode) {
  39219. return;
  39220. }
  39221. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39222. return;
  39223. }
  39224. var srcElement = (evt.srcElement || evt.target);
  39225. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39226. try {
  39227. srcElement.setPointerCapture(evt.pointerId);
  39228. }
  39229. catch (e) {
  39230. //Nothing to do with the error. Execution will continue.
  39231. }
  39232. // Manage panning with pan button click
  39233. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39234. // manage pointers
  39235. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39236. if (pointA === null) {
  39237. pointA = cacheSoloPointer;
  39238. }
  39239. else if (pointB === null) {
  39240. pointB = cacheSoloPointer;
  39241. }
  39242. if (!noPreventDefault) {
  39243. evt.preventDefault();
  39244. element.focus();
  39245. }
  39246. }
  39247. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39248. _this.camera.restoreState();
  39249. }
  39250. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39251. try {
  39252. srcElement.releasePointerCapture(evt.pointerId);
  39253. }
  39254. catch (e) {
  39255. //Nothing to do with the error.
  39256. }
  39257. cacheSoloPointer = null;
  39258. previousPinchSquaredDistance = 0;
  39259. previousMultiTouchPanPosition.isPaning = false;
  39260. previousMultiTouchPanPosition.isPinching = false;
  39261. twoFingerActivityCount = 0;
  39262. initialDistance = 0;
  39263. if (!isTouch) {
  39264. pointB = null; // Mouse and pen are mono pointer
  39265. }
  39266. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39267. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39268. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39269. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39270. if (engine.badOS) {
  39271. pointA = pointB = null;
  39272. }
  39273. else {
  39274. //only remove the impacted pointer in case of multitouch allowing on most
  39275. //platforms switching from rotate to zoom and pan seamlessly.
  39276. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39277. pointA = pointB;
  39278. pointB = null;
  39279. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39280. }
  39281. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39282. pointB = null;
  39283. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39284. }
  39285. else {
  39286. pointA = pointB = null;
  39287. }
  39288. }
  39289. if (!noPreventDefault) {
  39290. evt.preventDefault();
  39291. }
  39292. }
  39293. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39294. if (!noPreventDefault) {
  39295. evt.preventDefault();
  39296. }
  39297. // One button down
  39298. if (pointA && pointB === null && cacheSoloPointer) {
  39299. if (_this.panningSensibility !== 0 &&
  39300. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39301. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39302. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39303. }
  39304. else {
  39305. var offsetX = evt.clientX - cacheSoloPointer.x;
  39306. var offsetY = evt.clientY - cacheSoloPointer.y;
  39307. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39308. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39309. }
  39310. cacheSoloPointer.x = evt.clientX;
  39311. cacheSoloPointer.y = evt.clientY;
  39312. }
  39313. else if (pointA && pointB) {
  39314. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39315. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39316. ed.x = evt.clientX;
  39317. ed.y = evt.clientY;
  39318. var direction = _this.pinchInwards ? 1 : -1;
  39319. var distX = pointA.x - pointB.x;
  39320. var distY = pointA.y - pointB.y;
  39321. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39322. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39323. if (previousPinchSquaredDistance === 0) {
  39324. initialDistance = pinchDistance;
  39325. previousPinchSquaredDistance = pinchSquaredDistance;
  39326. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39327. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39328. return;
  39329. }
  39330. if (_this.multiTouchPanAndZoom) {
  39331. if (_this.pinchDeltaPercentage) {
  39332. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39333. }
  39334. else {
  39335. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39336. (_this.pinchPrecision *
  39337. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39338. direction);
  39339. }
  39340. if (_this.panningSensibility !== 0) {
  39341. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39342. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39343. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39344. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39345. previousMultiTouchPanPosition.x = pointersCenterX;
  39346. previousMultiTouchPanPosition.y = pointersCenterY;
  39347. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39348. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39349. }
  39350. }
  39351. else {
  39352. twoFingerActivityCount++;
  39353. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39354. if (_this.pinchDeltaPercentage) {
  39355. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39356. }
  39357. else {
  39358. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39359. (_this.pinchPrecision *
  39360. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39361. direction);
  39362. }
  39363. previousMultiTouchPanPosition.isPaning = false;
  39364. previousMultiTouchPanPosition.isPinching = true;
  39365. }
  39366. else {
  39367. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39368. if (!previousMultiTouchPanPosition.isPaning) {
  39369. previousMultiTouchPanPosition.isPaning = true;
  39370. previousMultiTouchPanPosition.isPinching = false;
  39371. previousMultiTouchPanPosition.x = ed.x;
  39372. previousMultiTouchPanPosition.y = ed.y;
  39373. return;
  39374. }
  39375. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39376. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39377. }
  39378. }
  39379. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39380. previousMultiTouchPanPosition.x = ed.x;
  39381. previousMultiTouchPanPosition.y = ed.y;
  39382. }
  39383. }
  39384. previousPinchSquaredDistance = pinchSquaredDistance;
  39385. }
  39386. }
  39387. };
  39388. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39389. this._onContextMenu = function (evt) {
  39390. evt.preventDefault();
  39391. };
  39392. if (!this.camera._useCtrlForPanning) {
  39393. element.addEventListener("contextmenu", this._onContextMenu, false);
  39394. }
  39395. this._onLostFocus = function () {
  39396. //this._keys = [];
  39397. pointA = pointB = null;
  39398. previousPinchSquaredDistance = 0;
  39399. previousMultiTouchPanPosition.isPaning = false;
  39400. previousMultiTouchPanPosition.isPinching = false;
  39401. twoFingerActivityCount = 0;
  39402. cacheSoloPointer = null;
  39403. initialDistance = 0;
  39404. };
  39405. this._onMouseMove = function (evt) {
  39406. if (!engine.isPointerLock) {
  39407. return;
  39408. }
  39409. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39410. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39411. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39412. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39413. if (!noPreventDefault) {
  39414. evt.preventDefault();
  39415. }
  39416. };
  39417. this._onGestureStart = function (e) {
  39418. if (window.MSGesture === undefined) {
  39419. return;
  39420. }
  39421. if (!_this._MSGestureHandler) {
  39422. _this._MSGestureHandler = new MSGesture();
  39423. _this._MSGestureHandler.target = element;
  39424. }
  39425. _this._MSGestureHandler.addPointer(e.pointerId);
  39426. };
  39427. this._onGesture = function (e) {
  39428. _this.camera.radius *= e.scale;
  39429. if (e.preventDefault) {
  39430. if (!noPreventDefault) {
  39431. e.stopPropagation();
  39432. e.preventDefault();
  39433. }
  39434. }
  39435. };
  39436. element.addEventListener("mousemove", this._onMouseMove, false);
  39437. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39438. element.addEventListener("MSGestureChange", this._onGesture, false);
  39439. BABYLON.Tools.RegisterTopRootEvents([
  39440. { name: "blur", handler: this._onLostFocus }
  39441. ]);
  39442. };
  39443. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39444. if (this._onLostFocus) {
  39445. BABYLON.Tools.UnregisterTopRootEvents([
  39446. { name: "blur", handler: this._onLostFocus }
  39447. ]);
  39448. }
  39449. if (element && this._observer) {
  39450. this.camera.getScene().onPointerObservable.remove(this._observer);
  39451. this._observer = null;
  39452. if (this._onContextMenu) {
  39453. element.removeEventListener("contextmenu", this._onContextMenu);
  39454. }
  39455. if (this._onMouseMove) {
  39456. element.removeEventListener("mousemove", this._onMouseMove);
  39457. }
  39458. if (this._onGestureStart) {
  39459. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39460. }
  39461. if (this._onGesture) {
  39462. element.removeEventListener("MSGestureChange", this._onGesture);
  39463. }
  39464. this._isPanClick = false;
  39465. this.pinchInwards = true;
  39466. this._onMouseMove = null;
  39467. this._onGestureStart = null;
  39468. this._onGesture = null;
  39469. this._MSGestureHandler = null;
  39470. this._onLostFocus = null;
  39471. this._onContextMenu = null;
  39472. }
  39473. };
  39474. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39475. return "ArcRotateCameraPointersInput";
  39476. };
  39477. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39478. return "pointers";
  39479. };
  39480. __decorate([
  39481. BABYLON.serialize()
  39482. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39483. __decorate([
  39484. BABYLON.serialize()
  39485. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39486. __decorate([
  39487. BABYLON.serialize()
  39488. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39489. __decorate([
  39490. BABYLON.serialize()
  39491. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39492. __decorate([
  39493. BABYLON.serialize()
  39494. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39495. __decorate([
  39496. BABYLON.serialize()
  39497. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39498. __decorate([
  39499. BABYLON.serialize()
  39500. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39501. __decorate([
  39502. BABYLON.serialize()
  39503. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39504. return ArcRotateCameraPointersInput;
  39505. }());
  39506. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39507. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39508. })(BABYLON || (BABYLON = {}));
  39509. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39510. var BABYLON;
  39511. (function (BABYLON) {
  39512. var ArcRotateCamera = /** @class */ (function (_super) {
  39513. __extends(ArcRotateCamera, _super);
  39514. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39515. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39516. _this.inertialAlphaOffset = 0;
  39517. _this.inertialBetaOffset = 0;
  39518. _this.inertialRadiusOffset = 0;
  39519. _this.lowerAlphaLimit = null;
  39520. _this.upperAlphaLimit = null;
  39521. _this.lowerBetaLimit = 0.01;
  39522. _this.upperBetaLimit = Math.PI;
  39523. _this.lowerRadiusLimit = null;
  39524. _this.upperRadiusLimit = null;
  39525. _this.inertialPanningX = 0;
  39526. _this.inertialPanningY = 0;
  39527. _this.pinchToPanMaxDistance = 20;
  39528. _this.panningDistanceLimit = null;
  39529. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39530. _this.panningInertia = 0.9;
  39531. //-- end properties for backward compatibility for inputs
  39532. _this.zoomOnFactor = 1;
  39533. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39534. _this.allowUpsideDown = true;
  39535. _this._viewMatrix = new BABYLON.Matrix();
  39536. // Panning
  39537. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39538. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39539. _this.checkCollisions = false;
  39540. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39541. _this._previousPosition = BABYLON.Vector3.Zero();
  39542. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39543. _this._newPosition = BABYLON.Vector3.Zero();
  39544. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39545. if (collidedMesh === void 0) { collidedMesh = null; }
  39546. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39547. newPosition.multiplyInPlace(_this._collider._radius);
  39548. }
  39549. if (!collidedMesh) {
  39550. _this._previousPosition.copyFrom(_this.position);
  39551. }
  39552. else {
  39553. _this.setPosition(newPosition);
  39554. if (_this.onCollide) {
  39555. _this.onCollide(collidedMesh);
  39556. }
  39557. }
  39558. // Recompute because of constraints
  39559. var cosa = Math.cos(_this.alpha);
  39560. var sina = Math.sin(_this.alpha);
  39561. var cosb = Math.cos(_this.beta);
  39562. var sinb = Math.sin(_this.beta);
  39563. if (sinb === 0) {
  39564. sinb = 0.0001;
  39565. }
  39566. var target = _this._getTargetPosition();
  39567. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39568. _this.position.copyFrom(_this._newPosition);
  39569. var up = _this.upVector;
  39570. if (_this.allowUpsideDown && _this.beta < 0) {
  39571. up = up.clone();
  39572. up = up.negate();
  39573. }
  39574. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39575. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39576. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39577. _this._collisionTriggered = false;
  39578. };
  39579. _this._target = BABYLON.Vector3.Zero();
  39580. if (target) {
  39581. _this.setTarget(target);
  39582. }
  39583. _this.alpha = alpha;
  39584. _this.beta = beta;
  39585. _this.radius = radius;
  39586. _this.getViewMatrix();
  39587. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39588. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39589. return _this;
  39590. }
  39591. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39592. get: function () {
  39593. return this._target;
  39594. },
  39595. set: function (value) {
  39596. this.setTarget(value);
  39597. },
  39598. enumerable: true,
  39599. configurable: true
  39600. });
  39601. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39602. //-- begin properties for backward compatibility for inputs
  39603. get: function () {
  39604. var pointers = this.inputs.attached["pointers"];
  39605. if (pointers)
  39606. return pointers.angularSensibilityX;
  39607. return 0;
  39608. },
  39609. set: function (value) {
  39610. var pointers = this.inputs.attached["pointers"];
  39611. if (pointers) {
  39612. pointers.angularSensibilityX = value;
  39613. }
  39614. },
  39615. enumerable: true,
  39616. configurable: true
  39617. });
  39618. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39619. get: function () {
  39620. var pointers = this.inputs.attached["pointers"];
  39621. if (pointers)
  39622. return pointers.angularSensibilityY;
  39623. return 0;
  39624. },
  39625. set: function (value) {
  39626. var pointers = this.inputs.attached["pointers"];
  39627. if (pointers) {
  39628. pointers.angularSensibilityY = value;
  39629. }
  39630. },
  39631. enumerable: true,
  39632. configurable: true
  39633. });
  39634. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39635. get: function () {
  39636. var pointers = this.inputs.attached["pointers"];
  39637. if (pointers)
  39638. return pointers.pinchPrecision;
  39639. return 0;
  39640. },
  39641. set: function (value) {
  39642. var pointers = this.inputs.attached["pointers"];
  39643. if (pointers) {
  39644. pointers.pinchPrecision = value;
  39645. }
  39646. },
  39647. enumerable: true,
  39648. configurable: true
  39649. });
  39650. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39651. get: function () {
  39652. var pointers = this.inputs.attached["pointers"];
  39653. if (pointers)
  39654. return pointers.pinchDeltaPercentage;
  39655. return 0;
  39656. },
  39657. set: function (value) {
  39658. var pointers = this.inputs.attached["pointers"];
  39659. if (pointers) {
  39660. pointers.pinchDeltaPercentage = value;
  39661. }
  39662. },
  39663. enumerable: true,
  39664. configurable: true
  39665. });
  39666. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39667. get: function () {
  39668. var pointers = this.inputs.attached["pointers"];
  39669. if (pointers)
  39670. return pointers.panningSensibility;
  39671. return 0;
  39672. },
  39673. set: function (value) {
  39674. var pointers = this.inputs.attached["pointers"];
  39675. if (pointers) {
  39676. pointers.panningSensibility = value;
  39677. }
  39678. },
  39679. enumerable: true,
  39680. configurable: true
  39681. });
  39682. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39683. get: function () {
  39684. var keyboard = this.inputs.attached["keyboard"];
  39685. if (keyboard)
  39686. return keyboard.keysUp;
  39687. return [];
  39688. },
  39689. set: function (value) {
  39690. var keyboard = this.inputs.attached["keyboard"];
  39691. if (keyboard)
  39692. keyboard.keysUp = value;
  39693. },
  39694. enumerable: true,
  39695. configurable: true
  39696. });
  39697. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39698. get: function () {
  39699. var keyboard = this.inputs.attached["keyboard"];
  39700. if (keyboard)
  39701. return keyboard.keysDown;
  39702. return [];
  39703. },
  39704. set: function (value) {
  39705. var keyboard = this.inputs.attached["keyboard"];
  39706. if (keyboard)
  39707. keyboard.keysDown = value;
  39708. },
  39709. enumerable: true,
  39710. configurable: true
  39711. });
  39712. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39713. get: function () {
  39714. var keyboard = this.inputs.attached["keyboard"];
  39715. if (keyboard)
  39716. return keyboard.keysLeft;
  39717. return [];
  39718. },
  39719. set: function (value) {
  39720. var keyboard = this.inputs.attached["keyboard"];
  39721. if (keyboard)
  39722. keyboard.keysLeft = value;
  39723. },
  39724. enumerable: true,
  39725. configurable: true
  39726. });
  39727. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39728. get: function () {
  39729. var keyboard = this.inputs.attached["keyboard"];
  39730. if (keyboard)
  39731. return keyboard.keysRight;
  39732. return [];
  39733. },
  39734. set: function (value) {
  39735. var keyboard = this.inputs.attached["keyboard"];
  39736. if (keyboard)
  39737. keyboard.keysRight = value;
  39738. },
  39739. enumerable: true,
  39740. configurable: true
  39741. });
  39742. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39743. get: function () {
  39744. var mousewheel = this.inputs.attached["mousewheel"];
  39745. if (mousewheel)
  39746. return mousewheel.wheelPrecision;
  39747. return 0;
  39748. },
  39749. set: function (value) {
  39750. var mousewheel = this.inputs.attached["mousewheel"];
  39751. if (mousewheel)
  39752. mousewheel.wheelPrecision = value;
  39753. },
  39754. enumerable: true,
  39755. configurable: true
  39756. });
  39757. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39758. get: function () {
  39759. var mousewheel = this.inputs.attached["mousewheel"];
  39760. if (mousewheel)
  39761. return mousewheel.wheelDeltaPercentage;
  39762. return 0;
  39763. },
  39764. set: function (value) {
  39765. var mousewheel = this.inputs.attached["mousewheel"];
  39766. if (mousewheel)
  39767. mousewheel.wheelDeltaPercentage = value;
  39768. },
  39769. enumerable: true,
  39770. configurable: true
  39771. });
  39772. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39773. get: function () {
  39774. return this._bouncingBehavior;
  39775. },
  39776. enumerable: true,
  39777. configurable: true
  39778. });
  39779. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39780. get: function () {
  39781. return this._bouncingBehavior != null;
  39782. },
  39783. set: function (value) {
  39784. if (value === this.useBouncingBehavior) {
  39785. return;
  39786. }
  39787. if (value) {
  39788. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39789. this.addBehavior(this._bouncingBehavior);
  39790. }
  39791. else if (this._bouncingBehavior) {
  39792. this.removeBehavior(this._bouncingBehavior);
  39793. this._bouncingBehavior = null;
  39794. }
  39795. },
  39796. enumerable: true,
  39797. configurable: true
  39798. });
  39799. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39800. get: function () {
  39801. return this._framingBehavior;
  39802. },
  39803. enumerable: true,
  39804. configurable: true
  39805. });
  39806. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39807. get: function () {
  39808. return this._framingBehavior != null;
  39809. },
  39810. set: function (value) {
  39811. if (value === this.useFramingBehavior) {
  39812. return;
  39813. }
  39814. if (value) {
  39815. this._framingBehavior = new BABYLON.FramingBehavior();
  39816. this.addBehavior(this._framingBehavior);
  39817. }
  39818. else if (this._framingBehavior) {
  39819. this.removeBehavior(this._framingBehavior);
  39820. this._framingBehavior = null;
  39821. }
  39822. },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39827. get: function () {
  39828. return this._autoRotationBehavior;
  39829. },
  39830. enumerable: true,
  39831. configurable: true
  39832. });
  39833. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39834. get: function () {
  39835. return this._autoRotationBehavior != null;
  39836. },
  39837. set: function (value) {
  39838. if (value === this.useAutoRotationBehavior) {
  39839. return;
  39840. }
  39841. if (value) {
  39842. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39843. this.addBehavior(this._autoRotationBehavior);
  39844. }
  39845. else if (this._autoRotationBehavior) {
  39846. this.removeBehavior(this._autoRotationBehavior);
  39847. this._autoRotationBehavior = null;
  39848. }
  39849. },
  39850. enumerable: true,
  39851. configurable: true
  39852. });
  39853. // Cache
  39854. ArcRotateCamera.prototype._initCache = function () {
  39855. _super.prototype._initCache.call(this);
  39856. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39857. this._cache.alpha = undefined;
  39858. this._cache.beta = undefined;
  39859. this._cache.radius = undefined;
  39860. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39861. };
  39862. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39863. if (!ignoreParentClass) {
  39864. _super.prototype._updateCache.call(this);
  39865. }
  39866. this._cache._target.copyFrom(this._getTargetPosition());
  39867. this._cache.alpha = this.alpha;
  39868. this._cache.beta = this.beta;
  39869. this._cache.radius = this.radius;
  39870. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39871. };
  39872. ArcRotateCamera.prototype._getTargetPosition = function () {
  39873. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39874. var pos = this._targetHost.getAbsolutePosition();
  39875. if (this._targetBoundingCenter) {
  39876. pos.addToRef(this._targetBoundingCenter, this._target);
  39877. }
  39878. else {
  39879. this._target.copyFrom(pos);
  39880. }
  39881. }
  39882. var lockedTargetPosition = this._getLockedTargetPosition();
  39883. if (lockedTargetPosition) {
  39884. return lockedTargetPosition;
  39885. }
  39886. return this._target;
  39887. };
  39888. ArcRotateCamera.prototype.storeState = function () {
  39889. this._storedAlpha = this.alpha;
  39890. this._storedBeta = this.beta;
  39891. this._storedRadius = this.radius;
  39892. this._storedTarget = this._getTargetPosition().clone();
  39893. return _super.prototype.storeState.call(this);
  39894. };
  39895. /**
  39896. * Restored camera state. You must call storeState() first
  39897. */
  39898. ArcRotateCamera.prototype._restoreStateValues = function () {
  39899. if (!_super.prototype._restoreStateValues.call(this)) {
  39900. return false;
  39901. }
  39902. this.alpha = this._storedAlpha;
  39903. this.beta = this._storedBeta;
  39904. this.radius = this._storedRadius;
  39905. this.setTarget(this._storedTarget.clone());
  39906. this.inertialAlphaOffset = 0;
  39907. this.inertialBetaOffset = 0;
  39908. this.inertialRadiusOffset = 0;
  39909. this.inertialPanningX = 0;
  39910. this.inertialPanningY = 0;
  39911. return true;
  39912. };
  39913. // Synchronized
  39914. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39915. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39916. return false;
  39917. return this._cache._target.equals(this._getTargetPosition())
  39918. && this._cache.alpha === this.alpha
  39919. && this._cache.beta === this.beta
  39920. && this._cache.radius === this.radius
  39921. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39922. };
  39923. // Methods
  39924. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39925. var _this = this;
  39926. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39927. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39928. this._useCtrlForPanning = useCtrlForPanning;
  39929. this._panningMouseButton = panningMouseButton;
  39930. this.inputs.attachElement(element, noPreventDefault);
  39931. this._reset = function () {
  39932. _this.inertialAlphaOffset = 0;
  39933. _this.inertialBetaOffset = 0;
  39934. _this.inertialRadiusOffset = 0;
  39935. _this.inertialPanningX = 0;
  39936. _this.inertialPanningY = 0;
  39937. };
  39938. };
  39939. ArcRotateCamera.prototype.detachControl = function (element) {
  39940. this.inputs.detachElement(element);
  39941. if (this._reset) {
  39942. this._reset();
  39943. }
  39944. };
  39945. ArcRotateCamera.prototype._checkInputs = function () {
  39946. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39947. if (this._collisionTriggered) {
  39948. return;
  39949. }
  39950. this.inputs.checkInputs();
  39951. // Inertia
  39952. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39953. if (this.getScene().useRightHandedSystem) {
  39954. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39955. }
  39956. else {
  39957. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39958. }
  39959. this.beta += this.inertialBetaOffset;
  39960. this.radius -= this.inertialRadiusOffset;
  39961. this.inertialAlphaOffset *= this.inertia;
  39962. this.inertialBetaOffset *= this.inertia;
  39963. this.inertialRadiusOffset *= this.inertia;
  39964. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39965. this.inertialAlphaOffset = 0;
  39966. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39967. this.inertialBetaOffset = 0;
  39968. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39969. this.inertialRadiusOffset = 0;
  39970. }
  39971. // Panning inertia
  39972. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39973. if (!this._localDirection) {
  39974. this._localDirection = BABYLON.Vector3.Zero();
  39975. this._transformedDirection = BABYLON.Vector3.Zero();
  39976. }
  39977. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39978. this._localDirection.multiplyInPlace(this.panningAxis);
  39979. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39980. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39981. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39982. if (!this.panningAxis.y) {
  39983. this._transformedDirection.y = 0;
  39984. }
  39985. if (!this._targetHost) {
  39986. if (this.panningDistanceLimit) {
  39987. this._transformedDirection.addInPlace(this._target);
  39988. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39989. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39990. this._target.copyFrom(this._transformedDirection);
  39991. }
  39992. }
  39993. else {
  39994. this._target.addInPlace(this._transformedDirection);
  39995. }
  39996. }
  39997. this.inertialPanningX *= this.panningInertia;
  39998. this.inertialPanningY *= this.panningInertia;
  39999. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40000. this.inertialPanningX = 0;
  40001. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40002. this.inertialPanningY = 0;
  40003. }
  40004. // Limits
  40005. this._checkLimits();
  40006. _super.prototype._checkInputs.call(this);
  40007. };
  40008. ArcRotateCamera.prototype._checkLimits = function () {
  40009. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40010. if (this.allowUpsideDown && this.beta > Math.PI) {
  40011. this.beta = this.beta - (2 * Math.PI);
  40012. }
  40013. }
  40014. else {
  40015. if (this.beta < this.lowerBetaLimit) {
  40016. this.beta = this.lowerBetaLimit;
  40017. }
  40018. }
  40019. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40020. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40021. this.beta = this.beta + (2 * Math.PI);
  40022. }
  40023. }
  40024. else {
  40025. if (this.beta > this.upperBetaLimit) {
  40026. this.beta = this.upperBetaLimit;
  40027. }
  40028. }
  40029. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40030. this.alpha = this.lowerAlphaLimit;
  40031. }
  40032. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40033. this.alpha = this.upperAlphaLimit;
  40034. }
  40035. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40036. this.radius = this.lowerRadiusLimit;
  40037. }
  40038. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40039. this.radius = this.upperRadiusLimit;
  40040. }
  40041. };
  40042. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40043. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40044. this.radius = radiusv3.length();
  40045. if (this.radius === 0) {
  40046. this.radius = 0.0001; // Just to avoid division by zero
  40047. }
  40048. // Alpha
  40049. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40050. if (radiusv3.z < 0) {
  40051. this.alpha = 2 * Math.PI - this.alpha;
  40052. }
  40053. // Beta
  40054. this.beta = Math.acos(radiusv3.y / this.radius);
  40055. this._checkLimits();
  40056. };
  40057. ArcRotateCamera.prototype.setPosition = function (position) {
  40058. if (this.position.equals(position)) {
  40059. return;
  40060. }
  40061. this.position.copyFrom(position);
  40062. this.rebuildAnglesAndRadius();
  40063. };
  40064. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40065. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40066. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40067. if (target.getBoundingInfo) {
  40068. if (toBoundingCenter) {
  40069. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40070. }
  40071. else {
  40072. this._targetBoundingCenter = null;
  40073. }
  40074. this._targetHost = target;
  40075. this._target = this._getTargetPosition();
  40076. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40077. }
  40078. else {
  40079. var newTarget = target;
  40080. var currentTarget = this._getTargetPosition();
  40081. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40082. return;
  40083. }
  40084. this._targetHost = null;
  40085. this._target = newTarget;
  40086. this._targetBoundingCenter = null;
  40087. this.onMeshTargetChangedObservable.notifyObservers(null);
  40088. }
  40089. this.rebuildAnglesAndRadius();
  40090. };
  40091. ArcRotateCamera.prototype._getViewMatrix = function () {
  40092. // Compute
  40093. var cosa = Math.cos(this.alpha);
  40094. var sina = Math.sin(this.alpha);
  40095. var cosb = Math.cos(this.beta);
  40096. var sinb = Math.sin(this.beta);
  40097. if (sinb === 0) {
  40098. sinb = 0.0001;
  40099. }
  40100. var target = this._getTargetPosition();
  40101. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40102. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40103. if (!this._collider) {
  40104. this._collider = new BABYLON.Collider();
  40105. }
  40106. this._collider._radius = this.collisionRadius;
  40107. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40108. this._collisionTriggered = true;
  40109. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40110. }
  40111. else {
  40112. this.position.copyFrom(this._newPosition);
  40113. var up = this.upVector;
  40114. if (this.allowUpsideDown && sinb < 0) {
  40115. up = up.clone();
  40116. up = up.negate();
  40117. }
  40118. if (this.getScene().useRightHandedSystem) {
  40119. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40120. }
  40121. else {
  40122. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40123. }
  40124. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40125. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40126. }
  40127. this._currentTarget = target;
  40128. return this._viewMatrix;
  40129. };
  40130. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40131. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40132. meshes = meshes || this.getScene().meshes;
  40133. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40134. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40135. this.radius = distance * this.zoomOnFactor;
  40136. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40137. };
  40138. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40139. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40140. var meshesOrMinMaxVector;
  40141. var distance;
  40142. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40143. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40144. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40145. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40146. }
  40147. else {
  40148. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40149. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40150. distance = minMaxVectorAndDistance.distance;
  40151. }
  40152. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40153. if (!doNotUpdateMaxZ) {
  40154. this.maxZ = distance * 2;
  40155. }
  40156. };
  40157. /**
  40158. * @override
  40159. * Override Camera.createRigCamera
  40160. */
  40161. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40162. var alphaShift = 0;
  40163. switch (this.cameraRigMode) {
  40164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40167. case BABYLON.Camera.RIG_MODE_VR:
  40168. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40169. break;
  40170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40171. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40172. break;
  40173. }
  40174. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40175. rigCam._cameraRigParams = {};
  40176. return rigCam;
  40177. };
  40178. /**
  40179. * @override
  40180. * Override Camera._updateRigCameras
  40181. */
  40182. ArcRotateCamera.prototype._updateRigCameras = function () {
  40183. var camLeft = this._rigCameras[0];
  40184. var camRight = this._rigCameras[1];
  40185. camLeft.beta = camRight.beta = this.beta;
  40186. camLeft.radius = camRight.radius = this.radius;
  40187. switch (this.cameraRigMode) {
  40188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40190. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40191. case BABYLON.Camera.RIG_MODE_VR:
  40192. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40193. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40194. break;
  40195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40196. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40197. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40198. break;
  40199. }
  40200. _super.prototype._updateRigCameras.call(this);
  40201. };
  40202. ArcRotateCamera.prototype.dispose = function () {
  40203. this.inputs.clear();
  40204. _super.prototype.dispose.call(this);
  40205. };
  40206. ArcRotateCamera.prototype.getClassName = function () {
  40207. return "ArcRotateCamera";
  40208. };
  40209. __decorate([
  40210. BABYLON.serialize()
  40211. ], ArcRotateCamera.prototype, "alpha", void 0);
  40212. __decorate([
  40213. BABYLON.serialize()
  40214. ], ArcRotateCamera.prototype, "beta", void 0);
  40215. __decorate([
  40216. BABYLON.serialize()
  40217. ], ArcRotateCamera.prototype, "radius", void 0);
  40218. __decorate([
  40219. BABYLON.serializeAsVector3("target")
  40220. ], ArcRotateCamera.prototype, "_target", void 0);
  40221. __decorate([
  40222. BABYLON.serialize()
  40223. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40224. __decorate([
  40225. BABYLON.serialize()
  40226. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40227. __decorate([
  40228. BABYLON.serialize()
  40229. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40230. __decorate([
  40231. BABYLON.serialize()
  40232. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40233. __decorate([
  40234. BABYLON.serialize()
  40235. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40236. __decorate([
  40237. BABYLON.serialize()
  40238. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40239. __decorate([
  40240. BABYLON.serialize()
  40241. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40242. __decorate([
  40243. BABYLON.serialize()
  40244. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40245. __decorate([
  40246. BABYLON.serialize()
  40247. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40248. __decorate([
  40249. BABYLON.serialize()
  40250. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40251. __decorate([
  40252. BABYLON.serialize()
  40253. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40254. __decorate([
  40255. BABYLON.serialize()
  40256. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40257. __decorate([
  40258. BABYLON.serialize()
  40259. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40260. __decorate([
  40261. BABYLON.serializeAsVector3()
  40262. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40263. __decorate([
  40264. BABYLON.serialize()
  40265. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40266. __decorate([
  40267. BABYLON.serialize()
  40268. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40269. __decorate([
  40270. BABYLON.serialize()
  40271. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40272. return ArcRotateCamera;
  40273. }(BABYLON.TargetCamera));
  40274. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40275. })(BABYLON || (BABYLON = {}));
  40276. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40277. var BABYLON;
  40278. (function (BABYLON) {
  40279. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40280. __extends(ArcRotateCameraInputsManager, _super);
  40281. function ArcRotateCameraInputsManager(camera) {
  40282. return _super.call(this, camera) || this;
  40283. }
  40284. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40285. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40286. return this;
  40287. };
  40288. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40289. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40290. return this;
  40291. };
  40292. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40293. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40294. return this;
  40295. };
  40296. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40297. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40298. return this;
  40299. };
  40300. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40301. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40302. return this;
  40303. };
  40304. return ArcRotateCameraInputsManager;
  40305. }(BABYLON.CameraInputsManager));
  40306. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40307. })(BABYLON || (BABYLON = {}));
  40308. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40309. var BABYLON;
  40310. (function (BABYLON) {
  40311. var HemisphericLight = /** @class */ (function (_super) {
  40312. __extends(HemisphericLight, _super);
  40313. /**
  40314. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40315. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40316. * The HemisphericLight can't cast shadows.
  40317. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40318. */
  40319. function HemisphericLight(name, direction, scene) {
  40320. var _this = _super.call(this, name, scene) || this;
  40321. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40322. _this.direction = direction || BABYLON.Vector3.Up();
  40323. return _this;
  40324. }
  40325. HemisphericLight.prototype._buildUniformLayout = function () {
  40326. this._uniformBuffer.addUniform("vLightData", 4);
  40327. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40328. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40329. this._uniformBuffer.addUniform("vLightGround", 3);
  40330. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40331. this._uniformBuffer.addUniform("depthValues", 2);
  40332. this._uniformBuffer.create();
  40333. };
  40334. /**
  40335. * Returns the string "HemisphericLight".
  40336. */
  40337. HemisphericLight.prototype.getClassName = function () {
  40338. return "HemisphericLight";
  40339. };
  40340. /**
  40341. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40342. * Returns the updated direction.
  40343. */
  40344. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40345. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40346. return this.direction;
  40347. };
  40348. HemisphericLight.prototype.getShadowGenerator = function () {
  40349. return null;
  40350. };
  40351. /**
  40352. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40353. * Returns the HemisphericLight.
  40354. */
  40355. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40356. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40357. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40358. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40359. return this;
  40360. };
  40361. HemisphericLight.prototype._getWorldMatrix = function () {
  40362. if (!this._worldMatrix) {
  40363. this._worldMatrix = BABYLON.Matrix.Identity();
  40364. }
  40365. return this._worldMatrix;
  40366. };
  40367. /**
  40368. * Returns the integer 3.
  40369. */
  40370. HemisphericLight.prototype.getTypeID = function () {
  40371. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40372. };
  40373. __decorate([
  40374. BABYLON.serializeAsColor3()
  40375. ], HemisphericLight.prototype, "groundColor", void 0);
  40376. __decorate([
  40377. BABYLON.serializeAsVector3()
  40378. ], HemisphericLight.prototype, "direction", void 0);
  40379. return HemisphericLight;
  40380. }(BABYLON.Light));
  40381. BABYLON.HemisphericLight = HemisphericLight;
  40382. })(BABYLON || (BABYLON = {}));
  40383. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40384. var BABYLON;
  40385. (function (BABYLON) {
  40386. var ShadowLight = /** @class */ (function (_super) {
  40387. __extends(ShadowLight, _super);
  40388. function ShadowLight() {
  40389. var _this = _super !== null && _super.apply(this, arguments) || this;
  40390. _this._needProjectionMatrixCompute = true;
  40391. return _this;
  40392. }
  40393. Object.defineProperty(ShadowLight.prototype, "direction", {
  40394. get: function () {
  40395. return this._direction;
  40396. },
  40397. set: function (value) {
  40398. this._direction = value;
  40399. },
  40400. enumerable: true,
  40401. configurable: true
  40402. });
  40403. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40404. get: function () {
  40405. return this._shadowMinZ;
  40406. },
  40407. set: function (value) {
  40408. this._shadowMinZ = value;
  40409. this.forceProjectionMatrixCompute();
  40410. },
  40411. enumerable: true,
  40412. configurable: true
  40413. });
  40414. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40415. get: function () {
  40416. return this._shadowMaxZ;
  40417. },
  40418. set: function (value) {
  40419. this._shadowMaxZ = value;
  40420. this.forceProjectionMatrixCompute();
  40421. },
  40422. enumerable: true,
  40423. configurable: true
  40424. });
  40425. /**
  40426. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40427. */
  40428. ShadowLight.prototype.computeTransformedInformation = function () {
  40429. if (this.parent && this.parent.getWorldMatrix) {
  40430. if (!this.transformedPosition) {
  40431. this.transformedPosition = BABYLON.Vector3.Zero();
  40432. }
  40433. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40434. // In case the direction is present.
  40435. if (this.direction) {
  40436. if (!this.transformedDirection) {
  40437. this.transformedDirection = BABYLON.Vector3.Zero();
  40438. }
  40439. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40440. }
  40441. return true;
  40442. }
  40443. return false;
  40444. };
  40445. /**
  40446. * Return the depth scale used for the shadow map.
  40447. */
  40448. ShadowLight.prototype.getDepthScale = function () {
  40449. return 50.0;
  40450. };
  40451. /**
  40452. * Returns the light direction (Vector3) for any passed face index.
  40453. */
  40454. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40455. return this.transformedDirection ? this.transformedDirection : this.direction;
  40456. };
  40457. /**
  40458. * Returns the DirectionalLight absolute position in the World.
  40459. */
  40460. ShadowLight.prototype.getAbsolutePosition = function () {
  40461. return this.transformedPosition ? this.transformedPosition : this.position;
  40462. };
  40463. /**
  40464. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40465. * Returns the updated DirectionalLight direction (Vector3).
  40466. */
  40467. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40468. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40469. return this.direction;
  40470. };
  40471. /**
  40472. * Returns the light rotation (Vector3).
  40473. */
  40474. ShadowLight.prototype.getRotation = function () {
  40475. this.direction.normalize();
  40476. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40477. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40478. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40479. };
  40480. /**
  40481. * Boolean : false by default.
  40482. */
  40483. ShadowLight.prototype.needCube = function () {
  40484. return false;
  40485. };
  40486. /**
  40487. * Specifies wether or not the projection matrix should be recomputed this frame.
  40488. */
  40489. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40490. return this._needProjectionMatrixCompute;
  40491. };
  40492. /**
  40493. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40494. */
  40495. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40496. this._needProjectionMatrixCompute = true;
  40497. };
  40498. /**
  40499. * Get the world matrix of the sahdow lights.
  40500. */
  40501. ShadowLight.prototype._getWorldMatrix = function () {
  40502. if (!this._worldMatrix) {
  40503. this._worldMatrix = BABYLON.Matrix.Identity();
  40504. }
  40505. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40506. return this._worldMatrix;
  40507. };
  40508. /**
  40509. * Gets the minZ used for shadow according to both the scene and the light.
  40510. * @param activeCamera
  40511. */
  40512. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40513. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40514. };
  40515. /**
  40516. * Gets the maxZ used for shadow according to both the scene and the light.
  40517. * @param activeCamera
  40518. */
  40519. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40520. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40521. };
  40522. /**
  40523. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40524. * Returns the light.
  40525. */
  40526. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40527. if (this.customProjectionMatrixBuilder) {
  40528. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40529. }
  40530. else {
  40531. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40532. }
  40533. return this;
  40534. };
  40535. __decorate([
  40536. BABYLON.serializeAsVector3()
  40537. ], ShadowLight.prototype, "position", void 0);
  40538. __decorate([
  40539. BABYLON.serializeAsVector3()
  40540. ], ShadowLight.prototype, "direction", null);
  40541. __decorate([
  40542. BABYLON.serialize()
  40543. ], ShadowLight.prototype, "shadowMinZ", null);
  40544. __decorate([
  40545. BABYLON.serialize()
  40546. ], ShadowLight.prototype, "shadowMaxZ", null);
  40547. return ShadowLight;
  40548. }(BABYLON.Light));
  40549. BABYLON.ShadowLight = ShadowLight;
  40550. })(BABYLON || (BABYLON = {}));
  40551. //# sourceMappingURL=babylon.shadowLight.js.map
  40552. var BABYLON;
  40553. (function (BABYLON) {
  40554. var PointLight = /** @class */ (function (_super) {
  40555. __extends(PointLight, _super);
  40556. /**
  40557. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40558. * A PointLight emits the light in every direction.
  40559. * It can cast shadows.
  40560. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40561. * ```javascript
  40562. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40563. * ```
  40564. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40565. */
  40566. function PointLight(name, position, scene) {
  40567. var _this = _super.call(this, name, scene) || this;
  40568. _this._shadowAngle = Math.PI / 2;
  40569. _this.position = position;
  40570. return _this;
  40571. }
  40572. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40573. /**
  40574. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40575. * This specifies what angle the shadow will use to be created.
  40576. *
  40577. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40578. */
  40579. get: function () {
  40580. return this._shadowAngle;
  40581. },
  40582. /**
  40583. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40584. * This specifies what angle the shadow will use to be created.
  40585. *
  40586. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40587. */
  40588. set: function (value) {
  40589. this._shadowAngle = value;
  40590. this.forceProjectionMatrixCompute();
  40591. },
  40592. enumerable: true,
  40593. configurable: true
  40594. });
  40595. Object.defineProperty(PointLight.prototype, "direction", {
  40596. get: function () {
  40597. return this._direction;
  40598. },
  40599. /**
  40600. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40601. */
  40602. set: function (value) {
  40603. var previousNeedCube = this.needCube();
  40604. this._direction = value;
  40605. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40606. this._shadowGenerator.recreateShadowMap();
  40607. }
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. /**
  40613. * Returns the string "PointLight"
  40614. */
  40615. PointLight.prototype.getClassName = function () {
  40616. return "PointLight";
  40617. };
  40618. /**
  40619. * Returns the integer 0.
  40620. */
  40621. PointLight.prototype.getTypeID = function () {
  40622. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40623. };
  40624. /**
  40625. * Specifies wether or not the shadowmap should be a cube texture.
  40626. */
  40627. PointLight.prototype.needCube = function () {
  40628. return !this.direction;
  40629. };
  40630. /**
  40631. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40632. */
  40633. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40634. if (this.direction) {
  40635. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40636. }
  40637. else {
  40638. switch (faceIndex) {
  40639. case 0:
  40640. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40641. case 1:
  40642. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40643. case 2:
  40644. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40645. case 3:
  40646. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40647. case 4:
  40648. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40649. case 5:
  40650. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40651. }
  40652. }
  40653. return BABYLON.Vector3.Zero();
  40654. };
  40655. /**
  40656. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40657. * - fov = PI / 2
  40658. * - aspect ratio : 1.0
  40659. * - z-near and far equal to the active camera minZ and maxZ.
  40660. * Returns the PointLight.
  40661. */
  40662. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40663. var activeCamera = this.getScene().activeCamera;
  40664. if (!activeCamera) {
  40665. return;
  40666. }
  40667. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40668. };
  40669. PointLight.prototype._buildUniformLayout = function () {
  40670. this._uniformBuffer.addUniform("vLightData", 4);
  40671. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40672. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40673. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40674. this._uniformBuffer.addUniform("depthValues", 2);
  40675. this._uniformBuffer.create();
  40676. };
  40677. /**
  40678. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40679. * Returns the PointLight.
  40680. */
  40681. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40682. if (this.computeTransformedInformation()) {
  40683. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40684. return this;
  40685. }
  40686. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40687. return this;
  40688. };
  40689. __decorate([
  40690. BABYLON.serialize()
  40691. ], PointLight.prototype, "shadowAngle", null);
  40692. return PointLight;
  40693. }(BABYLON.ShadowLight));
  40694. BABYLON.PointLight = PointLight;
  40695. })(BABYLON || (BABYLON = {}));
  40696. //# sourceMappingURL=babylon.pointLight.js.map
  40697. var BABYLON;
  40698. (function (BABYLON) {
  40699. var DirectionalLight = /** @class */ (function (_super) {
  40700. __extends(DirectionalLight, _super);
  40701. /**
  40702. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40703. * The directional light is emitted from everywhere in the given direction.
  40704. * It can cast shawdows.
  40705. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40706. */
  40707. function DirectionalLight(name, direction, scene) {
  40708. var _this = _super.call(this, name, scene) || this;
  40709. _this._shadowFrustumSize = 0;
  40710. _this._shadowOrthoScale = 0.5;
  40711. _this.autoUpdateExtends = true;
  40712. // Cache
  40713. _this._orthoLeft = Number.MAX_VALUE;
  40714. _this._orthoRight = Number.MIN_VALUE;
  40715. _this._orthoTop = Number.MIN_VALUE;
  40716. _this._orthoBottom = Number.MAX_VALUE;
  40717. _this.position = direction.scale(-1.0);
  40718. _this.direction = direction;
  40719. return _this;
  40720. }
  40721. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40722. /**
  40723. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40724. */
  40725. get: function () {
  40726. return this._shadowFrustumSize;
  40727. },
  40728. /**
  40729. * Specifies a fix frustum size for the shadow generation.
  40730. */
  40731. set: function (value) {
  40732. this._shadowFrustumSize = value;
  40733. this.forceProjectionMatrixCompute();
  40734. },
  40735. enumerable: true,
  40736. configurable: true
  40737. });
  40738. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40739. get: function () {
  40740. return this._shadowOrthoScale;
  40741. },
  40742. set: function (value) {
  40743. this._shadowOrthoScale = value;
  40744. this.forceProjectionMatrixCompute();
  40745. },
  40746. enumerable: true,
  40747. configurable: true
  40748. });
  40749. /**
  40750. * Returns the string "DirectionalLight".
  40751. */
  40752. DirectionalLight.prototype.getClassName = function () {
  40753. return "DirectionalLight";
  40754. };
  40755. /**
  40756. * Returns the integer 1.
  40757. */
  40758. DirectionalLight.prototype.getTypeID = function () {
  40759. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40760. };
  40761. /**
  40762. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40763. * Returns the DirectionalLight Shadow projection matrix.
  40764. */
  40765. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40766. if (this.shadowFrustumSize > 0) {
  40767. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40768. }
  40769. else {
  40770. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40771. }
  40772. };
  40773. /**
  40774. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40775. * Returns the DirectionalLight Shadow projection matrix.
  40776. */
  40777. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40778. var activeCamera = this.getScene().activeCamera;
  40779. if (!activeCamera) {
  40780. return;
  40781. }
  40782. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40783. };
  40784. /**
  40785. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40786. * Returns the DirectionalLight Shadow projection matrix.
  40787. */
  40788. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40789. var activeCamera = this.getScene().activeCamera;
  40790. if (!activeCamera) {
  40791. return;
  40792. }
  40793. // Check extends
  40794. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40795. var tempVector3 = BABYLON.Vector3.Zero();
  40796. this._orthoLeft = Number.MAX_VALUE;
  40797. this._orthoRight = Number.MIN_VALUE;
  40798. this._orthoTop = Number.MIN_VALUE;
  40799. this._orthoBottom = Number.MAX_VALUE;
  40800. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40801. var mesh = renderList[meshIndex];
  40802. if (!mesh) {
  40803. continue;
  40804. }
  40805. var boundingInfo = mesh.getBoundingInfo();
  40806. var boundingBox = boundingInfo.boundingBox;
  40807. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40808. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40809. if (tempVector3.x < this._orthoLeft)
  40810. this._orthoLeft = tempVector3.x;
  40811. if (tempVector3.y < this._orthoBottom)
  40812. this._orthoBottom = tempVector3.y;
  40813. if (tempVector3.x > this._orthoRight)
  40814. this._orthoRight = tempVector3.x;
  40815. if (tempVector3.y > this._orthoTop)
  40816. this._orthoTop = tempVector3.y;
  40817. }
  40818. }
  40819. }
  40820. var xOffset = this._orthoRight - this._orthoLeft;
  40821. var yOffset = this._orthoTop - this._orthoBottom;
  40822. 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);
  40823. };
  40824. DirectionalLight.prototype._buildUniformLayout = function () {
  40825. this._uniformBuffer.addUniform("vLightData", 4);
  40826. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40827. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40828. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40829. this._uniformBuffer.addUniform("depthValues", 2);
  40830. this._uniformBuffer.create();
  40831. };
  40832. /**
  40833. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40834. * Returns the DirectionalLight.
  40835. */
  40836. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40837. if (this.computeTransformedInformation()) {
  40838. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40839. return this;
  40840. }
  40841. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40842. return this;
  40843. };
  40844. /**
  40845. * Gets the minZ used for shadow according to both the scene and the light.
  40846. *
  40847. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40848. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40849. * @param activeCamera
  40850. */
  40851. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40852. return 1;
  40853. };
  40854. /**
  40855. * Gets the maxZ used for shadow according to both the scene and the light.
  40856. *
  40857. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40858. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40859. * @param activeCamera
  40860. */
  40861. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40862. return 1;
  40863. };
  40864. __decorate([
  40865. BABYLON.serialize()
  40866. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40867. __decorate([
  40868. BABYLON.serialize()
  40869. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40870. __decorate([
  40871. BABYLON.serialize()
  40872. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40873. return DirectionalLight;
  40874. }(BABYLON.ShadowLight));
  40875. BABYLON.DirectionalLight = DirectionalLight;
  40876. })(BABYLON || (BABYLON = {}));
  40877. //# sourceMappingURL=babylon.directionalLight.js.map
  40878. var BABYLON;
  40879. (function (BABYLON) {
  40880. var SpotLight = /** @class */ (function (_super) {
  40881. __extends(SpotLight, _super);
  40882. /**
  40883. * Creates a SpotLight object in the scene with the passed parameters :
  40884. * - `position` (Vector3) is the initial SpotLight position,
  40885. * - `direction` (Vector3) is the initial SpotLight direction,
  40886. * - `angle` (float, in radians) is the spot light cone angle,
  40887. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40888. * A spot light is a simply light oriented cone.
  40889. * It can cast shadows.
  40890. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40891. */
  40892. function SpotLight(name, position, direction, angle, exponent, scene) {
  40893. var _this = _super.call(this, name, scene) || this;
  40894. _this.position = position;
  40895. _this.direction = direction;
  40896. _this.angle = angle;
  40897. _this.exponent = exponent;
  40898. return _this;
  40899. }
  40900. Object.defineProperty(SpotLight.prototype, "angle", {
  40901. get: function () {
  40902. return this._angle;
  40903. },
  40904. set: function (value) {
  40905. this._angle = value;
  40906. this.forceProjectionMatrixCompute();
  40907. },
  40908. enumerable: true,
  40909. configurable: true
  40910. });
  40911. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40912. get: function () {
  40913. return this._shadowAngleScale;
  40914. },
  40915. /**
  40916. * Allows scaling the angle of the light for shadow generation only.
  40917. */
  40918. set: function (value) {
  40919. this._shadowAngleScale = value;
  40920. this.forceProjectionMatrixCompute();
  40921. },
  40922. enumerable: true,
  40923. configurable: true
  40924. });
  40925. /**
  40926. * Returns the string "SpotLight".
  40927. */
  40928. SpotLight.prototype.getClassName = function () {
  40929. return "SpotLight";
  40930. };
  40931. /**
  40932. * Returns the integer 2.
  40933. */
  40934. SpotLight.prototype.getTypeID = function () {
  40935. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40936. };
  40937. /**
  40938. * 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.
  40939. * Returns the SpotLight.
  40940. */
  40941. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40942. var activeCamera = this.getScene().activeCamera;
  40943. if (!activeCamera) {
  40944. return;
  40945. }
  40946. this._shadowAngleScale = this._shadowAngleScale || 1;
  40947. var angle = this._shadowAngleScale * this._angle;
  40948. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40949. };
  40950. SpotLight.prototype._buildUniformLayout = function () {
  40951. this._uniformBuffer.addUniform("vLightData", 4);
  40952. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40953. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40954. this._uniformBuffer.addUniform("vLightDirection", 3);
  40955. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40956. this._uniformBuffer.addUniform("depthValues", 2);
  40957. this._uniformBuffer.create();
  40958. };
  40959. /**
  40960. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40961. * Return the SpotLight.
  40962. */
  40963. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40964. var normalizeDirection;
  40965. if (this.computeTransformedInformation()) {
  40966. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40967. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40968. }
  40969. else {
  40970. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40971. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40972. }
  40973. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40974. return this;
  40975. };
  40976. __decorate([
  40977. BABYLON.serialize()
  40978. ], SpotLight.prototype, "angle", null);
  40979. __decorate([
  40980. BABYLON.serialize()
  40981. /**
  40982. * Allows scaling the angle of the light for shadow generation only.
  40983. */
  40984. ], SpotLight.prototype, "shadowAngleScale", null);
  40985. __decorate([
  40986. BABYLON.serialize()
  40987. ], SpotLight.prototype, "exponent", void 0);
  40988. return SpotLight;
  40989. }(BABYLON.ShadowLight));
  40990. BABYLON.SpotLight = SpotLight;
  40991. })(BABYLON || (BABYLON = {}));
  40992. //# sourceMappingURL=babylon.spotLight.js.map
  40993. var BABYLON;
  40994. (function (BABYLON) {
  40995. var AnimationRange = /** @class */ (function () {
  40996. function AnimationRange(name, from, to) {
  40997. this.name = name;
  40998. this.from = from;
  40999. this.to = to;
  41000. }
  41001. AnimationRange.prototype.clone = function () {
  41002. return new AnimationRange(this.name, this.from, this.to);
  41003. };
  41004. return AnimationRange;
  41005. }());
  41006. BABYLON.AnimationRange = AnimationRange;
  41007. /**
  41008. * Composed of a frame, and an action function
  41009. */
  41010. var AnimationEvent = /** @class */ (function () {
  41011. function AnimationEvent(frame, action, onlyOnce) {
  41012. this.frame = frame;
  41013. this.action = action;
  41014. this.onlyOnce = onlyOnce;
  41015. this.isDone = false;
  41016. }
  41017. return AnimationEvent;
  41018. }());
  41019. BABYLON.AnimationEvent = AnimationEvent;
  41020. var PathCursor = /** @class */ (function () {
  41021. function PathCursor(path) {
  41022. this.path = path;
  41023. this._onchange = new Array();
  41024. this.value = 0;
  41025. this.animations = new Array();
  41026. }
  41027. PathCursor.prototype.getPoint = function () {
  41028. var point = this.path.getPointAtLengthPosition(this.value);
  41029. return new BABYLON.Vector3(point.x, 0, point.y);
  41030. };
  41031. PathCursor.prototype.moveAhead = function (step) {
  41032. if (step === void 0) { step = 0.002; }
  41033. this.move(step);
  41034. return this;
  41035. };
  41036. PathCursor.prototype.moveBack = function (step) {
  41037. if (step === void 0) { step = 0.002; }
  41038. this.move(-step);
  41039. return this;
  41040. };
  41041. PathCursor.prototype.move = function (step) {
  41042. if (Math.abs(step) > 1) {
  41043. throw "step size should be less than 1.";
  41044. }
  41045. this.value += step;
  41046. this.ensureLimits();
  41047. this.raiseOnChange();
  41048. return this;
  41049. };
  41050. PathCursor.prototype.ensureLimits = function () {
  41051. while (this.value > 1) {
  41052. this.value -= 1;
  41053. }
  41054. while (this.value < 0) {
  41055. this.value += 1;
  41056. }
  41057. return this;
  41058. };
  41059. // used by animation engine
  41060. PathCursor.prototype.raiseOnChange = function () {
  41061. var _this = this;
  41062. this._onchange.forEach(function (f) { return f(_this); });
  41063. return this;
  41064. };
  41065. PathCursor.prototype.onchange = function (f) {
  41066. this._onchange.push(f);
  41067. return this;
  41068. };
  41069. return PathCursor;
  41070. }());
  41071. BABYLON.PathCursor = PathCursor;
  41072. var Animation = /** @class */ (function () {
  41073. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41074. this.name = name;
  41075. this.targetProperty = targetProperty;
  41076. this.framePerSecond = framePerSecond;
  41077. this.dataType = dataType;
  41078. this.loopMode = loopMode;
  41079. this.enableBlending = enableBlending;
  41080. this._runtimeAnimations = new Array();
  41081. // The set of event that will be linked to this animation
  41082. this._events = new Array();
  41083. this.blendingSpeed = 0.01;
  41084. this._ranges = {};
  41085. this.targetPropertyPath = targetProperty.split(".");
  41086. this.dataType = dataType;
  41087. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41088. }
  41089. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41090. var dataType = undefined;
  41091. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41092. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41093. }
  41094. else if (from instanceof BABYLON.Quaternion) {
  41095. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41096. }
  41097. else if (from instanceof BABYLON.Vector3) {
  41098. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41099. }
  41100. else if (from instanceof BABYLON.Vector2) {
  41101. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41102. }
  41103. else if (from instanceof BABYLON.Color3) {
  41104. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41105. }
  41106. else if (from instanceof BABYLON.Size) {
  41107. dataType = Animation.ANIMATIONTYPE_SIZE;
  41108. }
  41109. if (dataType == undefined) {
  41110. return null;
  41111. }
  41112. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41113. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41114. animation.setKeys(keys);
  41115. if (easingFunction !== undefined) {
  41116. animation.setEasingFunction(easingFunction);
  41117. }
  41118. return animation;
  41119. };
  41120. /**
  41121. * Sets up an animation.
  41122. * @param property the property to animate
  41123. * @param animationType the animation type to apply
  41124. * @param easingFunction the easing function used in the animation
  41125. * @returns The created animation
  41126. */
  41127. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41128. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41129. animation.setEasingFunction(easingFunction);
  41130. return animation;
  41131. };
  41132. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41133. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41134. if (!animation) {
  41135. return null;
  41136. }
  41137. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41138. };
  41139. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41140. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41141. if (!animation) {
  41142. return null;
  41143. }
  41144. node.animations.push(animation);
  41145. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41146. };
  41147. /**
  41148. * Transition property of the Camera to the target Value.
  41149. * @param property The property to transition
  41150. * @param targetValue The target Value of the property
  41151. * @param host The object where the property to animate belongs
  41152. * @param scene Scene used to run the animation
  41153. * @param frameRate Framerate (in frame/s) to use
  41154. * @param transition The transition type we want to use
  41155. * @param duration The duration of the animation, in milliseconds
  41156. * @param onAnimationEnd Call back trigger at the end of the animation.
  41157. */
  41158. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41159. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41160. if (duration <= 0) {
  41161. host[property] = targetValue;
  41162. if (onAnimationEnd) {
  41163. onAnimationEnd();
  41164. }
  41165. return null;
  41166. }
  41167. var endFrame = frameRate * (duration / 1000);
  41168. transition.setKeys([{
  41169. frame: 0,
  41170. value: host[property].clone ? host[property].clone() : host[property]
  41171. },
  41172. {
  41173. frame: endFrame,
  41174. value: targetValue
  41175. }]);
  41176. if (!host.animations) {
  41177. host.animations = [];
  41178. }
  41179. host.animations.push(transition);
  41180. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41181. animation.onAnimationEnd = onAnimationEnd;
  41182. return animation;
  41183. };
  41184. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41185. /**
  41186. * Return the array of runtime animations currently using this animation
  41187. */
  41188. get: function () {
  41189. return this._runtimeAnimations;
  41190. },
  41191. enumerable: true,
  41192. configurable: true
  41193. });
  41194. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41195. get: function () {
  41196. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41197. var runtimeAnimation = _a[_i];
  41198. if (!runtimeAnimation.isStopped) {
  41199. return true;
  41200. }
  41201. }
  41202. return false;
  41203. },
  41204. enumerable: true,
  41205. configurable: true
  41206. });
  41207. // Methods
  41208. /**
  41209. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41210. */
  41211. Animation.prototype.toString = function (fullDetails) {
  41212. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41213. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41214. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41215. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41216. if (fullDetails) {
  41217. ret += ", Ranges: {";
  41218. var first = true;
  41219. for (var name in this._ranges) {
  41220. if (first) {
  41221. ret += ", ";
  41222. first = false;
  41223. }
  41224. ret += name;
  41225. }
  41226. ret += "}";
  41227. }
  41228. return ret;
  41229. };
  41230. /**
  41231. * Add an event to this animation.
  41232. */
  41233. Animation.prototype.addEvent = function (event) {
  41234. this._events.push(event);
  41235. };
  41236. /**
  41237. * Remove all events found at the given frame
  41238. * @param frame
  41239. */
  41240. Animation.prototype.removeEvents = function (frame) {
  41241. for (var index = 0; index < this._events.length; index++) {
  41242. if (this._events[index].frame === frame) {
  41243. this._events.splice(index, 1);
  41244. index--;
  41245. }
  41246. }
  41247. };
  41248. Animation.prototype.getEvents = function () {
  41249. return this._events;
  41250. };
  41251. Animation.prototype.createRange = function (name, from, to) {
  41252. // check name not already in use; could happen for bones after serialized
  41253. if (!this._ranges[name]) {
  41254. this._ranges[name] = new AnimationRange(name, from, to);
  41255. }
  41256. };
  41257. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41258. if (deleteFrames === void 0) { deleteFrames = true; }
  41259. var range = this._ranges[name];
  41260. if (!range) {
  41261. return;
  41262. }
  41263. if (deleteFrames) {
  41264. var from = range.from;
  41265. var to = range.to;
  41266. // this loop MUST go high to low for multiple splices to work
  41267. for (var key = this._keys.length - 1; key >= 0; key--) {
  41268. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41269. this._keys.splice(key, 1);
  41270. }
  41271. }
  41272. }
  41273. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41274. };
  41275. Animation.prototype.getRange = function (name) {
  41276. return this._ranges[name];
  41277. };
  41278. Animation.prototype.getKeys = function () {
  41279. return this._keys;
  41280. };
  41281. Animation.prototype.getHighestFrame = function () {
  41282. var ret = 0;
  41283. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41284. if (ret < this._keys[key].frame) {
  41285. ret = this._keys[key].frame;
  41286. }
  41287. }
  41288. return ret;
  41289. };
  41290. Animation.prototype.getEasingFunction = function () {
  41291. return this._easingFunction;
  41292. };
  41293. Animation.prototype.setEasingFunction = function (easingFunction) {
  41294. this._easingFunction = easingFunction;
  41295. };
  41296. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41297. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41298. };
  41299. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41300. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41301. };
  41302. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41303. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41304. };
  41305. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41306. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41307. };
  41308. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41309. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41310. };
  41311. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41312. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41313. };
  41314. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41315. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41316. };
  41317. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41318. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41319. };
  41320. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41321. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41322. };
  41323. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41324. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41325. };
  41326. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41327. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41328. };
  41329. Animation.prototype.clone = function () {
  41330. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41331. clone.enableBlending = this.enableBlending;
  41332. clone.blendingSpeed = this.blendingSpeed;
  41333. if (this._keys) {
  41334. clone.setKeys(this._keys);
  41335. }
  41336. if (this._ranges) {
  41337. clone._ranges = {};
  41338. for (var name in this._ranges) {
  41339. var range = this._ranges[name];
  41340. if (!range) {
  41341. continue;
  41342. }
  41343. clone._ranges[name] = range.clone();
  41344. }
  41345. }
  41346. return clone;
  41347. };
  41348. Animation.prototype.setKeys = function (values) {
  41349. this._keys = values.slice(0);
  41350. };
  41351. Animation.prototype.serialize = function () {
  41352. var serializationObject = {};
  41353. serializationObject.name = this.name;
  41354. serializationObject.property = this.targetProperty;
  41355. serializationObject.framePerSecond = this.framePerSecond;
  41356. serializationObject.dataType = this.dataType;
  41357. serializationObject.loopBehavior = this.loopMode;
  41358. serializationObject.enableBlending = this.enableBlending;
  41359. serializationObject.blendingSpeed = this.blendingSpeed;
  41360. var dataType = this.dataType;
  41361. serializationObject.keys = [];
  41362. var keys = this.getKeys();
  41363. for (var index = 0; index < keys.length; index++) {
  41364. var animationKey = keys[index];
  41365. var key = {};
  41366. key.frame = animationKey.frame;
  41367. switch (dataType) {
  41368. case Animation.ANIMATIONTYPE_FLOAT:
  41369. key.values = [animationKey.value];
  41370. break;
  41371. case Animation.ANIMATIONTYPE_QUATERNION:
  41372. case Animation.ANIMATIONTYPE_MATRIX:
  41373. case Animation.ANIMATIONTYPE_VECTOR3:
  41374. case Animation.ANIMATIONTYPE_COLOR3:
  41375. key.values = animationKey.value.asArray();
  41376. break;
  41377. }
  41378. serializationObject.keys.push(key);
  41379. }
  41380. serializationObject.ranges = [];
  41381. for (var name in this._ranges) {
  41382. var source = this._ranges[name];
  41383. if (!source) {
  41384. continue;
  41385. }
  41386. var range = {};
  41387. range.name = name;
  41388. range.from = source.from;
  41389. range.to = source.to;
  41390. serializationObject.ranges.push(range);
  41391. }
  41392. return serializationObject;
  41393. };
  41394. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41395. get: function () {
  41396. return Animation._ANIMATIONTYPE_FLOAT;
  41397. },
  41398. enumerable: true,
  41399. configurable: true
  41400. });
  41401. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41402. get: function () {
  41403. return Animation._ANIMATIONTYPE_VECTOR3;
  41404. },
  41405. enumerable: true,
  41406. configurable: true
  41407. });
  41408. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41409. get: function () {
  41410. return Animation._ANIMATIONTYPE_VECTOR2;
  41411. },
  41412. enumerable: true,
  41413. configurable: true
  41414. });
  41415. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41416. get: function () {
  41417. return Animation._ANIMATIONTYPE_SIZE;
  41418. },
  41419. enumerable: true,
  41420. configurable: true
  41421. });
  41422. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41423. get: function () {
  41424. return Animation._ANIMATIONTYPE_QUATERNION;
  41425. },
  41426. enumerable: true,
  41427. configurable: true
  41428. });
  41429. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41430. get: function () {
  41431. return Animation._ANIMATIONTYPE_MATRIX;
  41432. },
  41433. enumerable: true,
  41434. configurable: true
  41435. });
  41436. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41437. get: function () {
  41438. return Animation._ANIMATIONTYPE_COLOR3;
  41439. },
  41440. enumerable: true,
  41441. configurable: true
  41442. });
  41443. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41444. get: function () {
  41445. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41451. get: function () {
  41452. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41458. get: function () {
  41459. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Animation.Parse = function (parsedAnimation) {
  41465. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41466. var dataType = parsedAnimation.dataType;
  41467. var keys = [];
  41468. var data;
  41469. var index;
  41470. if (parsedAnimation.enableBlending) {
  41471. animation.enableBlending = parsedAnimation.enableBlending;
  41472. }
  41473. if (parsedAnimation.blendingSpeed) {
  41474. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41475. }
  41476. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41477. var key = parsedAnimation.keys[index];
  41478. var inTangent;
  41479. var outTangent;
  41480. switch (dataType) {
  41481. case Animation.ANIMATIONTYPE_FLOAT:
  41482. data = key.values[0];
  41483. if (key.values.length >= 1) {
  41484. inTangent = key.values[1];
  41485. }
  41486. if (key.values.length >= 2) {
  41487. outTangent = key.values[2];
  41488. }
  41489. break;
  41490. case Animation.ANIMATIONTYPE_QUATERNION:
  41491. data = BABYLON.Quaternion.FromArray(key.values);
  41492. if (key.values.length >= 8) {
  41493. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41494. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41495. inTangent = _inTangent;
  41496. }
  41497. }
  41498. if (key.values.length >= 12) {
  41499. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41500. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41501. outTangent = _outTangent;
  41502. }
  41503. }
  41504. break;
  41505. case Animation.ANIMATIONTYPE_MATRIX:
  41506. data = BABYLON.Matrix.FromArray(key.values);
  41507. break;
  41508. case Animation.ANIMATIONTYPE_COLOR3:
  41509. data = BABYLON.Color3.FromArray(key.values);
  41510. break;
  41511. case Animation.ANIMATIONTYPE_VECTOR3:
  41512. default:
  41513. data = BABYLON.Vector3.FromArray(key.values);
  41514. break;
  41515. }
  41516. var keyData = {};
  41517. keyData.frame = key.frame;
  41518. keyData.value = data;
  41519. if (inTangent != undefined) {
  41520. keyData.inTangent = inTangent;
  41521. }
  41522. if (outTangent != undefined) {
  41523. keyData.outTangent = outTangent;
  41524. }
  41525. keys.push(keyData);
  41526. }
  41527. animation.setKeys(keys);
  41528. if (parsedAnimation.ranges) {
  41529. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41530. data = parsedAnimation.ranges[index];
  41531. animation.createRange(data.name, data.from, data.to);
  41532. }
  41533. }
  41534. return animation;
  41535. };
  41536. Animation.AppendSerializedAnimations = function (source, destination) {
  41537. if (source.animations) {
  41538. destination.animations = [];
  41539. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41540. var animation = source.animations[animationIndex];
  41541. destination.animations.push(animation.serialize());
  41542. }
  41543. }
  41544. };
  41545. Animation.AllowMatricesInterpolation = false;
  41546. // Statics
  41547. Animation._ANIMATIONTYPE_FLOAT = 0;
  41548. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41549. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41550. Animation._ANIMATIONTYPE_MATRIX = 3;
  41551. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41552. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41553. Animation._ANIMATIONTYPE_SIZE = 6;
  41554. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41555. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41556. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41557. return Animation;
  41558. }());
  41559. BABYLON.Animation = Animation;
  41560. })(BABYLON || (BABYLON = {}));
  41561. //# sourceMappingURL=babylon.animation.js.map
  41562. var BABYLON;
  41563. (function (BABYLON) {
  41564. var AnimationGroup = /** @class */ (function () {
  41565. function AnimationGroup() {
  41566. }
  41567. return AnimationGroup;
  41568. }());
  41569. BABYLON.AnimationGroup = AnimationGroup;
  41570. })(BABYLON || (BABYLON = {}));
  41571. //# sourceMappingURL=babylon.animationGroup.js.map
  41572. var BABYLON;
  41573. (function (BABYLON) {
  41574. var RuntimeAnimation = /** @class */ (function () {
  41575. function RuntimeAnimation(target, animation) {
  41576. this._offsetsCache = {};
  41577. this._highLimitsCache = {};
  41578. this._stopped = false;
  41579. this._blendingFactor = 0;
  41580. this._ratioOffset = 0;
  41581. this._animation = animation;
  41582. this._target = target;
  41583. animation._runtimeAnimations.push(this);
  41584. }
  41585. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41586. get: function () {
  41587. return this._animation;
  41588. },
  41589. enumerable: true,
  41590. configurable: true
  41591. });
  41592. RuntimeAnimation.prototype.reset = function () {
  41593. this._offsetsCache = {};
  41594. this._highLimitsCache = {};
  41595. this.currentFrame = 0;
  41596. this._blendingFactor = 0;
  41597. this._originalBlendValue = null;
  41598. };
  41599. RuntimeAnimation.prototype.isStopped = function () {
  41600. return this._stopped;
  41601. };
  41602. RuntimeAnimation.prototype.dispose = function () {
  41603. var index = this._animation.runtimeAnimations.indexOf(this);
  41604. if (index > -1) {
  41605. this._animation.runtimeAnimations.splice(index, 1);
  41606. }
  41607. };
  41608. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41609. if (typeof value === "function") {
  41610. return value();
  41611. }
  41612. return value;
  41613. };
  41614. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41615. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41616. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41617. }
  41618. this.currentFrame = currentFrame;
  41619. var keys = this._animation.getKeys();
  41620. // Try to get a hash to find the right key
  41621. 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));
  41622. if (keys[startKeyIndex].frame >= currentFrame) {
  41623. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41624. startKeyIndex--;
  41625. }
  41626. }
  41627. for (var key = startKeyIndex; key < keys.length; key++) {
  41628. var endKey = keys[key + 1];
  41629. if (endKey.frame >= currentFrame) {
  41630. var startKey = keys[key];
  41631. var startValue = this._getKeyValue(startKey.value);
  41632. var endValue = this._getKeyValue(endKey.value);
  41633. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41634. var frameDelta = endKey.frame - startKey.frame;
  41635. // gradient : percent of currentFrame between the frame inf and the frame sup
  41636. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41637. // check for easingFunction and correction of gradient
  41638. var easingFunction = this._animation.getEasingFunction();
  41639. if (easingFunction != null) {
  41640. gradient = easingFunction.ease(gradient);
  41641. }
  41642. switch (this._animation.dataType) {
  41643. // Float
  41644. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41645. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41646. switch (loopMode) {
  41647. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41648. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41649. return floatValue;
  41650. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41651. return offsetValue * repeatCount + floatValue;
  41652. }
  41653. break;
  41654. // Quaternion
  41655. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41656. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41657. switch (loopMode) {
  41658. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41659. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41660. return quatValue;
  41661. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41662. return quatValue.add(offsetValue.scale(repeatCount));
  41663. }
  41664. return quatValue;
  41665. // Vector3
  41666. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41667. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41668. switch (loopMode) {
  41669. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41670. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41671. return vec3Value;
  41672. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41673. return vec3Value.add(offsetValue.scale(repeatCount));
  41674. }
  41675. // Vector2
  41676. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41677. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41678. switch (loopMode) {
  41679. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41680. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41681. return vec2Value;
  41682. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41683. return vec2Value.add(offsetValue.scale(repeatCount));
  41684. }
  41685. // Size
  41686. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41687. switch (loopMode) {
  41688. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41689. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41690. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41691. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41692. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41693. }
  41694. // Color3
  41695. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41696. switch (loopMode) {
  41697. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41698. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41699. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41700. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41701. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41702. }
  41703. // Matrix
  41704. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41705. switch (loopMode) {
  41706. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41707. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41708. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41709. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41710. }
  41711. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41712. return startValue;
  41713. }
  41714. default:
  41715. break;
  41716. }
  41717. break;
  41718. }
  41719. }
  41720. return this._getKeyValue(keys[keys.length - 1].value);
  41721. };
  41722. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41723. if (blend === void 0) { blend = false; }
  41724. // Set value
  41725. var path;
  41726. var destination;
  41727. var targetPropertyPath = this._animation.targetPropertyPath;
  41728. if (targetPropertyPath.length > 1) {
  41729. var property = this._target[targetPropertyPath[0]];
  41730. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41731. property = property[targetPropertyPath[index]];
  41732. }
  41733. path = targetPropertyPath[targetPropertyPath.length - 1];
  41734. destination = property;
  41735. }
  41736. else {
  41737. path = targetPropertyPath[0];
  41738. destination = this._target;
  41739. }
  41740. // Blending
  41741. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41742. if (!this._originalBlendValue) {
  41743. if (destination[path].clone) {
  41744. this._originalBlendValue = destination[path].clone();
  41745. }
  41746. else {
  41747. this._originalBlendValue = destination[path];
  41748. }
  41749. }
  41750. if (this._originalBlendValue.prototype) {
  41751. if (this._originalBlendValue.prototype.Lerp) {
  41752. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41753. }
  41754. else {
  41755. destination[path] = currentValue;
  41756. }
  41757. }
  41758. else if (this._originalBlendValue.m) {
  41759. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41760. }
  41761. else {
  41762. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41763. }
  41764. this._blendingFactor += this._animation.blendingSpeed;
  41765. }
  41766. else {
  41767. destination[path] = currentValue;
  41768. }
  41769. if (this._target.markAsDirty) {
  41770. this._target.markAsDirty(this._animation.targetProperty);
  41771. }
  41772. };
  41773. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41774. var keys = this._animation.getKeys();
  41775. if (frame < keys[0].frame) {
  41776. frame = keys[0].frame;
  41777. }
  41778. else if (frame > keys[keys.length - 1].frame) {
  41779. frame = keys[keys.length - 1].frame;
  41780. }
  41781. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41782. this.setValue(currentValue);
  41783. };
  41784. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41785. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41786. this._ratioOffset = this._previousRatio - newRatio;
  41787. };
  41788. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41789. if (blend === void 0) { blend = false; }
  41790. var targetPropertyPath = this._animation.targetPropertyPath;
  41791. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41792. this._stopped = true;
  41793. return false;
  41794. }
  41795. var returnValue = true;
  41796. var keys = this._animation.getKeys();
  41797. // Adding a start key at frame 0 if missing
  41798. if (keys[0].frame !== 0) {
  41799. var newKey = { frame: 0, value: keys[0].value };
  41800. keys.splice(0, 0, newKey);
  41801. }
  41802. // Check limits
  41803. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41804. from = keys[0].frame;
  41805. }
  41806. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41807. to = keys[keys.length - 1].frame;
  41808. }
  41809. //to and from cannot be the same key
  41810. if (from === to) {
  41811. if (from > keys[0].frame) {
  41812. from--;
  41813. }
  41814. else if (to < keys[keys.length - 1].frame) {
  41815. to++;
  41816. }
  41817. }
  41818. // Compute ratio
  41819. var range = to - from;
  41820. var offsetValue;
  41821. // ratio represents the frame delta between from and to
  41822. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41823. var highLimitValue = 0;
  41824. this._previousDelay = delay;
  41825. this._previousRatio = ratio;
  41826. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41827. returnValue = false;
  41828. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41829. }
  41830. else {
  41831. // Get max value if required
  41832. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41833. var keyOffset = to.toString() + from.toString();
  41834. if (!this._offsetsCache[keyOffset]) {
  41835. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41836. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41837. switch (this._animation.dataType) {
  41838. // Float
  41839. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41840. this._offsetsCache[keyOffset] = toValue - fromValue;
  41841. break;
  41842. // Quaternion
  41843. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41845. break;
  41846. // Vector3
  41847. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41849. // Vector2
  41850. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41851. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41852. // Size
  41853. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41854. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41855. // Color3
  41856. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41857. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41858. default:
  41859. break;
  41860. }
  41861. this._highLimitsCache[keyOffset] = toValue;
  41862. }
  41863. highLimitValue = this._highLimitsCache[keyOffset];
  41864. offsetValue = this._offsetsCache[keyOffset];
  41865. }
  41866. }
  41867. if (offsetValue === undefined) {
  41868. switch (this._animation.dataType) {
  41869. // Float
  41870. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41871. offsetValue = 0;
  41872. break;
  41873. // Quaternion
  41874. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41875. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41876. break;
  41877. // Vector3
  41878. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41879. offsetValue = BABYLON.Vector3.Zero();
  41880. break;
  41881. // Vector2
  41882. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41883. offsetValue = BABYLON.Vector2.Zero();
  41884. break;
  41885. // Size
  41886. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41887. offsetValue = BABYLON.Size.Zero();
  41888. break;
  41889. // Color3
  41890. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41891. offsetValue = BABYLON.Color3.Black();
  41892. }
  41893. }
  41894. // Compute value
  41895. var repeatCount = (ratio / range) >> 0;
  41896. var currentFrame = returnValue ? from + ratio % range : to;
  41897. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41898. // Set value
  41899. this.setValue(currentValue);
  41900. // Check events
  41901. var events = this._animation.getEvents();
  41902. for (var index = 0; index < events.length; index++) {
  41903. // Make sure current frame has passed event frame and that event frame is within the current range
  41904. // Also, handle both forward and reverse animations
  41905. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41906. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41907. var event = events[index];
  41908. if (!event.isDone) {
  41909. // If event should be done only once, remove it.
  41910. if (event.onlyOnce) {
  41911. events.splice(index, 1);
  41912. index--;
  41913. }
  41914. event.isDone = true;
  41915. event.action();
  41916. } // Don't do anything if the event has already be done.
  41917. }
  41918. else if (events[index].isDone && !events[index].onlyOnce) {
  41919. // reset event, the animation is looping
  41920. events[index].isDone = false;
  41921. }
  41922. }
  41923. if (!returnValue) {
  41924. this._stopped = true;
  41925. }
  41926. return returnValue;
  41927. };
  41928. return RuntimeAnimation;
  41929. }());
  41930. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41931. })(BABYLON || (BABYLON = {}));
  41932. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41933. var BABYLON;
  41934. (function (BABYLON) {
  41935. var Animatable = /** @class */ (function () {
  41936. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41937. if (fromFrame === void 0) { fromFrame = 0; }
  41938. if (toFrame === void 0) { toFrame = 100; }
  41939. if (loopAnimation === void 0) { loopAnimation = false; }
  41940. if (speedRatio === void 0) { speedRatio = 1.0; }
  41941. this.target = target;
  41942. this.fromFrame = fromFrame;
  41943. this.toFrame = toFrame;
  41944. this.loopAnimation = loopAnimation;
  41945. this.onAnimationEnd = onAnimationEnd;
  41946. this._localDelayOffset = null;
  41947. this._pausedDelay = null;
  41948. this._runtimeAnimations = new Array();
  41949. this._paused = false;
  41950. this._speedRatio = 1;
  41951. this.animationStarted = false;
  41952. if (animations) {
  41953. this.appendAnimations(target, animations);
  41954. }
  41955. this._speedRatio = speedRatio;
  41956. this._scene = scene;
  41957. scene._activeAnimatables.push(this);
  41958. }
  41959. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41960. get: function () {
  41961. return this._speedRatio;
  41962. },
  41963. set: function (value) {
  41964. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41965. var animation = this._runtimeAnimations[index];
  41966. animation._prepareForSpeedRatioChange(value);
  41967. }
  41968. this._speedRatio = value;
  41969. },
  41970. enumerable: true,
  41971. configurable: true
  41972. });
  41973. // Methods
  41974. Animatable.prototype.getAnimations = function () {
  41975. return this._runtimeAnimations;
  41976. };
  41977. Animatable.prototype.appendAnimations = function (target, animations) {
  41978. for (var index = 0; index < animations.length; index++) {
  41979. var animation = animations[index];
  41980. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41981. }
  41982. };
  41983. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41984. var runtimeAnimations = this._runtimeAnimations;
  41985. for (var index = 0; index < runtimeAnimations.length; index++) {
  41986. if (runtimeAnimations[index].animation.targetProperty === property) {
  41987. return runtimeAnimations[index].animation;
  41988. }
  41989. }
  41990. return null;
  41991. };
  41992. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41993. var runtimeAnimations = this._runtimeAnimations;
  41994. for (var index = 0; index < runtimeAnimations.length; index++) {
  41995. if (runtimeAnimations[index].animation.targetProperty === property) {
  41996. return runtimeAnimations[index];
  41997. }
  41998. }
  41999. return null;
  42000. };
  42001. Animatable.prototype.reset = function () {
  42002. var runtimeAnimations = this._runtimeAnimations;
  42003. for (var index = 0; index < runtimeAnimations.length; index++) {
  42004. runtimeAnimations[index].reset();
  42005. }
  42006. this._localDelayOffset = null;
  42007. this._pausedDelay = null;
  42008. };
  42009. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42010. var runtimeAnimations = this._runtimeAnimations;
  42011. for (var index = 0; index < runtimeAnimations.length; index++) {
  42012. runtimeAnimations[index].animation.enableBlending = true;
  42013. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42014. }
  42015. };
  42016. Animatable.prototype.disableBlending = function () {
  42017. var runtimeAnimations = this._runtimeAnimations;
  42018. for (var index = 0; index < runtimeAnimations.length; index++) {
  42019. runtimeAnimations[index].animation.enableBlending = false;
  42020. }
  42021. };
  42022. Animatable.prototype.goToFrame = function (frame) {
  42023. var runtimeAnimations = this._runtimeAnimations;
  42024. if (runtimeAnimations[0]) {
  42025. var fps = runtimeAnimations[0].animation.framePerSecond;
  42026. var currentFrame = runtimeAnimations[0].currentFrame;
  42027. var adjustTime = frame - currentFrame;
  42028. var delay = adjustTime * 1000 / fps;
  42029. if (this._localDelayOffset === null) {
  42030. this._localDelayOffset = 0;
  42031. }
  42032. this._localDelayOffset -= delay;
  42033. }
  42034. for (var index = 0; index < runtimeAnimations.length; index++) {
  42035. runtimeAnimations[index].goToFrame(frame);
  42036. }
  42037. };
  42038. Animatable.prototype.pause = function () {
  42039. if (this._paused) {
  42040. return;
  42041. }
  42042. this._paused = true;
  42043. };
  42044. Animatable.prototype.restart = function () {
  42045. this._paused = false;
  42046. };
  42047. Animatable.prototype.stop = function (animationName) {
  42048. if (animationName) {
  42049. var idx = this._scene._activeAnimatables.indexOf(this);
  42050. if (idx > -1) {
  42051. var runtimeAnimations = this._runtimeAnimations;
  42052. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42053. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42054. continue;
  42055. }
  42056. runtimeAnimations[index].dispose();
  42057. runtimeAnimations.splice(index, 1);
  42058. }
  42059. if (runtimeAnimations.length == 0) {
  42060. this._scene._activeAnimatables.splice(idx, 1);
  42061. if (this.onAnimationEnd) {
  42062. this.onAnimationEnd();
  42063. }
  42064. }
  42065. }
  42066. }
  42067. else {
  42068. var index = this._scene._activeAnimatables.indexOf(this);
  42069. if (index > -1) {
  42070. this._scene._activeAnimatables.splice(index, 1);
  42071. var runtimeAnimations = this._runtimeAnimations;
  42072. for (var index = 0; index < runtimeAnimations.length; index++) {
  42073. runtimeAnimations[index].dispose();
  42074. }
  42075. if (this.onAnimationEnd) {
  42076. this.onAnimationEnd();
  42077. }
  42078. }
  42079. }
  42080. };
  42081. Animatable.prototype._animate = function (delay) {
  42082. if (this._paused) {
  42083. this.animationStarted = false;
  42084. if (this._pausedDelay === null) {
  42085. this._pausedDelay = delay;
  42086. }
  42087. return true;
  42088. }
  42089. if (this._localDelayOffset === null) {
  42090. this._localDelayOffset = delay;
  42091. }
  42092. else if (this._pausedDelay !== null) {
  42093. this._localDelayOffset += delay - this._pausedDelay;
  42094. this._pausedDelay = null;
  42095. }
  42096. // Animating
  42097. var running = false;
  42098. var runtimeAnimations = this._runtimeAnimations;
  42099. var index;
  42100. for (index = 0; index < runtimeAnimations.length; index++) {
  42101. var animation = runtimeAnimations[index];
  42102. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42103. running = running || isRunning;
  42104. }
  42105. this.animationStarted = running;
  42106. if (!running) {
  42107. // Remove from active animatables
  42108. index = this._scene._activeAnimatables.indexOf(this);
  42109. this._scene._activeAnimatables.splice(index, 1);
  42110. // Dispose all runtime animations
  42111. for (index = 0; index < runtimeAnimations.length; index++) {
  42112. runtimeAnimations[index].dispose();
  42113. }
  42114. }
  42115. if (!running && this.onAnimationEnd) {
  42116. this.onAnimationEnd();
  42117. this.onAnimationEnd = null;
  42118. }
  42119. return running;
  42120. };
  42121. return Animatable;
  42122. }());
  42123. BABYLON.Animatable = Animatable;
  42124. })(BABYLON || (BABYLON = {}));
  42125. //# sourceMappingURL=babylon.animatable.js.map
  42126. var BABYLON;
  42127. (function (BABYLON) {
  42128. var EasingFunction = /** @class */ (function () {
  42129. function EasingFunction() {
  42130. // Properties
  42131. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42132. }
  42133. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42134. get: function () {
  42135. return EasingFunction._EASINGMODE_EASEIN;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42141. get: function () {
  42142. return EasingFunction._EASINGMODE_EASEOUT;
  42143. },
  42144. enumerable: true,
  42145. configurable: true
  42146. });
  42147. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42148. get: function () {
  42149. return EasingFunction._EASINGMODE_EASEINOUT;
  42150. },
  42151. enumerable: true,
  42152. configurable: true
  42153. });
  42154. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42155. var n = Math.min(Math.max(easingMode, 0), 2);
  42156. this._easingMode = n;
  42157. };
  42158. EasingFunction.prototype.getEasingMode = function () {
  42159. return this._easingMode;
  42160. };
  42161. EasingFunction.prototype.easeInCore = function (gradient) {
  42162. throw new Error('You must implement this method');
  42163. };
  42164. EasingFunction.prototype.ease = function (gradient) {
  42165. switch (this._easingMode) {
  42166. case EasingFunction.EASINGMODE_EASEIN:
  42167. return this.easeInCore(gradient);
  42168. case EasingFunction.EASINGMODE_EASEOUT:
  42169. return (1 - this.easeInCore(1 - gradient));
  42170. }
  42171. if (gradient >= 0.5) {
  42172. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42173. }
  42174. return (this.easeInCore(gradient * 2) * 0.5);
  42175. };
  42176. //Statics
  42177. EasingFunction._EASINGMODE_EASEIN = 0;
  42178. EasingFunction._EASINGMODE_EASEOUT = 1;
  42179. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42180. return EasingFunction;
  42181. }());
  42182. BABYLON.EasingFunction = EasingFunction;
  42183. var CircleEase = /** @class */ (function (_super) {
  42184. __extends(CircleEase, _super);
  42185. function CircleEase() {
  42186. return _super !== null && _super.apply(this, arguments) || this;
  42187. }
  42188. CircleEase.prototype.easeInCore = function (gradient) {
  42189. gradient = Math.max(0, Math.min(1, gradient));
  42190. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42191. };
  42192. return CircleEase;
  42193. }(EasingFunction));
  42194. BABYLON.CircleEase = CircleEase;
  42195. var BackEase = /** @class */ (function (_super) {
  42196. __extends(BackEase, _super);
  42197. function BackEase(amplitude) {
  42198. if (amplitude === void 0) { amplitude = 1; }
  42199. var _this = _super.call(this) || this;
  42200. _this.amplitude = amplitude;
  42201. return _this;
  42202. }
  42203. BackEase.prototype.easeInCore = function (gradient) {
  42204. var num = Math.max(0, this.amplitude);
  42205. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42206. };
  42207. return BackEase;
  42208. }(EasingFunction));
  42209. BABYLON.BackEase = BackEase;
  42210. var BounceEase = /** @class */ (function (_super) {
  42211. __extends(BounceEase, _super);
  42212. function BounceEase(bounces, bounciness) {
  42213. if (bounces === void 0) { bounces = 3; }
  42214. if (bounciness === void 0) { bounciness = 2; }
  42215. var _this = _super.call(this) || this;
  42216. _this.bounces = bounces;
  42217. _this.bounciness = bounciness;
  42218. return _this;
  42219. }
  42220. BounceEase.prototype.easeInCore = function (gradient) {
  42221. var y = Math.max(0.0, this.bounces);
  42222. var bounciness = this.bounciness;
  42223. if (bounciness <= 1.0) {
  42224. bounciness = 1.001;
  42225. }
  42226. var num9 = Math.pow(bounciness, y);
  42227. var num5 = 1.0 - bounciness;
  42228. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42229. var num15 = gradient * num4;
  42230. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42231. var num3 = Math.floor(num65);
  42232. var num13 = num3 + 1.0;
  42233. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42234. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42235. var num7 = (num8 + num12) * 0.5;
  42236. var num6 = gradient - num7;
  42237. var num2 = num7 - num8;
  42238. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42239. };
  42240. return BounceEase;
  42241. }(EasingFunction));
  42242. BABYLON.BounceEase = BounceEase;
  42243. var CubicEase = /** @class */ (function (_super) {
  42244. __extends(CubicEase, _super);
  42245. function CubicEase() {
  42246. return _super !== null && _super.apply(this, arguments) || this;
  42247. }
  42248. CubicEase.prototype.easeInCore = function (gradient) {
  42249. return (gradient * gradient * gradient);
  42250. };
  42251. return CubicEase;
  42252. }(EasingFunction));
  42253. BABYLON.CubicEase = CubicEase;
  42254. var ElasticEase = /** @class */ (function (_super) {
  42255. __extends(ElasticEase, _super);
  42256. function ElasticEase(oscillations, springiness) {
  42257. if (oscillations === void 0) { oscillations = 3; }
  42258. if (springiness === void 0) { springiness = 3; }
  42259. var _this = _super.call(this) || this;
  42260. _this.oscillations = oscillations;
  42261. _this.springiness = springiness;
  42262. return _this;
  42263. }
  42264. ElasticEase.prototype.easeInCore = function (gradient) {
  42265. var num2;
  42266. var num3 = Math.max(0.0, this.oscillations);
  42267. var num = Math.max(0.0, this.springiness);
  42268. if (num == 0) {
  42269. num2 = gradient;
  42270. }
  42271. else {
  42272. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42273. }
  42274. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42275. };
  42276. return ElasticEase;
  42277. }(EasingFunction));
  42278. BABYLON.ElasticEase = ElasticEase;
  42279. var ExponentialEase = /** @class */ (function (_super) {
  42280. __extends(ExponentialEase, _super);
  42281. function ExponentialEase(exponent) {
  42282. if (exponent === void 0) { exponent = 2; }
  42283. var _this = _super.call(this) || this;
  42284. _this.exponent = exponent;
  42285. return _this;
  42286. }
  42287. ExponentialEase.prototype.easeInCore = function (gradient) {
  42288. if (this.exponent <= 0) {
  42289. return gradient;
  42290. }
  42291. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42292. };
  42293. return ExponentialEase;
  42294. }(EasingFunction));
  42295. BABYLON.ExponentialEase = ExponentialEase;
  42296. var PowerEase = /** @class */ (function (_super) {
  42297. __extends(PowerEase, _super);
  42298. function PowerEase(power) {
  42299. if (power === void 0) { power = 2; }
  42300. var _this = _super.call(this) || this;
  42301. _this.power = power;
  42302. return _this;
  42303. }
  42304. PowerEase.prototype.easeInCore = function (gradient) {
  42305. var y = Math.max(0.0, this.power);
  42306. return Math.pow(gradient, y);
  42307. };
  42308. return PowerEase;
  42309. }(EasingFunction));
  42310. BABYLON.PowerEase = PowerEase;
  42311. var QuadraticEase = /** @class */ (function (_super) {
  42312. __extends(QuadraticEase, _super);
  42313. function QuadraticEase() {
  42314. return _super !== null && _super.apply(this, arguments) || this;
  42315. }
  42316. QuadraticEase.prototype.easeInCore = function (gradient) {
  42317. return (gradient * gradient);
  42318. };
  42319. return QuadraticEase;
  42320. }(EasingFunction));
  42321. BABYLON.QuadraticEase = QuadraticEase;
  42322. var QuarticEase = /** @class */ (function (_super) {
  42323. __extends(QuarticEase, _super);
  42324. function QuarticEase() {
  42325. return _super !== null && _super.apply(this, arguments) || this;
  42326. }
  42327. QuarticEase.prototype.easeInCore = function (gradient) {
  42328. return (gradient * gradient * gradient * gradient);
  42329. };
  42330. return QuarticEase;
  42331. }(EasingFunction));
  42332. BABYLON.QuarticEase = QuarticEase;
  42333. var QuinticEase = /** @class */ (function (_super) {
  42334. __extends(QuinticEase, _super);
  42335. function QuinticEase() {
  42336. return _super !== null && _super.apply(this, arguments) || this;
  42337. }
  42338. QuinticEase.prototype.easeInCore = function (gradient) {
  42339. return (gradient * gradient * gradient * gradient * gradient);
  42340. };
  42341. return QuinticEase;
  42342. }(EasingFunction));
  42343. BABYLON.QuinticEase = QuinticEase;
  42344. var SineEase = /** @class */ (function (_super) {
  42345. __extends(SineEase, _super);
  42346. function SineEase() {
  42347. return _super !== null && _super.apply(this, arguments) || this;
  42348. }
  42349. SineEase.prototype.easeInCore = function (gradient) {
  42350. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42351. };
  42352. return SineEase;
  42353. }(EasingFunction));
  42354. BABYLON.SineEase = SineEase;
  42355. var BezierCurveEase = /** @class */ (function (_super) {
  42356. __extends(BezierCurveEase, _super);
  42357. function BezierCurveEase(x1, y1, x2, y2) {
  42358. if (x1 === void 0) { x1 = 0; }
  42359. if (y1 === void 0) { y1 = 0; }
  42360. if (x2 === void 0) { x2 = 1; }
  42361. if (y2 === void 0) { y2 = 1; }
  42362. var _this = _super.call(this) || this;
  42363. _this.x1 = x1;
  42364. _this.y1 = y1;
  42365. _this.x2 = x2;
  42366. _this.y2 = y2;
  42367. return _this;
  42368. }
  42369. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42370. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42371. };
  42372. return BezierCurveEase;
  42373. }(EasingFunction));
  42374. BABYLON.BezierCurveEase = BezierCurveEase;
  42375. })(BABYLON || (BABYLON = {}));
  42376. //# sourceMappingURL=babylon.easing.js.map
  42377. var BABYLON;
  42378. (function (BABYLON) {
  42379. var Condition = /** @class */ (function () {
  42380. function Condition(actionManager) {
  42381. this._actionManager = actionManager;
  42382. }
  42383. Condition.prototype.isValid = function () {
  42384. return true;
  42385. };
  42386. Condition.prototype._getProperty = function (propertyPath) {
  42387. return this._actionManager._getProperty(propertyPath);
  42388. };
  42389. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42390. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42391. };
  42392. Condition.prototype.serialize = function () {
  42393. };
  42394. Condition.prototype._serialize = function (serializedCondition) {
  42395. return {
  42396. type: 2,
  42397. children: [],
  42398. name: serializedCondition.name,
  42399. properties: serializedCondition.properties
  42400. };
  42401. };
  42402. return Condition;
  42403. }());
  42404. BABYLON.Condition = Condition;
  42405. var ValueCondition = /** @class */ (function (_super) {
  42406. __extends(ValueCondition, _super);
  42407. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42408. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42409. var _this = _super.call(this, actionManager) || this;
  42410. _this.propertyPath = propertyPath;
  42411. _this.value = value;
  42412. _this.operator = operator;
  42413. _this._target = target;
  42414. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42415. _this._property = _this._getProperty(_this.propertyPath);
  42416. return _this;
  42417. }
  42418. Object.defineProperty(ValueCondition, "IsEqual", {
  42419. get: function () {
  42420. return ValueCondition._IsEqual;
  42421. },
  42422. enumerable: true,
  42423. configurable: true
  42424. });
  42425. Object.defineProperty(ValueCondition, "IsDifferent", {
  42426. get: function () {
  42427. return ValueCondition._IsDifferent;
  42428. },
  42429. enumerable: true,
  42430. configurable: true
  42431. });
  42432. Object.defineProperty(ValueCondition, "IsGreater", {
  42433. get: function () {
  42434. return ValueCondition._IsGreater;
  42435. },
  42436. enumerable: true,
  42437. configurable: true
  42438. });
  42439. Object.defineProperty(ValueCondition, "IsLesser", {
  42440. get: function () {
  42441. return ValueCondition._IsLesser;
  42442. },
  42443. enumerable: true,
  42444. configurable: true
  42445. });
  42446. // Methods
  42447. ValueCondition.prototype.isValid = function () {
  42448. switch (this.operator) {
  42449. case ValueCondition.IsGreater:
  42450. return this._effectiveTarget[this._property] > this.value;
  42451. case ValueCondition.IsLesser:
  42452. return this._effectiveTarget[this._property] < this.value;
  42453. case ValueCondition.IsEqual:
  42454. case ValueCondition.IsDifferent:
  42455. var check;
  42456. if (this.value.equals) {
  42457. check = this.value.equals(this._effectiveTarget[this._property]);
  42458. }
  42459. else {
  42460. check = this.value === this._effectiveTarget[this._property];
  42461. }
  42462. return this.operator === ValueCondition.IsEqual ? check : !check;
  42463. }
  42464. return false;
  42465. };
  42466. ValueCondition.prototype.serialize = function () {
  42467. return this._serialize({
  42468. name: "ValueCondition",
  42469. properties: [
  42470. BABYLON.Action._GetTargetProperty(this._target),
  42471. { name: "propertyPath", value: this.propertyPath },
  42472. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42473. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42474. ]
  42475. });
  42476. };
  42477. ValueCondition.GetOperatorName = function (operator) {
  42478. switch (operator) {
  42479. case ValueCondition._IsEqual: return "IsEqual";
  42480. case ValueCondition._IsDifferent: return "IsDifferent";
  42481. case ValueCondition._IsGreater: return "IsGreater";
  42482. case ValueCondition._IsLesser: return "IsLesser";
  42483. default: return "";
  42484. }
  42485. };
  42486. // Statics
  42487. ValueCondition._IsEqual = 0;
  42488. ValueCondition._IsDifferent = 1;
  42489. ValueCondition._IsGreater = 2;
  42490. ValueCondition._IsLesser = 3;
  42491. return ValueCondition;
  42492. }(Condition));
  42493. BABYLON.ValueCondition = ValueCondition;
  42494. var PredicateCondition = /** @class */ (function (_super) {
  42495. __extends(PredicateCondition, _super);
  42496. function PredicateCondition(actionManager, predicate) {
  42497. var _this = _super.call(this, actionManager) || this;
  42498. _this.predicate = predicate;
  42499. return _this;
  42500. }
  42501. PredicateCondition.prototype.isValid = function () {
  42502. return this.predicate();
  42503. };
  42504. return PredicateCondition;
  42505. }(Condition));
  42506. BABYLON.PredicateCondition = PredicateCondition;
  42507. var StateCondition = /** @class */ (function (_super) {
  42508. __extends(StateCondition, _super);
  42509. function StateCondition(actionManager, target, value) {
  42510. var _this = _super.call(this, actionManager) || this;
  42511. _this.value = value;
  42512. _this._target = target;
  42513. return _this;
  42514. }
  42515. // Methods
  42516. StateCondition.prototype.isValid = function () {
  42517. return this._target.state === this.value;
  42518. };
  42519. StateCondition.prototype.serialize = function () {
  42520. return this._serialize({
  42521. name: "StateCondition",
  42522. properties: [
  42523. BABYLON.Action._GetTargetProperty(this._target),
  42524. { name: "value", value: this.value }
  42525. ]
  42526. });
  42527. };
  42528. return StateCondition;
  42529. }(Condition));
  42530. BABYLON.StateCondition = StateCondition;
  42531. })(BABYLON || (BABYLON = {}));
  42532. //# sourceMappingURL=babylon.condition.js.map
  42533. var BABYLON;
  42534. (function (BABYLON) {
  42535. var Action = /** @class */ (function () {
  42536. function Action(triggerOptions, condition) {
  42537. this.triggerOptions = triggerOptions;
  42538. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42539. if (triggerOptions.parameter) {
  42540. this.trigger = triggerOptions.trigger;
  42541. this._triggerParameter = triggerOptions.parameter;
  42542. }
  42543. else {
  42544. this.trigger = triggerOptions;
  42545. }
  42546. this._nextActiveAction = this;
  42547. this._condition = condition;
  42548. }
  42549. // Methods
  42550. Action.prototype._prepare = function () {
  42551. };
  42552. Action.prototype.getTriggerParameter = function () {
  42553. return this._triggerParameter;
  42554. };
  42555. Action.prototype._executeCurrent = function (evt) {
  42556. if (this._nextActiveAction._condition) {
  42557. var condition = this._nextActiveAction._condition;
  42558. var currentRenderId = this._actionManager.getScene().getRenderId();
  42559. // We cache the current evaluation for the current frame
  42560. if (condition._evaluationId === currentRenderId) {
  42561. if (!condition._currentResult) {
  42562. return;
  42563. }
  42564. }
  42565. else {
  42566. condition._evaluationId = currentRenderId;
  42567. if (!condition.isValid()) {
  42568. condition._currentResult = false;
  42569. return;
  42570. }
  42571. condition._currentResult = true;
  42572. }
  42573. }
  42574. this.onBeforeExecuteObservable.notifyObservers(this);
  42575. this._nextActiveAction.execute(evt);
  42576. this.skipToNextActiveAction();
  42577. };
  42578. Action.prototype.execute = function (evt) {
  42579. };
  42580. Action.prototype.skipToNextActiveAction = function () {
  42581. if (this._nextActiveAction._child) {
  42582. if (!this._nextActiveAction._child._actionManager) {
  42583. this._nextActiveAction._child._actionManager = this._actionManager;
  42584. }
  42585. this._nextActiveAction = this._nextActiveAction._child;
  42586. }
  42587. else {
  42588. this._nextActiveAction = this;
  42589. }
  42590. };
  42591. Action.prototype.then = function (action) {
  42592. this._child = action;
  42593. action._actionManager = this._actionManager;
  42594. action._prepare();
  42595. return action;
  42596. };
  42597. Action.prototype._getProperty = function (propertyPath) {
  42598. return this._actionManager._getProperty(propertyPath);
  42599. };
  42600. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42601. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42602. };
  42603. Action.prototype.serialize = function (parent) {
  42604. };
  42605. // Called by BABYLON.Action objects in serialize(...). Internal use
  42606. Action.prototype._serialize = function (serializedAction, parent) {
  42607. var serializationObject = {
  42608. type: 1,
  42609. children: [],
  42610. name: serializedAction.name,
  42611. properties: serializedAction.properties || []
  42612. };
  42613. // Serialize child
  42614. if (this._child) {
  42615. this._child.serialize(serializationObject);
  42616. }
  42617. // Check if "this" has a condition
  42618. if (this._condition) {
  42619. var serializedCondition = this._condition.serialize();
  42620. serializedCondition.children.push(serializationObject);
  42621. if (parent) {
  42622. parent.children.push(serializedCondition);
  42623. }
  42624. return serializedCondition;
  42625. }
  42626. if (parent) {
  42627. parent.children.push(serializationObject);
  42628. }
  42629. return serializationObject;
  42630. };
  42631. Action._SerializeValueAsString = function (value) {
  42632. if (typeof value === "number") {
  42633. return value.toString();
  42634. }
  42635. if (typeof value === "boolean") {
  42636. return value ? "true" : "false";
  42637. }
  42638. if (value instanceof BABYLON.Vector2) {
  42639. return value.x + ", " + value.y;
  42640. }
  42641. if (value instanceof BABYLON.Vector3) {
  42642. return value.x + ", " + value.y + ", " + value.z;
  42643. }
  42644. if (value instanceof BABYLON.Color3) {
  42645. return value.r + ", " + value.g + ", " + value.b;
  42646. }
  42647. if (value instanceof BABYLON.Color4) {
  42648. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42649. }
  42650. return value; // string
  42651. };
  42652. Action._GetTargetProperty = function (target) {
  42653. return {
  42654. name: "target",
  42655. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42656. : target instanceof BABYLON.Light ? "LightProperties"
  42657. : target instanceof BABYLON.Camera ? "CameraProperties"
  42658. : "SceneProperties",
  42659. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42660. };
  42661. };
  42662. return Action;
  42663. }());
  42664. BABYLON.Action = Action;
  42665. })(BABYLON || (BABYLON = {}));
  42666. //# sourceMappingURL=babylon.action.js.map
  42667. var BABYLON;
  42668. (function (BABYLON) {
  42669. /**
  42670. * ActionEvent is the event beint sent when an action is triggered.
  42671. */
  42672. var ActionEvent = /** @class */ (function () {
  42673. /**
  42674. * @param source The mesh or sprite that triggered the action.
  42675. * @param pointerX The X mouse cursor position at the time of the event
  42676. * @param pointerY The Y mouse cursor position at the time of the event
  42677. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42678. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42679. */
  42680. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42681. this.source = source;
  42682. this.pointerX = pointerX;
  42683. this.pointerY = pointerY;
  42684. this.meshUnderPointer = meshUnderPointer;
  42685. this.sourceEvent = sourceEvent;
  42686. this.additionalData = additionalData;
  42687. }
  42688. /**
  42689. * Helper function to auto-create an ActionEvent from a source mesh.
  42690. * @param source The source mesh that triggered the event
  42691. * @param evt {Event} The original (browser) event
  42692. */
  42693. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42694. var scene = source.getScene();
  42695. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42696. };
  42697. /**
  42698. * Helper function to auto-create an ActionEvent from a source mesh.
  42699. * @param source The source sprite that triggered the event
  42700. * @param scene Scene associated with the sprite
  42701. * @param evt {Event} The original (browser) event
  42702. */
  42703. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42704. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42705. };
  42706. /**
  42707. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42708. * @param scene the scene where the event occurred
  42709. * @param evt {Event} The original (browser) event
  42710. */
  42711. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42712. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42713. };
  42714. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42715. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42716. };
  42717. return ActionEvent;
  42718. }());
  42719. BABYLON.ActionEvent = ActionEvent;
  42720. /**
  42721. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42722. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42723. */
  42724. var ActionManager = /** @class */ (function () {
  42725. function ActionManager(scene) {
  42726. // Members
  42727. this.actions = new Array();
  42728. this.hoverCursor = '';
  42729. this._scene = scene;
  42730. scene._actionManagers.push(this);
  42731. }
  42732. Object.defineProperty(ActionManager, "NothingTrigger", {
  42733. get: function () {
  42734. return ActionManager._NothingTrigger;
  42735. },
  42736. enumerable: true,
  42737. configurable: true
  42738. });
  42739. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42740. get: function () {
  42741. return ActionManager._OnPickTrigger;
  42742. },
  42743. enumerable: true,
  42744. configurable: true
  42745. });
  42746. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42747. get: function () {
  42748. return ActionManager._OnLeftPickTrigger;
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42754. get: function () {
  42755. return ActionManager._OnRightPickTrigger;
  42756. },
  42757. enumerable: true,
  42758. configurable: true
  42759. });
  42760. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42761. get: function () {
  42762. return ActionManager._OnCenterPickTrigger;
  42763. },
  42764. enumerable: true,
  42765. configurable: true
  42766. });
  42767. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42768. get: function () {
  42769. return ActionManager._OnPickDownTrigger;
  42770. },
  42771. enumerable: true,
  42772. configurable: true
  42773. });
  42774. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42775. get: function () {
  42776. return ActionManager._OnDoublePickTrigger;
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42782. get: function () {
  42783. return ActionManager._OnPickUpTrigger;
  42784. },
  42785. enumerable: true,
  42786. configurable: true
  42787. });
  42788. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42789. /// This trigger will only be raised if you also declared a OnPickDown
  42790. get: function () {
  42791. return ActionManager._OnPickOutTrigger;
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42797. get: function () {
  42798. return ActionManager._OnLongPressTrigger;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42804. get: function () {
  42805. return ActionManager._OnPointerOverTrigger;
  42806. },
  42807. enumerable: true,
  42808. configurable: true
  42809. });
  42810. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42811. get: function () {
  42812. return ActionManager._OnPointerOutTrigger;
  42813. },
  42814. enumerable: true,
  42815. configurable: true
  42816. });
  42817. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42818. get: function () {
  42819. return ActionManager._OnEveryFrameTrigger;
  42820. },
  42821. enumerable: true,
  42822. configurable: true
  42823. });
  42824. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42825. get: function () {
  42826. return ActionManager._OnIntersectionEnterTrigger;
  42827. },
  42828. enumerable: true,
  42829. configurable: true
  42830. });
  42831. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42832. get: function () {
  42833. return ActionManager._OnIntersectionExitTrigger;
  42834. },
  42835. enumerable: true,
  42836. configurable: true
  42837. });
  42838. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42839. get: function () {
  42840. return ActionManager._OnKeyDownTrigger;
  42841. },
  42842. enumerable: true,
  42843. configurable: true
  42844. });
  42845. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42846. get: function () {
  42847. return ActionManager._OnKeyUpTrigger;
  42848. },
  42849. enumerable: true,
  42850. configurable: true
  42851. });
  42852. // Methods
  42853. ActionManager.prototype.dispose = function () {
  42854. var index = this._scene._actionManagers.indexOf(this);
  42855. for (var i = 0; i < this.actions.length; i++) {
  42856. var action = this.actions[i];
  42857. ActionManager.Triggers[action.trigger]--;
  42858. if (ActionManager.Triggers[action.trigger] === 0) {
  42859. delete ActionManager.Triggers[action.trigger];
  42860. }
  42861. }
  42862. if (index > -1) {
  42863. this._scene._actionManagers.splice(index, 1);
  42864. }
  42865. };
  42866. ActionManager.prototype.getScene = function () {
  42867. return this._scene;
  42868. };
  42869. /**
  42870. * Does this action manager handles actions of any of the given triggers
  42871. * @param {number[]} triggers - the triggers to be tested
  42872. * @return {boolean} whether one (or more) of the triggers is handeled
  42873. */
  42874. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42875. for (var index = 0; index < this.actions.length; index++) {
  42876. var action = this.actions[index];
  42877. if (triggers.indexOf(action.trigger) > -1) {
  42878. return true;
  42879. }
  42880. }
  42881. return false;
  42882. };
  42883. /**
  42884. * Does this action manager handles actions of a given trigger
  42885. * @param {number} trigger - the trigger to be tested
  42886. * @return {boolean} whether the trigger is handeled
  42887. */
  42888. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42889. for (var index = 0; index < this.actions.length; index++) {
  42890. var action = this.actions[index];
  42891. if (action.trigger === trigger) {
  42892. return true;
  42893. }
  42894. }
  42895. return false;
  42896. };
  42897. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42898. /**
  42899. * Does this action manager has pointer triggers
  42900. * @return {boolean} whether or not it has pointer triggers
  42901. */
  42902. get: function () {
  42903. for (var index = 0; index < this.actions.length; index++) {
  42904. var action = this.actions[index];
  42905. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42906. return true;
  42907. }
  42908. }
  42909. return false;
  42910. },
  42911. enumerable: true,
  42912. configurable: true
  42913. });
  42914. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42915. /**
  42916. * Does this action manager has pick triggers
  42917. * @return {boolean} whether or not it has pick triggers
  42918. */
  42919. get: function () {
  42920. for (var index = 0; index < this.actions.length; index++) {
  42921. var action = this.actions[index];
  42922. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42923. return true;
  42924. }
  42925. }
  42926. return false;
  42927. },
  42928. enumerable: true,
  42929. configurable: true
  42930. });
  42931. Object.defineProperty(ActionManager, "HasTriggers", {
  42932. /**
  42933. * Does exist one action manager with at least one trigger
  42934. * @return {boolean} whether or not it exists one action manager with one trigger
  42935. **/
  42936. get: function () {
  42937. for (var t in ActionManager.Triggers) {
  42938. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42939. return true;
  42940. }
  42941. }
  42942. return false;
  42943. },
  42944. enumerable: true,
  42945. configurable: true
  42946. });
  42947. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42948. /**
  42949. * Does exist one action manager with at least one pick trigger
  42950. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42951. **/
  42952. get: function () {
  42953. for (var t in ActionManager.Triggers) {
  42954. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42955. var t_int = parseInt(t);
  42956. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42957. return true;
  42958. }
  42959. }
  42960. }
  42961. return false;
  42962. },
  42963. enumerable: true,
  42964. configurable: true
  42965. });
  42966. /**
  42967. * Does exist one action manager that handles actions of a given trigger
  42968. * @param {number} trigger - the trigger to be tested
  42969. * @return {boolean} whether the trigger is handeled by at least one action manager
  42970. **/
  42971. ActionManager.HasSpecificTrigger = function (trigger) {
  42972. for (var t in ActionManager.Triggers) {
  42973. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42974. var t_int = parseInt(t);
  42975. if (t_int === trigger) {
  42976. return true;
  42977. }
  42978. }
  42979. }
  42980. return false;
  42981. };
  42982. /**
  42983. * Registers an action to this action manager
  42984. * @param {BABYLON.Action} action - the action to be registered
  42985. * @return {BABYLON.Action} the action amended (prepared) after registration
  42986. */
  42987. ActionManager.prototype.registerAction = function (action) {
  42988. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42989. if (this.getScene().actionManager !== this) {
  42990. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42991. return null;
  42992. }
  42993. }
  42994. this.actions.push(action);
  42995. if (ActionManager.Triggers[action.trigger]) {
  42996. ActionManager.Triggers[action.trigger]++;
  42997. }
  42998. else {
  42999. ActionManager.Triggers[action.trigger] = 1;
  43000. }
  43001. action._actionManager = this;
  43002. action._prepare();
  43003. return action;
  43004. };
  43005. /**
  43006. * Process a specific trigger
  43007. * @param {number} trigger - the trigger to process
  43008. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43009. */
  43010. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43011. for (var index = 0; index < this.actions.length; index++) {
  43012. var action = this.actions[index];
  43013. if (action.trigger === trigger) {
  43014. if (evt) {
  43015. if (trigger === ActionManager.OnKeyUpTrigger
  43016. || trigger === ActionManager.OnKeyDownTrigger) {
  43017. var parameter = action.getTriggerParameter();
  43018. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43019. if (!parameter.toLowerCase) {
  43020. continue;
  43021. }
  43022. var lowerCase = parameter.toLowerCase();
  43023. if (lowerCase !== evt.sourceEvent.key) {
  43024. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43025. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43026. if (actualkey !== lowerCase) {
  43027. continue;
  43028. }
  43029. }
  43030. }
  43031. }
  43032. }
  43033. action._executeCurrent(evt);
  43034. }
  43035. }
  43036. };
  43037. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43038. var properties = propertyPath.split(".");
  43039. for (var index = 0; index < properties.length - 1; index++) {
  43040. target = target[properties[index]];
  43041. }
  43042. return target;
  43043. };
  43044. ActionManager.prototype._getProperty = function (propertyPath) {
  43045. var properties = propertyPath.split(".");
  43046. return properties[properties.length - 1];
  43047. };
  43048. ActionManager.prototype.serialize = function (name) {
  43049. var root = {
  43050. children: new Array(),
  43051. name: name,
  43052. type: 3,
  43053. properties: new Array() // Empty for root but required
  43054. };
  43055. for (var i = 0; i < this.actions.length; i++) {
  43056. var triggerObject = {
  43057. type: 0,
  43058. children: new Array(),
  43059. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43060. properties: new Array()
  43061. };
  43062. var triggerOptions = this.actions[i].triggerOptions;
  43063. if (triggerOptions && typeof triggerOptions !== "number") {
  43064. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43065. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43066. }
  43067. else {
  43068. var parameter = {};
  43069. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43070. if (triggerOptions.parameter.mesh) {
  43071. parameter._meshId = triggerOptions.parameter.mesh.id;
  43072. }
  43073. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43074. }
  43075. }
  43076. // Serialize child action, recursively
  43077. this.actions[i].serialize(triggerObject);
  43078. // Add serialized trigger
  43079. root.children.push(triggerObject);
  43080. }
  43081. return root;
  43082. };
  43083. ActionManager.Parse = function (parsedActions, object, scene) {
  43084. var actionManager = new ActionManager(scene);
  43085. if (object === null)
  43086. scene.actionManager = actionManager;
  43087. else
  43088. object.actionManager = actionManager;
  43089. // instanciate a new object
  43090. var instanciate = function (name, params) {
  43091. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43092. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43093. newInstance.constructor.apply(newInstance, params);
  43094. return newInstance;
  43095. };
  43096. var parseParameter = function (name, value, target, propertyPath) {
  43097. if (propertyPath === null) {
  43098. // String, boolean or float
  43099. var floatValue = parseFloat(value);
  43100. if (value === "true" || value === "false")
  43101. return value === "true";
  43102. else
  43103. return isNaN(floatValue) ? value : floatValue;
  43104. }
  43105. var effectiveTarget = propertyPath.split(".");
  43106. var values = value.split(",");
  43107. // Get effective Target
  43108. for (var i = 0; i < effectiveTarget.length; i++) {
  43109. target = target[effectiveTarget[i]];
  43110. }
  43111. // Return appropriate value with its type
  43112. if (typeof (target) === "boolean")
  43113. return values[0] === "true";
  43114. if (typeof (target) === "string")
  43115. return values[0];
  43116. // Parameters with multiple values such as Vector3 etc.
  43117. var split = new Array();
  43118. for (var i = 0; i < values.length; i++)
  43119. split.push(parseFloat(values[i]));
  43120. if (target instanceof BABYLON.Vector3)
  43121. return BABYLON.Vector3.FromArray(split);
  43122. if (target instanceof BABYLON.Vector4)
  43123. return BABYLON.Vector4.FromArray(split);
  43124. if (target instanceof BABYLON.Color3)
  43125. return BABYLON.Color3.FromArray(split);
  43126. if (target instanceof BABYLON.Color4)
  43127. return BABYLON.Color4.FromArray(split);
  43128. return parseFloat(values[0]);
  43129. };
  43130. // traverse graph per trigger
  43131. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43132. if (combineArray === void 0) { combineArray = null; }
  43133. if (parsedAction.detached)
  43134. return;
  43135. var parameters = new Array();
  43136. var target = null;
  43137. var propertyPath = null;
  43138. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43139. // Parameters
  43140. if (parsedAction.type === 2)
  43141. parameters.push(actionManager);
  43142. else
  43143. parameters.push(trigger);
  43144. if (combine) {
  43145. var actions = new Array();
  43146. for (var j = 0; j < parsedAction.combine.length; j++) {
  43147. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43148. }
  43149. parameters.push(actions);
  43150. }
  43151. else {
  43152. for (var i = 0; i < parsedAction.properties.length; i++) {
  43153. var value = parsedAction.properties[i].value;
  43154. var name = parsedAction.properties[i].name;
  43155. var targetType = parsedAction.properties[i].targetType;
  43156. if (name === "target")
  43157. if (targetType !== null && targetType === "SceneProperties")
  43158. value = target = scene;
  43159. else
  43160. value = target = scene.getNodeByName(value);
  43161. else if (name === "parent")
  43162. value = scene.getNodeByName(value);
  43163. else if (name === "sound")
  43164. value = scene.getSoundByName(value);
  43165. else if (name !== "propertyPath") {
  43166. if (parsedAction.type === 2 && name === "operator")
  43167. value = BABYLON.ValueCondition[value];
  43168. else
  43169. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43170. }
  43171. else {
  43172. propertyPath = value;
  43173. }
  43174. parameters.push(value);
  43175. }
  43176. }
  43177. if (combineArray === null) {
  43178. parameters.push(condition);
  43179. }
  43180. else {
  43181. parameters.push(null);
  43182. }
  43183. // If interpolate value action
  43184. if (parsedAction.name === "InterpolateValueAction") {
  43185. var param = parameters[parameters.length - 2];
  43186. parameters[parameters.length - 1] = param;
  43187. parameters[parameters.length - 2] = condition;
  43188. }
  43189. // Action or condition(s) and not CombineAction
  43190. var newAction = instanciate(parsedAction.name, parameters);
  43191. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43192. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43193. if (action)
  43194. action.then(nothing);
  43195. else
  43196. actionManager.registerAction(nothing);
  43197. action = nothing;
  43198. }
  43199. if (combineArray === null) {
  43200. if (newAction instanceof BABYLON.Condition) {
  43201. condition = newAction;
  43202. newAction = action;
  43203. }
  43204. else {
  43205. condition = null;
  43206. if (action)
  43207. action.then(newAction);
  43208. else
  43209. actionManager.registerAction(newAction);
  43210. }
  43211. }
  43212. else {
  43213. combineArray.push(newAction);
  43214. }
  43215. for (var i = 0; i < parsedAction.children.length; i++)
  43216. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43217. };
  43218. // triggers
  43219. for (var i = 0; i < parsedActions.children.length; i++) {
  43220. var triggerParams;
  43221. var trigger = parsedActions.children[i];
  43222. if (trigger.properties.length > 0) {
  43223. var param = trigger.properties[0].value;
  43224. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43225. if (value._meshId) {
  43226. value.mesh = scene.getMeshByID(value._meshId);
  43227. }
  43228. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43229. }
  43230. else
  43231. triggerParams = ActionManager[trigger.name];
  43232. for (var j = 0; j < trigger.children.length; j++) {
  43233. if (!trigger.detached)
  43234. traverse(trigger.children[j], triggerParams, null, null);
  43235. }
  43236. }
  43237. };
  43238. ActionManager.GetTriggerName = function (trigger) {
  43239. switch (trigger) {
  43240. case 0: return "NothingTrigger";
  43241. case 1: return "OnPickTrigger";
  43242. case 2: return "OnLeftPickTrigger";
  43243. case 3: return "OnRightPickTrigger";
  43244. case 4: return "OnCenterPickTrigger";
  43245. case 5: return "OnPickDownTrigger";
  43246. case 6: return "OnPickUpTrigger";
  43247. case 7: return "OnLongPressTrigger";
  43248. case 8: return "OnPointerOverTrigger";
  43249. case 9: return "OnPointerOutTrigger";
  43250. case 10: return "OnEveryFrameTrigger";
  43251. case 11: return "OnIntersectionEnterTrigger";
  43252. case 12: return "OnIntersectionExitTrigger";
  43253. case 13: return "OnKeyDownTrigger";
  43254. case 14: return "OnKeyUpTrigger";
  43255. case 15: return "OnPickOutTrigger";
  43256. default: return "";
  43257. }
  43258. };
  43259. // Statics
  43260. ActionManager._NothingTrigger = 0;
  43261. ActionManager._OnPickTrigger = 1;
  43262. ActionManager._OnLeftPickTrigger = 2;
  43263. ActionManager._OnRightPickTrigger = 3;
  43264. ActionManager._OnCenterPickTrigger = 4;
  43265. ActionManager._OnPickDownTrigger = 5;
  43266. ActionManager._OnDoublePickTrigger = 6;
  43267. ActionManager._OnPickUpTrigger = 7;
  43268. ActionManager._OnLongPressTrigger = 8;
  43269. ActionManager._OnPointerOverTrigger = 9;
  43270. ActionManager._OnPointerOutTrigger = 10;
  43271. ActionManager._OnEveryFrameTrigger = 11;
  43272. ActionManager._OnIntersectionEnterTrigger = 12;
  43273. ActionManager._OnIntersectionExitTrigger = 13;
  43274. ActionManager._OnKeyDownTrigger = 14;
  43275. ActionManager._OnKeyUpTrigger = 15;
  43276. ActionManager._OnPickOutTrigger = 16;
  43277. ActionManager.Triggers = {};
  43278. return ActionManager;
  43279. }());
  43280. BABYLON.ActionManager = ActionManager;
  43281. })(BABYLON || (BABYLON = {}));
  43282. //# sourceMappingURL=babylon.actionManager.js.map
  43283. var BABYLON;
  43284. (function (BABYLON) {
  43285. var InterpolateValueAction = /** @class */ (function (_super) {
  43286. __extends(InterpolateValueAction, _super);
  43287. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43288. if (duration === void 0) { duration = 1000; }
  43289. var _this = _super.call(this, triggerOptions, condition) || this;
  43290. _this.propertyPath = propertyPath;
  43291. _this.value = value;
  43292. _this.duration = duration;
  43293. _this.stopOtherAnimations = stopOtherAnimations;
  43294. _this.onInterpolationDone = onInterpolationDone;
  43295. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43296. _this._target = _this._effectiveTarget = target;
  43297. return _this;
  43298. }
  43299. InterpolateValueAction.prototype._prepare = function () {
  43300. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43301. this._property = this._getProperty(this.propertyPath);
  43302. };
  43303. InterpolateValueAction.prototype.execute = function () {
  43304. var _this = this;
  43305. var scene = this._actionManager.getScene();
  43306. var keys = [
  43307. {
  43308. frame: 0,
  43309. value: this._effectiveTarget[this._property]
  43310. }, {
  43311. frame: 100,
  43312. value: this.value
  43313. }
  43314. ];
  43315. var dataType;
  43316. if (typeof this.value === "number") {
  43317. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43318. }
  43319. else if (this.value instanceof BABYLON.Color3) {
  43320. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43321. }
  43322. else if (this.value instanceof BABYLON.Vector3) {
  43323. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43324. }
  43325. else if (this.value instanceof BABYLON.Matrix) {
  43326. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43327. }
  43328. else if (this.value instanceof BABYLON.Quaternion) {
  43329. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43330. }
  43331. else {
  43332. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43333. return;
  43334. }
  43335. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43336. animation.setKeys(keys);
  43337. if (this.stopOtherAnimations) {
  43338. scene.stopAnimation(this._effectiveTarget);
  43339. }
  43340. var wrapper = function () {
  43341. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43342. if (_this.onInterpolationDone) {
  43343. _this.onInterpolationDone();
  43344. }
  43345. };
  43346. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43347. };
  43348. InterpolateValueAction.prototype.serialize = function (parent) {
  43349. return _super.prototype._serialize.call(this, {
  43350. name: "InterpolateValueAction",
  43351. properties: [
  43352. BABYLON.Action._GetTargetProperty(this._target),
  43353. { name: "propertyPath", value: this.propertyPath },
  43354. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43355. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43356. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43357. ]
  43358. }, parent);
  43359. };
  43360. return InterpolateValueAction;
  43361. }(BABYLON.Action));
  43362. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43363. })(BABYLON || (BABYLON = {}));
  43364. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43365. var BABYLON;
  43366. (function (BABYLON) {
  43367. var SwitchBooleanAction = /** @class */ (function (_super) {
  43368. __extends(SwitchBooleanAction, _super);
  43369. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43370. var _this = _super.call(this, triggerOptions, condition) || this;
  43371. _this.propertyPath = propertyPath;
  43372. _this._target = _this._effectiveTarget = target;
  43373. return _this;
  43374. }
  43375. SwitchBooleanAction.prototype._prepare = function () {
  43376. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43377. this._property = this._getProperty(this.propertyPath);
  43378. };
  43379. SwitchBooleanAction.prototype.execute = function () {
  43380. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43381. };
  43382. SwitchBooleanAction.prototype.serialize = function (parent) {
  43383. return _super.prototype._serialize.call(this, {
  43384. name: "SwitchBooleanAction",
  43385. properties: [
  43386. BABYLON.Action._GetTargetProperty(this._target),
  43387. { name: "propertyPath", value: this.propertyPath }
  43388. ]
  43389. }, parent);
  43390. };
  43391. return SwitchBooleanAction;
  43392. }(BABYLON.Action));
  43393. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43394. var SetStateAction = /** @class */ (function (_super) {
  43395. __extends(SetStateAction, _super);
  43396. function SetStateAction(triggerOptions, target, value, condition) {
  43397. var _this = _super.call(this, triggerOptions, condition) || this;
  43398. _this.value = value;
  43399. _this._target = target;
  43400. return _this;
  43401. }
  43402. SetStateAction.prototype.execute = function () {
  43403. this._target.state = this.value;
  43404. };
  43405. SetStateAction.prototype.serialize = function (parent) {
  43406. return _super.prototype._serialize.call(this, {
  43407. name: "SetStateAction",
  43408. properties: [
  43409. BABYLON.Action._GetTargetProperty(this._target),
  43410. { name: "value", value: this.value }
  43411. ]
  43412. }, parent);
  43413. };
  43414. return SetStateAction;
  43415. }(BABYLON.Action));
  43416. BABYLON.SetStateAction = SetStateAction;
  43417. var SetValueAction = /** @class */ (function (_super) {
  43418. __extends(SetValueAction, _super);
  43419. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43420. var _this = _super.call(this, triggerOptions, condition) || this;
  43421. _this.propertyPath = propertyPath;
  43422. _this.value = value;
  43423. _this._target = _this._effectiveTarget = target;
  43424. return _this;
  43425. }
  43426. SetValueAction.prototype._prepare = function () {
  43427. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43428. this._property = this._getProperty(this.propertyPath);
  43429. };
  43430. SetValueAction.prototype.execute = function () {
  43431. this._effectiveTarget[this._property] = this.value;
  43432. if (this._target.markAsDirty) {
  43433. this._target.markAsDirty(this._property);
  43434. }
  43435. };
  43436. SetValueAction.prototype.serialize = function (parent) {
  43437. return _super.prototype._serialize.call(this, {
  43438. name: "SetValueAction",
  43439. properties: [
  43440. BABYLON.Action._GetTargetProperty(this._target),
  43441. { name: "propertyPath", value: this.propertyPath },
  43442. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43443. ]
  43444. }, parent);
  43445. };
  43446. return SetValueAction;
  43447. }(BABYLON.Action));
  43448. BABYLON.SetValueAction = SetValueAction;
  43449. var IncrementValueAction = /** @class */ (function (_super) {
  43450. __extends(IncrementValueAction, _super);
  43451. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43452. var _this = _super.call(this, triggerOptions, condition) || this;
  43453. _this.propertyPath = propertyPath;
  43454. _this.value = value;
  43455. _this._target = _this._effectiveTarget = target;
  43456. return _this;
  43457. }
  43458. IncrementValueAction.prototype._prepare = function () {
  43459. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43460. this._property = this._getProperty(this.propertyPath);
  43461. if (typeof this._effectiveTarget[this._property] !== "number") {
  43462. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43463. }
  43464. };
  43465. IncrementValueAction.prototype.execute = function () {
  43466. this._effectiveTarget[this._property] += this.value;
  43467. if (this._target.markAsDirty) {
  43468. this._target.markAsDirty(this._property);
  43469. }
  43470. };
  43471. IncrementValueAction.prototype.serialize = function (parent) {
  43472. return _super.prototype._serialize.call(this, {
  43473. name: "IncrementValueAction",
  43474. properties: [
  43475. BABYLON.Action._GetTargetProperty(this._target),
  43476. { name: "propertyPath", value: this.propertyPath },
  43477. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43478. ]
  43479. }, parent);
  43480. };
  43481. return IncrementValueAction;
  43482. }(BABYLON.Action));
  43483. BABYLON.IncrementValueAction = IncrementValueAction;
  43484. var PlayAnimationAction = /** @class */ (function (_super) {
  43485. __extends(PlayAnimationAction, _super);
  43486. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43487. var _this = _super.call(this, triggerOptions, condition) || this;
  43488. _this.from = from;
  43489. _this.to = to;
  43490. _this.loop = loop;
  43491. _this._target = target;
  43492. return _this;
  43493. }
  43494. PlayAnimationAction.prototype._prepare = function () {
  43495. };
  43496. PlayAnimationAction.prototype.execute = function () {
  43497. var scene = this._actionManager.getScene();
  43498. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43499. };
  43500. PlayAnimationAction.prototype.serialize = function (parent) {
  43501. return _super.prototype._serialize.call(this, {
  43502. name: "PlayAnimationAction",
  43503. properties: [
  43504. BABYLON.Action._GetTargetProperty(this._target),
  43505. { name: "from", value: String(this.from) },
  43506. { name: "to", value: String(this.to) },
  43507. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43508. ]
  43509. }, parent);
  43510. };
  43511. return PlayAnimationAction;
  43512. }(BABYLON.Action));
  43513. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43514. var StopAnimationAction = /** @class */ (function (_super) {
  43515. __extends(StopAnimationAction, _super);
  43516. function StopAnimationAction(triggerOptions, target, condition) {
  43517. var _this = _super.call(this, triggerOptions, condition) || this;
  43518. _this._target = target;
  43519. return _this;
  43520. }
  43521. StopAnimationAction.prototype._prepare = function () {
  43522. };
  43523. StopAnimationAction.prototype.execute = function () {
  43524. var scene = this._actionManager.getScene();
  43525. scene.stopAnimation(this._target);
  43526. };
  43527. StopAnimationAction.prototype.serialize = function (parent) {
  43528. return _super.prototype._serialize.call(this, {
  43529. name: "StopAnimationAction",
  43530. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43531. }, parent);
  43532. };
  43533. return StopAnimationAction;
  43534. }(BABYLON.Action));
  43535. BABYLON.StopAnimationAction = StopAnimationAction;
  43536. var DoNothingAction = /** @class */ (function (_super) {
  43537. __extends(DoNothingAction, _super);
  43538. function DoNothingAction(triggerOptions, condition) {
  43539. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43540. return _super.call(this, triggerOptions, condition) || this;
  43541. }
  43542. DoNothingAction.prototype.execute = function () {
  43543. };
  43544. DoNothingAction.prototype.serialize = function (parent) {
  43545. return _super.prototype._serialize.call(this, {
  43546. name: "DoNothingAction",
  43547. properties: []
  43548. }, parent);
  43549. };
  43550. return DoNothingAction;
  43551. }(BABYLON.Action));
  43552. BABYLON.DoNothingAction = DoNothingAction;
  43553. var CombineAction = /** @class */ (function (_super) {
  43554. __extends(CombineAction, _super);
  43555. function CombineAction(triggerOptions, children, condition) {
  43556. var _this = _super.call(this, triggerOptions, condition) || this;
  43557. _this.children = children;
  43558. return _this;
  43559. }
  43560. CombineAction.prototype._prepare = function () {
  43561. for (var index = 0; index < this.children.length; index++) {
  43562. this.children[index]._actionManager = this._actionManager;
  43563. this.children[index]._prepare();
  43564. }
  43565. };
  43566. CombineAction.prototype.execute = function (evt) {
  43567. for (var index = 0; index < this.children.length; index++) {
  43568. this.children[index].execute(evt);
  43569. }
  43570. };
  43571. CombineAction.prototype.serialize = function (parent) {
  43572. var serializationObject = _super.prototype._serialize.call(this, {
  43573. name: "CombineAction",
  43574. properties: [],
  43575. combine: []
  43576. }, parent);
  43577. for (var i = 0; i < this.children.length; i++) {
  43578. serializationObject.combine.push(this.children[i].serialize(null));
  43579. }
  43580. return serializationObject;
  43581. };
  43582. return CombineAction;
  43583. }(BABYLON.Action));
  43584. BABYLON.CombineAction = CombineAction;
  43585. var ExecuteCodeAction = /** @class */ (function (_super) {
  43586. __extends(ExecuteCodeAction, _super);
  43587. function ExecuteCodeAction(triggerOptions, func, condition) {
  43588. var _this = _super.call(this, triggerOptions, condition) || this;
  43589. _this.func = func;
  43590. return _this;
  43591. }
  43592. ExecuteCodeAction.prototype.execute = function (evt) {
  43593. this.func(evt);
  43594. };
  43595. return ExecuteCodeAction;
  43596. }(BABYLON.Action));
  43597. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43598. var SetParentAction = /** @class */ (function (_super) {
  43599. __extends(SetParentAction, _super);
  43600. function SetParentAction(triggerOptions, target, parent, condition) {
  43601. var _this = _super.call(this, triggerOptions, condition) || this;
  43602. _this._target = target;
  43603. _this._parent = parent;
  43604. return _this;
  43605. }
  43606. SetParentAction.prototype._prepare = function () {
  43607. };
  43608. SetParentAction.prototype.execute = function () {
  43609. if (this._target.parent === this._parent) {
  43610. return;
  43611. }
  43612. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43613. invertParentWorldMatrix.invert();
  43614. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43615. this._target.parent = this._parent;
  43616. };
  43617. SetParentAction.prototype.serialize = function (parent) {
  43618. return _super.prototype._serialize.call(this, {
  43619. name: "SetParentAction",
  43620. properties: [
  43621. BABYLON.Action._GetTargetProperty(this._target),
  43622. BABYLON.Action._GetTargetProperty(this._parent),
  43623. ]
  43624. }, parent);
  43625. };
  43626. return SetParentAction;
  43627. }(BABYLON.Action));
  43628. BABYLON.SetParentAction = SetParentAction;
  43629. var PlaySoundAction = /** @class */ (function (_super) {
  43630. __extends(PlaySoundAction, _super);
  43631. function PlaySoundAction(triggerOptions, sound, condition) {
  43632. var _this = _super.call(this, triggerOptions, condition) || this;
  43633. _this._sound = sound;
  43634. return _this;
  43635. }
  43636. PlaySoundAction.prototype._prepare = function () {
  43637. };
  43638. PlaySoundAction.prototype.execute = function () {
  43639. if (this._sound !== undefined)
  43640. this._sound.play();
  43641. };
  43642. PlaySoundAction.prototype.serialize = function (parent) {
  43643. return _super.prototype._serialize.call(this, {
  43644. name: "PlaySoundAction",
  43645. properties: [{ name: "sound", value: this._sound.name }]
  43646. }, parent);
  43647. };
  43648. return PlaySoundAction;
  43649. }(BABYLON.Action));
  43650. BABYLON.PlaySoundAction = PlaySoundAction;
  43651. var StopSoundAction = /** @class */ (function (_super) {
  43652. __extends(StopSoundAction, _super);
  43653. function StopSoundAction(triggerOptions, sound, condition) {
  43654. var _this = _super.call(this, triggerOptions, condition) || this;
  43655. _this._sound = sound;
  43656. return _this;
  43657. }
  43658. StopSoundAction.prototype._prepare = function () {
  43659. };
  43660. StopSoundAction.prototype.execute = function () {
  43661. if (this._sound !== undefined)
  43662. this._sound.stop();
  43663. };
  43664. StopSoundAction.prototype.serialize = function (parent) {
  43665. return _super.prototype._serialize.call(this, {
  43666. name: "StopSoundAction",
  43667. properties: [{ name: "sound", value: this._sound.name }]
  43668. }, parent);
  43669. };
  43670. return StopSoundAction;
  43671. }(BABYLON.Action));
  43672. BABYLON.StopSoundAction = StopSoundAction;
  43673. })(BABYLON || (BABYLON = {}));
  43674. //# sourceMappingURL=babylon.directActions.js.map
  43675. var BABYLON;
  43676. (function (BABYLON) {
  43677. var SpriteManager = /** @class */ (function () {
  43678. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43679. if (epsilon === void 0) { epsilon = 0.01; }
  43680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43681. this.name = name;
  43682. this.sprites = new Array();
  43683. this.renderingGroupId = 0;
  43684. this.layerMask = 0x0FFFFFFF;
  43685. this.fogEnabled = true;
  43686. this.isPickable = false;
  43687. /**
  43688. * An event triggered when the manager is disposed.
  43689. * @type {BABYLON.Observable}
  43690. */
  43691. this.onDisposeObservable = new BABYLON.Observable();
  43692. this._vertexBuffers = {};
  43693. this._capacity = capacity;
  43694. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43695. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43696. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43697. if (cellSize.width && cellSize.height) {
  43698. this.cellWidth = cellSize.width;
  43699. this.cellHeight = cellSize.height;
  43700. }
  43701. else if (cellSize !== undefined) {
  43702. this.cellWidth = cellSize;
  43703. this.cellHeight = cellSize;
  43704. }
  43705. else {
  43706. return;
  43707. }
  43708. this._epsilon = epsilon;
  43709. this._scene = scene;
  43710. this._scene.spriteManagers.push(this);
  43711. var indices = [];
  43712. var index = 0;
  43713. for (var count = 0; count < capacity; count++) {
  43714. indices.push(index);
  43715. indices.push(index + 1);
  43716. indices.push(index + 2);
  43717. indices.push(index);
  43718. indices.push(index + 2);
  43719. indices.push(index + 3);
  43720. index += 4;
  43721. }
  43722. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43723. // VBO
  43724. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43725. this._vertexData = new Float32Array(capacity * 16 * 4);
  43726. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43727. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43728. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43729. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43730. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43731. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43732. this._vertexBuffers["options"] = options;
  43733. this._vertexBuffers["cellInfo"] = cellInfo;
  43734. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43735. // Effects
  43736. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43737. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43738. }
  43739. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43740. set: function (callback) {
  43741. if (this._onDisposeObserver) {
  43742. this.onDisposeObservable.remove(this._onDisposeObserver);
  43743. }
  43744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43745. },
  43746. enumerable: true,
  43747. configurable: true
  43748. });
  43749. Object.defineProperty(SpriteManager.prototype, "texture", {
  43750. get: function () {
  43751. return this._spriteTexture;
  43752. },
  43753. set: function (value) {
  43754. this._spriteTexture = value;
  43755. },
  43756. enumerable: true,
  43757. configurable: true
  43758. });
  43759. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43760. var arrayOffset = index * 16;
  43761. if (offsetX === 0)
  43762. offsetX = this._epsilon;
  43763. else if (offsetX === 1)
  43764. offsetX = 1 - this._epsilon;
  43765. if (offsetY === 0)
  43766. offsetY = this._epsilon;
  43767. else if (offsetY === 1)
  43768. offsetY = 1 - this._epsilon;
  43769. this._vertexData[arrayOffset] = sprite.position.x;
  43770. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43771. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43772. this._vertexData[arrayOffset + 3] = sprite.angle;
  43773. this._vertexData[arrayOffset + 4] = sprite.width;
  43774. this._vertexData[arrayOffset + 5] = sprite.height;
  43775. this._vertexData[arrayOffset + 6] = offsetX;
  43776. this._vertexData[arrayOffset + 7] = offsetY;
  43777. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43778. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43779. var offset = (sprite.cellIndex / rowSize) >> 0;
  43780. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43781. this._vertexData[arrayOffset + 11] = offset;
  43782. // Color
  43783. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43784. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43785. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43786. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43787. };
  43788. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43789. var count = Math.min(this._capacity, this.sprites.length);
  43790. var min = BABYLON.Vector3.Zero();
  43791. var max = BABYLON.Vector3.Zero();
  43792. var distance = Number.MAX_VALUE;
  43793. var currentSprite = null;
  43794. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43795. var cameraView = camera.getViewMatrix();
  43796. for (var index = 0; index < count; index++) {
  43797. var sprite = this.sprites[index];
  43798. if (!sprite) {
  43799. continue;
  43800. }
  43801. if (predicate) {
  43802. if (!predicate(sprite)) {
  43803. continue;
  43804. }
  43805. }
  43806. else if (!sprite.isPickable) {
  43807. continue;
  43808. }
  43809. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43810. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43811. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43812. if (ray.intersectsBoxMinMax(min, max)) {
  43813. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43814. if (distance > currentDistance) {
  43815. distance = currentDistance;
  43816. currentSprite = sprite;
  43817. if (fastCheck) {
  43818. break;
  43819. }
  43820. }
  43821. }
  43822. }
  43823. if (currentSprite) {
  43824. var result = new BABYLON.PickingInfo();
  43825. result.hit = true;
  43826. result.pickedSprite = currentSprite;
  43827. result.distance = distance;
  43828. return result;
  43829. }
  43830. return null;
  43831. };
  43832. SpriteManager.prototype.render = function () {
  43833. // Check
  43834. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43835. return;
  43836. var engine = this._scene.getEngine();
  43837. var baseSize = this._spriteTexture.getBaseSize();
  43838. // Sprites
  43839. var deltaTime = engine.getDeltaTime();
  43840. var max = Math.min(this._capacity, this.sprites.length);
  43841. var rowSize = baseSize.width / this.cellWidth;
  43842. var offset = 0;
  43843. for (var index = 0; index < max; index++) {
  43844. var sprite = this.sprites[index];
  43845. if (!sprite) {
  43846. continue;
  43847. }
  43848. sprite._animate(deltaTime);
  43849. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43850. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43851. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43852. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43853. }
  43854. this._buffer.update(this._vertexData);
  43855. // Render
  43856. var effect = this._effectBase;
  43857. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43858. effect = this._effectFog;
  43859. }
  43860. engine.enableEffect(effect);
  43861. var viewMatrix = this._scene.getViewMatrix();
  43862. effect.setTexture("diffuseSampler", this._spriteTexture);
  43863. effect.setMatrix("view", viewMatrix);
  43864. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43865. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43866. // Fog
  43867. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43868. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43869. effect.setColor3("vFogColor", this._scene.fogColor);
  43870. }
  43871. // VBOs
  43872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43873. // Draw order
  43874. engine.setDepthFunctionToLessOrEqual();
  43875. effect.setBool("alphaTest", true);
  43876. engine.setColorWrite(false);
  43877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  43878. engine.setColorWrite(true);
  43879. effect.setBool("alphaTest", false);
  43880. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  43882. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43883. };
  43884. SpriteManager.prototype.dispose = function () {
  43885. if (this._buffer) {
  43886. this._buffer.dispose();
  43887. this._buffer = null;
  43888. }
  43889. if (this._indexBuffer) {
  43890. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43891. this._indexBuffer = null;
  43892. }
  43893. if (this._spriteTexture) {
  43894. this._spriteTexture.dispose();
  43895. this._spriteTexture = null;
  43896. }
  43897. // Remove from scene
  43898. var index = this._scene.spriteManagers.indexOf(this);
  43899. this._scene.spriteManagers.splice(index, 1);
  43900. // Callback
  43901. this.onDisposeObservable.notifyObservers(this);
  43902. this.onDisposeObservable.clear();
  43903. };
  43904. return SpriteManager;
  43905. }());
  43906. BABYLON.SpriteManager = SpriteManager;
  43907. })(BABYLON || (BABYLON = {}));
  43908. //# sourceMappingURL=babylon.spriteManager.js.map
  43909. var BABYLON;
  43910. (function (BABYLON) {
  43911. var Sprite = /** @class */ (function () {
  43912. function Sprite(name, manager) {
  43913. this.name = name;
  43914. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43915. this.width = 1.0;
  43916. this.height = 1.0;
  43917. this.angle = 0;
  43918. this.cellIndex = 0;
  43919. this.invertU = 0;
  43920. this.invertV = 0;
  43921. this.animations = new Array();
  43922. this.isPickable = false;
  43923. this._animationStarted = false;
  43924. this._loopAnimation = false;
  43925. this._fromIndex = 0;
  43926. this._toIndex = 0;
  43927. this._delay = 0;
  43928. this._direction = 1;
  43929. this._time = 0;
  43930. this._manager = manager;
  43931. this._manager.sprites.push(this);
  43932. this.position = BABYLON.Vector3.Zero();
  43933. }
  43934. Object.defineProperty(Sprite.prototype, "size", {
  43935. get: function () {
  43936. return this.width;
  43937. },
  43938. set: function (value) {
  43939. this.width = value;
  43940. this.height = value;
  43941. },
  43942. enumerable: true,
  43943. configurable: true
  43944. });
  43945. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43946. this._fromIndex = from;
  43947. this._toIndex = to;
  43948. this._loopAnimation = loop;
  43949. this._delay = delay;
  43950. this._animationStarted = true;
  43951. this._direction = from < to ? 1 : -1;
  43952. this.cellIndex = from;
  43953. this._time = 0;
  43954. this._onAnimationEnd = onAnimationEnd;
  43955. };
  43956. Sprite.prototype.stopAnimation = function () {
  43957. this._animationStarted = false;
  43958. };
  43959. Sprite.prototype._animate = function (deltaTime) {
  43960. if (!this._animationStarted)
  43961. return;
  43962. this._time += deltaTime;
  43963. if (this._time > this._delay) {
  43964. this._time = this._time % this._delay;
  43965. this.cellIndex += this._direction;
  43966. if (this.cellIndex > this._toIndex) {
  43967. if (this._loopAnimation) {
  43968. this.cellIndex = this._fromIndex;
  43969. }
  43970. else {
  43971. this.cellIndex = this._toIndex;
  43972. this._animationStarted = false;
  43973. if (this._onAnimationEnd) {
  43974. this._onAnimationEnd();
  43975. }
  43976. if (this.disposeWhenFinishedAnimating) {
  43977. this.dispose();
  43978. }
  43979. }
  43980. }
  43981. }
  43982. };
  43983. Sprite.prototype.dispose = function () {
  43984. for (var i = 0; i < this._manager.sprites.length; i++) {
  43985. if (this._manager.sprites[i] == this) {
  43986. this._manager.sprites.splice(i, 1);
  43987. }
  43988. }
  43989. };
  43990. return Sprite;
  43991. }());
  43992. BABYLON.Sprite = Sprite;
  43993. })(BABYLON || (BABYLON = {}));
  43994. //# sourceMappingURL=babylon.sprite.js.map
  43995. var BABYLON;
  43996. (function (BABYLON) {
  43997. var IntersectionInfo = /** @class */ (function () {
  43998. function IntersectionInfo(bu, bv, distance) {
  43999. this.bu = bu;
  44000. this.bv = bv;
  44001. this.distance = distance;
  44002. this.faceId = 0;
  44003. this.subMeshId = 0;
  44004. }
  44005. return IntersectionInfo;
  44006. }());
  44007. BABYLON.IntersectionInfo = IntersectionInfo;
  44008. var PickingInfo = /** @class */ (function () {
  44009. function PickingInfo() {
  44010. this.hit = false;
  44011. this.distance = 0;
  44012. this.pickedPoint = null;
  44013. this.pickedMesh = null;
  44014. this.bu = 0;
  44015. this.bv = 0;
  44016. this.faceId = -1;
  44017. this.subMeshId = 0;
  44018. this.pickedSprite = null;
  44019. }
  44020. // Methods
  44021. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44022. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44023. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44024. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44025. return null;
  44026. }
  44027. var indices = this.pickedMesh.getIndices();
  44028. if (!indices) {
  44029. return null;
  44030. }
  44031. var result;
  44032. if (useVerticesNormals) {
  44033. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44034. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44035. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44036. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44037. normal0 = normal0.scale(this.bu);
  44038. normal1 = normal1.scale(this.bv);
  44039. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44040. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44041. }
  44042. else {
  44043. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44044. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44045. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44046. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44047. var p1p2 = vertex1.subtract(vertex2);
  44048. var p3p2 = vertex3.subtract(vertex2);
  44049. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44050. }
  44051. if (useWorldCoordinates) {
  44052. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44053. }
  44054. return BABYLON.Vector3.Normalize(result);
  44055. };
  44056. PickingInfo.prototype.getTextureCoordinates = function () {
  44057. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44058. return null;
  44059. }
  44060. var indices = this.pickedMesh.getIndices();
  44061. if (!indices) {
  44062. return null;
  44063. }
  44064. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44065. if (!uvs) {
  44066. return null;
  44067. }
  44068. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44069. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44070. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44071. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44072. uv1 = uv1.scale(this.bu);
  44073. uv2 = uv2.scale(this.bv);
  44074. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44075. };
  44076. return PickingInfo;
  44077. }());
  44078. BABYLON.PickingInfo = PickingInfo;
  44079. })(BABYLON || (BABYLON = {}));
  44080. //# sourceMappingURL=babylon.pickingInfo.js.map
  44081. var BABYLON;
  44082. (function (BABYLON) {
  44083. var Ray = /** @class */ (function () {
  44084. function Ray(origin, direction, length) {
  44085. if (length === void 0) { length = Number.MAX_VALUE; }
  44086. this.origin = origin;
  44087. this.direction = direction;
  44088. this.length = length;
  44089. }
  44090. // Methods
  44091. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44092. var d = 0.0;
  44093. var maxValue = Number.MAX_VALUE;
  44094. var inv;
  44095. var min;
  44096. var max;
  44097. var temp;
  44098. if (Math.abs(this.direction.x) < 0.0000001) {
  44099. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44100. return false;
  44101. }
  44102. }
  44103. else {
  44104. inv = 1.0 / this.direction.x;
  44105. min = (minimum.x - this.origin.x) * inv;
  44106. max = (maximum.x - this.origin.x) * inv;
  44107. if (max === -Infinity) {
  44108. max = Infinity;
  44109. }
  44110. if (min > max) {
  44111. temp = min;
  44112. min = max;
  44113. max = temp;
  44114. }
  44115. d = Math.max(min, d);
  44116. maxValue = Math.min(max, maxValue);
  44117. if (d > maxValue) {
  44118. return false;
  44119. }
  44120. }
  44121. if (Math.abs(this.direction.y) < 0.0000001) {
  44122. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44123. return false;
  44124. }
  44125. }
  44126. else {
  44127. inv = 1.0 / this.direction.y;
  44128. min = (minimum.y - this.origin.y) * inv;
  44129. max = (maximum.y - this.origin.y) * inv;
  44130. if (max === -Infinity) {
  44131. max = Infinity;
  44132. }
  44133. if (min > max) {
  44134. temp = min;
  44135. min = max;
  44136. max = temp;
  44137. }
  44138. d = Math.max(min, d);
  44139. maxValue = Math.min(max, maxValue);
  44140. if (d > maxValue) {
  44141. return false;
  44142. }
  44143. }
  44144. if (Math.abs(this.direction.z) < 0.0000001) {
  44145. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44146. return false;
  44147. }
  44148. }
  44149. else {
  44150. inv = 1.0 / this.direction.z;
  44151. min = (minimum.z - this.origin.z) * inv;
  44152. max = (maximum.z - this.origin.z) * inv;
  44153. if (max === -Infinity) {
  44154. max = Infinity;
  44155. }
  44156. if (min > max) {
  44157. temp = min;
  44158. min = max;
  44159. max = temp;
  44160. }
  44161. d = Math.max(min, d);
  44162. maxValue = Math.min(max, maxValue);
  44163. if (d > maxValue) {
  44164. return false;
  44165. }
  44166. }
  44167. return true;
  44168. };
  44169. Ray.prototype.intersectsBox = function (box) {
  44170. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44171. };
  44172. Ray.prototype.intersectsSphere = function (sphere) {
  44173. var x = sphere.center.x - this.origin.x;
  44174. var y = sphere.center.y - this.origin.y;
  44175. var z = sphere.center.z - this.origin.z;
  44176. var pyth = (x * x) + (y * y) + (z * z);
  44177. var rr = sphere.radius * sphere.radius;
  44178. if (pyth <= rr) {
  44179. return true;
  44180. }
  44181. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44182. if (dot < 0.0) {
  44183. return false;
  44184. }
  44185. var temp = pyth - (dot * dot);
  44186. return temp <= rr;
  44187. };
  44188. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44189. if (!this._edge1) {
  44190. this._edge1 = BABYLON.Vector3.Zero();
  44191. this._edge2 = BABYLON.Vector3.Zero();
  44192. this._pvec = BABYLON.Vector3.Zero();
  44193. this._tvec = BABYLON.Vector3.Zero();
  44194. this._qvec = BABYLON.Vector3.Zero();
  44195. }
  44196. vertex1.subtractToRef(vertex0, this._edge1);
  44197. vertex2.subtractToRef(vertex0, this._edge2);
  44198. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44199. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44200. if (det === 0) {
  44201. return null;
  44202. }
  44203. var invdet = 1 / det;
  44204. this.origin.subtractToRef(vertex0, this._tvec);
  44205. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44206. if (bu < 0 || bu > 1.0) {
  44207. return null;
  44208. }
  44209. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44210. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44211. if (bv < 0 || bu + bv > 1.0) {
  44212. return null;
  44213. }
  44214. //check if the distance is longer than the predefined length.
  44215. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44216. if (distance > this.length) {
  44217. return null;
  44218. }
  44219. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44220. };
  44221. Ray.prototype.intersectsPlane = function (plane) {
  44222. var distance;
  44223. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44224. if (Math.abs(result1) < 9.99999997475243E-07) {
  44225. return null;
  44226. }
  44227. else {
  44228. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44229. distance = (-plane.d - result2) / result1;
  44230. if (distance < 0.0) {
  44231. if (distance < -9.99999997475243E-07) {
  44232. return null;
  44233. }
  44234. else {
  44235. return 0;
  44236. }
  44237. }
  44238. return distance;
  44239. }
  44240. };
  44241. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44242. var tm = BABYLON.Tmp.Matrix[0];
  44243. mesh.getWorldMatrix().invertToRef(tm);
  44244. if (this._tmpRay) {
  44245. Ray.TransformToRef(this, tm, this._tmpRay);
  44246. }
  44247. else {
  44248. this._tmpRay = Ray.Transform(this, tm);
  44249. }
  44250. return mesh.intersects(this._tmpRay, fastCheck);
  44251. };
  44252. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44253. if (results) {
  44254. results.length = 0;
  44255. }
  44256. else {
  44257. results = [];
  44258. }
  44259. for (var i = 0; i < meshes.length; i++) {
  44260. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44261. if (pickInfo.hit) {
  44262. results.push(pickInfo);
  44263. }
  44264. }
  44265. results.sort(this._comparePickingInfo);
  44266. return results;
  44267. };
  44268. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44269. if (pickingInfoA.distance < pickingInfoB.distance) {
  44270. return -1;
  44271. }
  44272. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44273. return 1;
  44274. }
  44275. else {
  44276. return 0;
  44277. }
  44278. };
  44279. /**
  44280. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44281. * @param sega the first point of the segment to test the intersection against
  44282. * @param segb the second point of the segment to test the intersection against
  44283. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44284. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44285. */
  44286. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44287. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44288. var u = segb.subtract(sega);
  44289. var v = rsegb.subtract(this.origin);
  44290. var w = sega.subtract(this.origin);
  44291. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44292. var b = BABYLON.Vector3.Dot(u, v);
  44293. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44294. var d = BABYLON.Vector3.Dot(u, w);
  44295. var e = BABYLON.Vector3.Dot(v, w);
  44296. var D = a * c - b * b; // always >= 0
  44297. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44298. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44299. // compute the line parameters of the two closest points
  44300. if (D < Ray.smallnum) {
  44301. sN = 0.0; // force using point P0 on segment S1
  44302. sD = 1.0; // to prevent possible division by 0.0 later
  44303. tN = e;
  44304. tD = c;
  44305. }
  44306. else {
  44307. sN = (b * e - c * d);
  44308. tN = (a * e - b * d);
  44309. if (sN < 0.0) {
  44310. sN = 0.0;
  44311. tN = e;
  44312. tD = c;
  44313. }
  44314. else if (sN > sD) {
  44315. sN = sD;
  44316. tN = e + b;
  44317. tD = c;
  44318. }
  44319. }
  44320. if (tN < 0.0) {
  44321. tN = 0.0;
  44322. // recompute sc for this edge
  44323. if (-d < 0.0) {
  44324. sN = 0.0;
  44325. }
  44326. else if (-d > a)
  44327. sN = sD;
  44328. else {
  44329. sN = -d;
  44330. sD = a;
  44331. }
  44332. }
  44333. else if (tN > tD) {
  44334. tN = tD;
  44335. // recompute sc for this edge
  44336. if ((-d + b) < 0.0) {
  44337. sN = 0;
  44338. }
  44339. else if ((-d + b) > a) {
  44340. sN = sD;
  44341. }
  44342. else {
  44343. sN = (-d + b);
  44344. sD = a;
  44345. }
  44346. }
  44347. // finally do the division to get sc and tc
  44348. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44349. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44350. // get the difference of the two closest points
  44351. var qtc = v.multiplyByFloats(tc, tc, tc);
  44352. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44353. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44354. if (isIntersected) {
  44355. return qtc.length();
  44356. }
  44357. return -1;
  44358. };
  44359. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44360. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44361. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44362. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44363. this.direction.normalize();
  44364. return this;
  44365. };
  44366. // Statics
  44367. Ray.Zero = function () {
  44368. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44369. };
  44370. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44371. var result = Ray.Zero();
  44372. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44373. };
  44374. /**
  44375. * 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
  44376. * transformed to the given world matrix.
  44377. * @param origin The origin point
  44378. * @param end The end point
  44379. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44380. */
  44381. Ray.CreateNewFromTo = function (origin, end, world) {
  44382. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44383. var direction = end.subtract(origin);
  44384. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44385. direction.normalize();
  44386. return Ray.Transform(new Ray(origin, direction, length), world);
  44387. };
  44388. Ray.Transform = function (ray, matrix) {
  44389. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44390. Ray.TransformToRef(ray, matrix, result);
  44391. return result;
  44392. };
  44393. Ray.TransformToRef = function (ray, matrix, result) {
  44394. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44395. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44396. result.length = ray.length;
  44397. var dir = result.direction;
  44398. var len = dir.length();
  44399. if (!(len === 0 || len === 1)) {
  44400. var num = 1.0 / len;
  44401. dir.x *= num;
  44402. dir.y *= num;
  44403. dir.z *= num;
  44404. result.length *= len;
  44405. }
  44406. };
  44407. Ray.smallnum = 0.00000001;
  44408. Ray.rayl = 10e8;
  44409. return Ray;
  44410. }());
  44411. BABYLON.Ray = Ray;
  44412. })(BABYLON || (BABYLON = {}));
  44413. //# sourceMappingURL=babylon.ray.js.map
  44414. var BABYLON;
  44415. (function (BABYLON) {
  44416. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44417. if (boxMin.x > sphereCenter.x + sphereRadius)
  44418. return false;
  44419. if (sphereCenter.x - sphereRadius > boxMax.x)
  44420. return false;
  44421. if (boxMin.y > sphereCenter.y + sphereRadius)
  44422. return false;
  44423. if (sphereCenter.y - sphereRadius > boxMax.y)
  44424. return false;
  44425. if (boxMin.z > sphereCenter.z + sphereRadius)
  44426. return false;
  44427. if (sphereCenter.z - sphereRadius > boxMax.z)
  44428. return false;
  44429. return true;
  44430. };
  44431. var getLowestRoot = (function () {
  44432. var result = { root: 0, found: false };
  44433. return function (a, b, c, maxR) {
  44434. result.root = 0;
  44435. result.found = false;
  44436. var determinant = b * b - 4.0 * a * c;
  44437. if (determinant < 0)
  44438. return result;
  44439. var sqrtD = Math.sqrt(determinant);
  44440. var r1 = (-b - sqrtD) / (2.0 * a);
  44441. var r2 = (-b + sqrtD) / (2.0 * a);
  44442. if (r1 > r2) {
  44443. var temp = r2;
  44444. r2 = r1;
  44445. r1 = temp;
  44446. }
  44447. if (r1 > 0 && r1 < maxR) {
  44448. result.root = r1;
  44449. result.found = true;
  44450. return result;
  44451. }
  44452. if (r2 > 0 && r2 < maxR) {
  44453. result.root = r2;
  44454. result.found = true;
  44455. return result;
  44456. }
  44457. return result;
  44458. };
  44459. })();
  44460. var Collider = /** @class */ (function () {
  44461. function Collider() {
  44462. this._collisionPoint = BABYLON.Vector3.Zero();
  44463. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44464. this._tempVector = BABYLON.Vector3.Zero();
  44465. this._tempVector2 = BABYLON.Vector3.Zero();
  44466. this._tempVector3 = BABYLON.Vector3.Zero();
  44467. this._tempVector4 = BABYLON.Vector3.Zero();
  44468. this._edge = BABYLON.Vector3.Zero();
  44469. this._baseToVertex = BABYLON.Vector3.Zero();
  44470. this._destinationPoint = BABYLON.Vector3.Zero();
  44471. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44472. this._displacementVector = BABYLON.Vector3.Zero();
  44473. this._radius = BABYLON.Vector3.One();
  44474. this._retry = 0;
  44475. this._basePointWorld = BABYLON.Vector3.Zero();
  44476. this._velocityWorld = BABYLON.Vector3.Zero();
  44477. this._normalizedVelocity = BABYLON.Vector3.Zero();
  44478. this._collisionMask = -1;
  44479. }
  44480. Object.defineProperty(Collider.prototype, "collisionMask", {
  44481. get: function () {
  44482. return this._collisionMask;
  44483. },
  44484. set: function (mask) {
  44485. this._collisionMask = !isNaN(mask) ? mask : -1;
  44486. },
  44487. enumerable: true,
  44488. configurable: true
  44489. });
  44490. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  44491. /**
  44492. * Gets the plane normal used to compute the sliding response (in local space)
  44493. */
  44494. get: function () {
  44495. return this._slidePlaneNormal;
  44496. },
  44497. enumerable: true,
  44498. configurable: true
  44499. });
  44500. // Methods
  44501. Collider.prototype._initialize = function (source, dir, e) {
  44502. this._velocity = dir;
  44503. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  44504. this._basePoint = source;
  44505. source.multiplyToRef(this._radius, this._basePointWorld);
  44506. dir.multiplyToRef(this._radius, this._velocityWorld);
  44507. this._velocityWorldLength = this._velocityWorld.length();
  44508. this._epsilon = e;
  44509. this.collisionFound = false;
  44510. };
  44511. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44512. pa.subtractToRef(point, this._tempVector);
  44513. pb.subtractToRef(point, this._tempVector2);
  44514. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44515. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44516. if (d < 0)
  44517. return false;
  44518. pc.subtractToRef(point, this._tempVector3);
  44519. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44520. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44521. if (d < 0)
  44522. return false;
  44523. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44524. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44525. return d >= 0;
  44526. };
  44527. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44528. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  44529. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  44530. if (distance > this._velocityWorldLength + max + sphereRadius) {
  44531. return false;
  44532. }
  44533. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  44534. return false;
  44535. return true;
  44536. };
  44537. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44538. var t0;
  44539. var embeddedInPlane = false;
  44540. //defensive programming, actually not needed.
  44541. if (!trianglePlaneArray) {
  44542. trianglePlaneArray = [];
  44543. }
  44544. if (!trianglePlaneArray[faceIndex]) {
  44545. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44546. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44547. }
  44548. var trianglePlane = trianglePlaneArray[faceIndex];
  44549. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  44550. return;
  44551. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  44552. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  44553. if (normalDotVelocity == 0) {
  44554. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44555. return;
  44556. embeddedInPlane = true;
  44557. t0 = 0;
  44558. }
  44559. else {
  44560. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44561. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44562. if (t0 > t1) {
  44563. var temp = t1;
  44564. t1 = t0;
  44565. t0 = temp;
  44566. }
  44567. if (t0 > 1.0 || t1 < 0.0)
  44568. return;
  44569. if (t0 < 0)
  44570. t0 = 0;
  44571. if (t0 > 1.0)
  44572. t0 = 1.0;
  44573. }
  44574. this._collisionPoint.copyFromFloats(0, 0, 0);
  44575. var found = false;
  44576. var t = 1.0;
  44577. if (!embeddedInPlane) {
  44578. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44579. this._velocity.scaleToRef(t0, this._tempVector);
  44580. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44581. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44582. found = true;
  44583. t = t0;
  44584. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44585. }
  44586. }
  44587. if (!found) {
  44588. var velocitySquaredLength = this._velocity.lengthSquared();
  44589. var a = velocitySquaredLength;
  44590. this._basePoint.subtractToRef(p1, this._tempVector);
  44591. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44592. var c = this._tempVector.lengthSquared() - 1.0;
  44593. var lowestRoot = getLowestRoot(a, b, c, t);
  44594. if (lowestRoot.found) {
  44595. t = lowestRoot.root;
  44596. found = true;
  44597. this._collisionPoint.copyFrom(p1);
  44598. }
  44599. this._basePoint.subtractToRef(p2, this._tempVector);
  44600. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44601. c = this._tempVector.lengthSquared() - 1.0;
  44602. lowestRoot = getLowestRoot(a, b, c, t);
  44603. if (lowestRoot.found) {
  44604. t = lowestRoot.root;
  44605. found = true;
  44606. this._collisionPoint.copyFrom(p2);
  44607. }
  44608. this._basePoint.subtractToRef(p3, this._tempVector);
  44609. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44610. c = this._tempVector.lengthSquared() - 1.0;
  44611. lowestRoot = getLowestRoot(a, b, c, t);
  44612. if (lowestRoot.found) {
  44613. t = lowestRoot.root;
  44614. found = true;
  44615. this._collisionPoint.copyFrom(p3);
  44616. }
  44617. p2.subtractToRef(p1, this._edge);
  44618. p1.subtractToRef(this._basePoint, this._baseToVertex);
  44619. var edgeSquaredLength = this._edge.lengthSquared();
  44620. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44621. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44622. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44623. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44624. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44625. lowestRoot = getLowestRoot(a, b, c, t);
  44626. if (lowestRoot.found) {
  44627. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44628. if (f >= 0.0 && f <= 1.0) {
  44629. t = lowestRoot.root;
  44630. found = true;
  44631. this._edge.scaleInPlace(f);
  44632. p1.addToRef(this._edge, this._collisionPoint);
  44633. }
  44634. }
  44635. p3.subtractToRef(p2, this._edge);
  44636. p2.subtractToRef(this._basePoint, this._baseToVertex);
  44637. edgeSquaredLength = this._edge.lengthSquared();
  44638. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44639. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44640. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44641. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44642. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44643. lowestRoot = getLowestRoot(a, b, c, t);
  44644. if (lowestRoot.found) {
  44645. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44646. if (f >= 0.0 && f <= 1.0) {
  44647. t = lowestRoot.root;
  44648. found = true;
  44649. this._edge.scaleInPlace(f);
  44650. p2.addToRef(this._edge, this._collisionPoint);
  44651. }
  44652. }
  44653. p1.subtractToRef(p3, this._edge);
  44654. p3.subtractToRef(this._basePoint, this._baseToVertex);
  44655. edgeSquaredLength = this._edge.lengthSquared();
  44656. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44657. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44658. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44659. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44660. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44661. lowestRoot = getLowestRoot(a, b, c, t);
  44662. if (lowestRoot.found) {
  44663. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44664. if (f >= 0.0 && f <= 1.0) {
  44665. t = lowestRoot.root;
  44666. found = true;
  44667. this._edge.scaleInPlace(f);
  44668. p3.addToRef(this._edge, this._collisionPoint);
  44669. }
  44670. }
  44671. }
  44672. if (found) {
  44673. var distToCollision = t * this._velocity.length();
  44674. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  44675. if (!this.intersectionPoint) {
  44676. this.intersectionPoint = this._collisionPoint.clone();
  44677. }
  44678. else {
  44679. this.intersectionPoint.copyFrom(this._collisionPoint);
  44680. }
  44681. this._nearestDistance = distToCollision;
  44682. this.collisionFound = true;
  44683. }
  44684. }
  44685. };
  44686. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44687. for (var i = indexStart; i < indexEnd; i += 3) {
  44688. var p1 = pts[indices[i] - decal];
  44689. var p2 = pts[indices[i + 1] - decal];
  44690. var p3 = pts[indices[i + 2] - decal];
  44691. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44692. }
  44693. };
  44694. Collider.prototype._getResponse = function (pos, vel) {
  44695. pos.addToRef(vel, this._destinationPoint);
  44696. vel.scaleInPlace((this._nearestDistance / vel.length()));
  44697. this._basePoint.addToRef(vel, pos);
  44698. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44699. this._slidePlaneNormal.normalize();
  44700. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  44701. pos.addInPlace(this._displacementVector);
  44702. this.intersectionPoint.addInPlace(this._displacementVector);
  44703. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44704. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44705. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44706. };
  44707. return Collider;
  44708. }());
  44709. BABYLON.Collider = Collider;
  44710. })(BABYLON || (BABYLON = {}));
  44711. //# sourceMappingURL=babylon.collider.js.map
  44712. var BABYLON;
  44713. (function (BABYLON) {
  44714. //WebWorker code will be inserted to this variable.
  44715. BABYLON.CollisionWorker = "";
  44716. var WorkerTaskType;
  44717. (function (WorkerTaskType) {
  44718. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44719. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44720. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44721. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44722. var WorkerReplyType;
  44723. (function (WorkerReplyType) {
  44724. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44725. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44726. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44727. var CollisionCoordinatorWorker = /** @class */ (function () {
  44728. function CollisionCoordinatorWorker() {
  44729. var _this = this;
  44730. this._scaledPosition = BABYLON.Vector3.Zero();
  44731. this._scaledVelocity = BABYLON.Vector3.Zero();
  44732. this.onMeshUpdated = function (transformNode) {
  44733. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44734. };
  44735. this.onGeometryUpdated = function (geometry) {
  44736. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44737. };
  44738. this._afterRender = function () {
  44739. if (!_this._init)
  44740. return;
  44741. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44742. return;
  44743. }
  44744. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44745. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44746. if (_this._runningUpdated > 4) {
  44747. return;
  44748. }
  44749. ++_this._runningUpdated;
  44750. var payload = {
  44751. updatedMeshes: _this._addUpdateMeshesList,
  44752. updatedGeometries: _this._addUpdateGeometriesList,
  44753. removedGeometries: _this._toRemoveGeometryArray,
  44754. removedMeshes: _this._toRemoveMeshesArray
  44755. };
  44756. var message = {
  44757. payload: payload,
  44758. taskType: WorkerTaskType.UPDATE
  44759. };
  44760. var serializable = [];
  44761. for (var id in payload.updatedGeometries) {
  44762. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44763. //prepare transferables
  44764. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44765. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44766. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44767. }
  44768. }
  44769. _this._worker.postMessage(message, serializable);
  44770. _this._addUpdateMeshesList = {};
  44771. _this._addUpdateGeometriesList = {};
  44772. _this._toRemoveGeometryArray = [];
  44773. _this._toRemoveMeshesArray = [];
  44774. };
  44775. this._onMessageFromWorker = function (e) {
  44776. var returnData = e.data;
  44777. if (returnData.error != WorkerReplyType.SUCCESS) {
  44778. //TODO what errors can be returned from the worker?
  44779. BABYLON.Tools.Warn("error returned from worker!");
  44780. return;
  44781. }
  44782. switch (returnData.taskType) {
  44783. case WorkerTaskType.INIT:
  44784. _this._init = true;
  44785. //Update the worked with ALL of the scene's current state
  44786. _this._scene.meshes.forEach(function (mesh) {
  44787. _this.onMeshAdded(mesh);
  44788. });
  44789. _this._scene.getGeometries().forEach(function (geometry) {
  44790. _this.onGeometryAdded(geometry);
  44791. });
  44792. break;
  44793. case WorkerTaskType.UPDATE:
  44794. _this._runningUpdated--;
  44795. break;
  44796. case WorkerTaskType.COLLIDE:
  44797. var returnPayload = returnData.payload;
  44798. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44799. return;
  44800. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44801. if (callback) {
  44802. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44803. if (mesh) {
  44804. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44805. }
  44806. }
  44807. //cleanup
  44808. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44809. break;
  44810. }
  44811. };
  44812. this._collisionsCallbackArray = [];
  44813. this._init = false;
  44814. this._runningUpdated = 0;
  44815. this._addUpdateMeshesList = {};
  44816. this._addUpdateGeometriesList = {};
  44817. this._toRemoveGeometryArray = [];
  44818. this._toRemoveMeshesArray = [];
  44819. }
  44820. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44821. if (!this._init)
  44822. return;
  44823. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44824. return;
  44825. position.divideToRef(collider._radius, this._scaledPosition);
  44826. displacement.divideToRef(collider._radius, this._scaledVelocity);
  44827. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44828. var payload = {
  44829. collider: {
  44830. position: this._scaledPosition.asArray(),
  44831. velocity: this._scaledVelocity.asArray(),
  44832. radius: collider._radius.asArray()
  44833. },
  44834. collisionId: collisionIndex,
  44835. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44836. maximumRetry: maximumRetry
  44837. };
  44838. var message = {
  44839. payload: payload,
  44840. taskType: WorkerTaskType.COLLIDE
  44841. };
  44842. this._worker.postMessage(message);
  44843. };
  44844. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44845. this._scene = scene;
  44846. this._scene.registerAfterRender(this._afterRender);
  44847. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44848. this._worker = new Worker(workerUrl);
  44849. this._worker.onmessage = this._onMessageFromWorker;
  44850. var message = {
  44851. payload: {},
  44852. taskType: WorkerTaskType.INIT
  44853. };
  44854. this._worker.postMessage(message);
  44855. };
  44856. CollisionCoordinatorWorker.prototype.destroy = function () {
  44857. this._scene.unregisterAfterRender(this._afterRender);
  44858. this._worker.terminate();
  44859. };
  44860. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44861. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44862. this.onMeshUpdated(mesh);
  44863. };
  44864. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44865. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44866. };
  44867. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44868. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44869. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44870. this.onGeometryUpdated(geometry);
  44871. };
  44872. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44873. this._toRemoveGeometryArray.push(geometry.id);
  44874. };
  44875. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44876. var submeshes = [];
  44877. if (mesh.subMeshes) {
  44878. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44879. var boundingInfo = sm.getBoundingInfo();
  44880. return {
  44881. position: idx,
  44882. verticesStart: sm.verticesStart,
  44883. verticesCount: sm.verticesCount,
  44884. indexStart: sm.indexStart,
  44885. indexCount: sm.indexCount,
  44886. hasMaterial: !!sm.getMaterial(),
  44887. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44888. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44889. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44890. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44891. };
  44892. });
  44893. }
  44894. var geometryId = null;
  44895. if (mesh instanceof BABYLON.Mesh) {
  44896. var geometry = mesh.geometry;
  44897. geometryId = geometry ? geometry.id : null;
  44898. }
  44899. else if (mesh instanceof BABYLON.InstancedMesh) {
  44900. var geometry = mesh.sourceMesh.geometry;
  44901. geometryId = geometry ? geometry.id : null;
  44902. }
  44903. var boundingInfo = mesh.getBoundingInfo();
  44904. return {
  44905. uniqueId: mesh.uniqueId,
  44906. id: mesh.id,
  44907. name: mesh.name,
  44908. geometryId: geometryId,
  44909. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44910. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44911. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44912. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44913. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44914. subMeshes: submeshes,
  44915. checkCollisions: mesh.checkCollisions
  44916. };
  44917. };
  44918. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44919. return {
  44920. id: geometry.id,
  44921. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44922. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44923. indices: new Uint32Array(geometry.getIndices() || []),
  44924. };
  44925. };
  44926. return CollisionCoordinatorWorker;
  44927. }());
  44928. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44929. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44930. function CollisionCoordinatorLegacy() {
  44931. this._scaledPosition = BABYLON.Vector3.Zero();
  44932. this._scaledVelocity = BABYLON.Vector3.Zero();
  44933. this._finalPosition = BABYLON.Vector3.Zero();
  44934. }
  44935. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44936. position.divideToRef(collider._radius, this._scaledPosition);
  44937. displacement.divideToRef(collider._radius, this._scaledVelocity);
  44938. collider.collidedMesh = null;
  44939. collider._retry = 0;
  44940. collider._initialVelocity = this._scaledVelocity;
  44941. collider._initialPosition = this._scaledPosition;
  44942. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44943. this._finalPosition.multiplyInPlace(collider._radius);
  44944. //run the callback
  44945. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44946. };
  44947. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44948. this._scene = scene;
  44949. };
  44950. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44951. //Legacy need no destruction method.
  44952. };
  44953. //No update in legacy mode
  44954. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44955. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44956. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44957. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44958. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44959. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44960. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44961. if (excludedMesh === void 0) { excludedMesh = null; }
  44962. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44963. if (collider._retry >= maximumRetry) {
  44964. finalPosition.copyFrom(position);
  44965. return;
  44966. }
  44967. // Check if this is a mesh else camera or -1
  44968. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44969. collider._initialize(position, velocity, closeDistance);
  44970. // Check all meshes
  44971. for (var index = 0; index < this._scene.meshes.length; index++) {
  44972. var mesh = this._scene.meshes[index];
  44973. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44974. mesh._checkCollision(collider);
  44975. }
  44976. }
  44977. if (!collider.collisionFound) {
  44978. position.addToRef(velocity, finalPosition);
  44979. return;
  44980. }
  44981. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44982. collider._getResponse(position, velocity);
  44983. }
  44984. if (velocity.length() <= closeDistance) {
  44985. finalPosition.copyFrom(position);
  44986. return;
  44987. }
  44988. collider._retry++;
  44989. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44990. };
  44991. return CollisionCoordinatorLegacy;
  44992. }());
  44993. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44994. })(BABYLON || (BABYLON = {}));
  44995. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44996. var BABYLON;
  44997. (function (BABYLON) {
  44998. var Particle = /** @class */ (function () {
  44999. function Particle(particleSystem) {
  45000. this.particleSystem = particleSystem;
  45001. this.position = BABYLON.Vector3.Zero();
  45002. this.direction = BABYLON.Vector3.Zero();
  45003. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45004. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45005. this.lifeTime = 1.0;
  45006. this.age = 0;
  45007. this.size = 0;
  45008. this.angle = 0;
  45009. this.angularSpeed = 0;
  45010. this._currentFrameCounter = 0;
  45011. this.cellIndex = 0;
  45012. if (!this.particleSystem.isAnimationSheetEnabled) {
  45013. return;
  45014. }
  45015. this.cellIndex = this.particleSystem.startSpriteCellID;
  45016. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45017. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45018. }
  45019. else {
  45020. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45021. }
  45022. }
  45023. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45024. // (ageOffset / scaledUpdateSpeed) / available cells
  45025. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45026. this._currentFrameCounter += scaledUpdateSpeed;
  45027. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45028. this._currentFrameCounter = 0;
  45029. this.cellIndex++;
  45030. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45031. this.cellIndex = this.particleSystem.endSpriteCellID;
  45032. }
  45033. }
  45034. };
  45035. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45036. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45037. this.cellIndex++;
  45038. this._currentFrameCounter = 0;
  45039. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45040. if (this.particleSystem.spriteCellLoop) {
  45041. this.cellIndex = this.particleSystem.startSpriteCellID;
  45042. }
  45043. else {
  45044. this.cellIndex = this.particleSystem.endSpriteCellID;
  45045. }
  45046. }
  45047. }
  45048. else {
  45049. this._currentFrameCounter++;
  45050. }
  45051. };
  45052. Particle.prototype.copyTo = function (other) {
  45053. other.position.copyFrom(this.position);
  45054. other.direction.copyFrom(this.direction);
  45055. other.color.copyFrom(this.color);
  45056. other.colorStep.copyFrom(this.colorStep);
  45057. other.lifeTime = this.lifeTime;
  45058. other.age = this.age;
  45059. other.size = this.size;
  45060. other.angle = this.angle;
  45061. other.angularSpeed = this.angularSpeed;
  45062. other.particleSystem = this.particleSystem;
  45063. other.cellIndex = this.cellIndex;
  45064. };
  45065. return Particle;
  45066. }());
  45067. BABYLON.Particle = Particle;
  45068. })(BABYLON || (BABYLON = {}));
  45069. //# sourceMappingURL=babylon.particle.js.map
  45070. var BABYLON;
  45071. (function (BABYLON) {
  45072. var randomNumber = function (min, max) {
  45073. if (min === max) {
  45074. return (min);
  45075. }
  45076. var random = Math.random();
  45077. return ((random * (max - min)) + min);
  45078. };
  45079. var ParticleSystem = /** @class */ (function () {
  45080. // end of sheet animation
  45081. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45082. if (customEffect === void 0) { customEffect = null; }
  45083. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45084. if (epsilon === void 0) { epsilon = 0.01; }
  45085. var _this = this;
  45086. this.name = name;
  45087. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45088. // Members
  45089. this.animations = [];
  45090. this.renderingGroupId = 0;
  45091. this.emitter = null;
  45092. this.emitRate = 10;
  45093. this.manualEmitCount = -1;
  45094. this.updateSpeed = 0.01;
  45095. this.targetStopDuration = 0;
  45096. this.disposeOnStop = false;
  45097. this.minEmitPower = 1;
  45098. this.maxEmitPower = 1;
  45099. this.minLifeTime = 1;
  45100. this.maxLifeTime = 1;
  45101. this.minSize = 1;
  45102. this.maxSize = 1;
  45103. this.minAngularSpeed = 0;
  45104. this.maxAngularSpeed = 0;
  45105. this.layerMask = 0x0FFFFFFF;
  45106. this.customShader = null;
  45107. this.preventAutoStart = false;
  45108. /**
  45109. * An event triggered when the system is disposed.
  45110. * @type {BABYLON.Observable}
  45111. */
  45112. this.onDisposeObservable = new BABYLON.Observable();
  45113. this.onAnimationEnd = null;
  45114. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45115. this.forceDepthWrite = false;
  45116. this.gravity = BABYLON.Vector3.Zero();
  45117. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45118. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45119. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45120. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45121. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45122. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45123. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45124. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45125. this.particles = new Array();
  45126. this._stockParticles = new Array();
  45127. this._newPartsExcess = 0;
  45128. this._vertexBuffers = {};
  45129. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45130. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45131. this._scaledDirection = BABYLON.Vector3.Zero();
  45132. this._scaledGravity = BABYLON.Vector3.Zero();
  45133. this._currentRenderId = -1;
  45134. this._started = false;
  45135. this._stopped = false;
  45136. this._actualFrame = 0;
  45137. // sheet animation
  45138. this.startSpriteCellID = 0;
  45139. this.endSpriteCellID = 0;
  45140. this.spriteCellLoop = true;
  45141. this.spriteCellChangeSpeed = 0;
  45142. this.spriteCellWidth = 0;
  45143. this.spriteCellHeight = 0;
  45144. this._vertexBufferSize = 11;
  45145. this.appendParticleVertexes = null;
  45146. this.id = name;
  45147. this._capacity = capacity;
  45148. this._epsilon = epsilon;
  45149. if (_isAnimationSheetEnabled) {
  45150. this._vertexBufferSize = 12;
  45151. }
  45152. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45153. this._customEffect = customEffect;
  45154. scene.particleSystems.push(this);
  45155. this._createIndexBuffer();
  45156. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45157. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45158. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45159. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45160. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45161. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45162. if (this._isAnimationSheetEnabled) {
  45163. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45164. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45165. }
  45166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45167. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45168. this._vertexBuffers["options"] = options;
  45169. // Default behaviors
  45170. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  45171. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  45172. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  45173. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  45174. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  45175. };
  45176. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  45177. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  45178. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  45179. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  45180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  45181. };
  45182. this.updateFunction = function (particles) {
  45183. for (var index = 0; index < particles.length; index++) {
  45184. var particle = particles[index];
  45185. particle.age += _this._scaledUpdateSpeed;
  45186. if (particle.age >= particle.lifeTime) {
  45187. _this.recycleParticle(particle);
  45188. index--;
  45189. continue;
  45190. }
  45191. else {
  45192. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45193. particle.color.addInPlace(_this._scaledColorStep);
  45194. if (particle.color.a < 0)
  45195. particle.color.a = 0;
  45196. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45197. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45198. particle.position.addInPlace(_this._scaledDirection);
  45199. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45200. particle.direction.addInPlace(_this._scaledGravity);
  45201. if (_this._isAnimationSheetEnabled) {
  45202. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45203. }
  45204. }
  45205. }
  45206. };
  45207. }
  45208. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45209. set: function (callback) {
  45210. if (this._onDisposeObserver) {
  45211. this.onDisposeObservable.remove(this._onDisposeObserver);
  45212. }
  45213. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45219. get: function () {
  45220. return this._isAnimationSheetEnabled;
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. ParticleSystem.prototype._createIndexBuffer = function () {
  45226. var indices = [];
  45227. var index = 0;
  45228. for (var count = 0; count < this._capacity; count++) {
  45229. indices.push(index);
  45230. indices.push(index + 1);
  45231. indices.push(index + 2);
  45232. indices.push(index);
  45233. indices.push(index + 2);
  45234. indices.push(index + 3);
  45235. index += 4;
  45236. }
  45237. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45238. };
  45239. ParticleSystem.prototype.recycleParticle = function (particle) {
  45240. var lastParticle = this.particles.pop();
  45241. if (lastParticle !== particle) {
  45242. lastParticle.copyTo(particle);
  45243. this._stockParticles.push(lastParticle);
  45244. }
  45245. };
  45246. ParticleSystem.prototype.getCapacity = function () {
  45247. return this._capacity;
  45248. };
  45249. ParticleSystem.prototype.isAlive = function () {
  45250. return this._alive;
  45251. };
  45252. ParticleSystem.prototype.isStarted = function () {
  45253. return this._started;
  45254. };
  45255. ParticleSystem.prototype.start = function () {
  45256. this._started = true;
  45257. this._stopped = false;
  45258. this._actualFrame = 0;
  45259. };
  45260. ParticleSystem.prototype.stop = function () {
  45261. this._stopped = true;
  45262. };
  45263. // animation sheet
  45264. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45265. var offset = index * this._vertexBufferSize;
  45266. this._vertexData[offset] = particle.position.x;
  45267. this._vertexData[offset + 1] = particle.position.y;
  45268. this._vertexData[offset + 2] = particle.position.z;
  45269. this._vertexData[offset + 3] = particle.color.r;
  45270. this._vertexData[offset + 4] = particle.color.g;
  45271. this._vertexData[offset + 5] = particle.color.b;
  45272. this._vertexData[offset + 6] = particle.color.a;
  45273. this._vertexData[offset + 7] = particle.angle;
  45274. this._vertexData[offset + 8] = particle.size;
  45275. this._vertexData[offset + 9] = offsetX;
  45276. this._vertexData[offset + 10] = offsetY;
  45277. };
  45278. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45279. if (offsetX === 0)
  45280. offsetX = this._epsilon;
  45281. else if (offsetX === 1)
  45282. offsetX = 1 - this._epsilon;
  45283. if (offsetY === 0)
  45284. offsetY = this._epsilon;
  45285. else if (offsetY === 1)
  45286. offsetY = 1 - this._epsilon;
  45287. var offset = index * this._vertexBufferSize;
  45288. this._vertexData[offset] = particle.position.x;
  45289. this._vertexData[offset + 1] = particle.position.y;
  45290. this._vertexData[offset + 2] = particle.position.z;
  45291. this._vertexData[offset + 3] = particle.color.r;
  45292. this._vertexData[offset + 4] = particle.color.g;
  45293. this._vertexData[offset + 5] = particle.color.b;
  45294. this._vertexData[offset + 6] = particle.color.a;
  45295. this._vertexData[offset + 7] = particle.angle;
  45296. this._vertexData[offset + 8] = particle.size;
  45297. this._vertexData[offset + 9] = offsetX;
  45298. this._vertexData[offset + 10] = offsetY;
  45299. this._vertexData[offset + 11] = particle.cellIndex;
  45300. };
  45301. ParticleSystem.prototype._update = function (newParticles) {
  45302. // Update current
  45303. this._alive = this.particles.length > 0;
  45304. this.updateFunction(this.particles);
  45305. // Add new ones
  45306. var worldMatrix;
  45307. if (this.emitter.position) {
  45308. var emitterMesh = this.emitter;
  45309. worldMatrix = emitterMesh.getWorldMatrix();
  45310. }
  45311. else {
  45312. var emitterPosition = this.emitter;
  45313. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45314. }
  45315. var particle;
  45316. for (var index = 0; index < newParticles; index++) {
  45317. if (this.particles.length === this._capacity) {
  45318. break;
  45319. }
  45320. if (this._stockParticles.length !== 0) {
  45321. particle = this._stockParticles.pop();
  45322. particle.age = 0;
  45323. particle.cellIndex = this.startSpriteCellID;
  45324. }
  45325. else {
  45326. particle = new BABYLON.Particle(this);
  45327. }
  45328. this.particles.push(particle);
  45329. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45330. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45331. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45332. particle.size = randomNumber(this.minSize, this.maxSize);
  45333. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45334. this.startPositionFunction(worldMatrix, particle.position, particle);
  45335. var step = randomNumber(0, 1.0);
  45336. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45337. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45338. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45339. }
  45340. };
  45341. ParticleSystem.prototype._getEffect = function () {
  45342. if (this._customEffect) {
  45343. return this._customEffect;
  45344. }
  45345. ;
  45346. var defines = [];
  45347. if (this._scene.clipPlane) {
  45348. defines.push("#define CLIPPLANE");
  45349. }
  45350. if (this._isAnimationSheetEnabled) {
  45351. defines.push("#define ANIMATESHEET");
  45352. }
  45353. // Effect
  45354. var join = defines.join("\n");
  45355. if (this._cachedDefines !== join) {
  45356. this._cachedDefines = join;
  45357. var attributesNamesOrOptions;
  45358. var effectCreationOption;
  45359. if (this._isAnimationSheetEnabled) {
  45360. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45361. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45362. }
  45363. else {
  45364. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45365. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45366. }
  45367. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45368. }
  45369. return this._effect;
  45370. };
  45371. ParticleSystem.prototype.animate = function () {
  45372. if (!this._started)
  45373. return;
  45374. var effect = this._getEffect();
  45375. // Check
  45376. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45377. return;
  45378. if (this._currentRenderId === this._scene.getRenderId()) {
  45379. return;
  45380. }
  45381. this._currentRenderId = this._scene.getRenderId();
  45382. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45383. // determine the number of particles we need to create
  45384. var newParticles;
  45385. if (this.manualEmitCount > -1) {
  45386. newParticles = this.manualEmitCount;
  45387. this._newPartsExcess = 0;
  45388. this.manualEmitCount = 0;
  45389. }
  45390. else {
  45391. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45392. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45393. }
  45394. if (this._newPartsExcess > 1.0) {
  45395. newParticles += this._newPartsExcess >> 0;
  45396. this._newPartsExcess -= this._newPartsExcess >> 0;
  45397. }
  45398. this._alive = false;
  45399. if (!this._stopped) {
  45400. this._actualFrame += this._scaledUpdateSpeed;
  45401. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45402. this.stop();
  45403. }
  45404. else {
  45405. newParticles = 0;
  45406. }
  45407. this._update(newParticles);
  45408. // Stopped?
  45409. if (this._stopped) {
  45410. if (!this._alive) {
  45411. this._started = false;
  45412. if (this.onAnimationEnd) {
  45413. this.onAnimationEnd();
  45414. }
  45415. if (this.disposeOnStop) {
  45416. this._scene._toBeDisposed.push(this);
  45417. }
  45418. }
  45419. }
  45420. // Animation sheet
  45421. if (this._isAnimationSheetEnabled) {
  45422. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45423. }
  45424. else {
  45425. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45426. }
  45427. // Update VBO
  45428. var offset = 0;
  45429. for (var index = 0; index < this.particles.length; index++) {
  45430. var particle = this.particles[index];
  45431. this.appendParticleVertexes(offset, particle);
  45432. offset += 4;
  45433. }
  45434. if (this._vertexBuffer) {
  45435. this._vertexBuffer.update(this._vertexData);
  45436. }
  45437. };
  45438. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45439. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45440. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45441. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45442. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45443. };
  45444. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45445. this._appendParticleVertex(offset++, particle, 0, 0);
  45446. this._appendParticleVertex(offset++, particle, 1, 0);
  45447. this._appendParticleVertex(offset++, particle, 1, 1);
  45448. this._appendParticleVertex(offset++, particle, 0, 1);
  45449. };
  45450. ParticleSystem.prototype.rebuild = function () {
  45451. this._createIndexBuffer();
  45452. if (this._vertexBuffer) {
  45453. this._vertexBuffer._rebuild();
  45454. }
  45455. };
  45456. ParticleSystem.prototype.render = function () {
  45457. var effect = this._getEffect();
  45458. // Check
  45459. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45460. return 0;
  45461. var engine = this._scene.getEngine();
  45462. // Render
  45463. engine.enableEffect(effect);
  45464. engine.setState(false);
  45465. var viewMatrix = this._scene.getViewMatrix();
  45466. effect.setTexture("diffuseSampler", this.particleTexture);
  45467. effect.setMatrix("view", viewMatrix);
  45468. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45469. if (this._isAnimationSheetEnabled) {
  45470. var baseSize = this.particleTexture.getBaseSize();
  45471. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45472. }
  45473. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45474. if (this._scene.clipPlane) {
  45475. var clipPlane = this._scene.clipPlane;
  45476. var invView = viewMatrix.clone();
  45477. invView.invert();
  45478. effect.setMatrix("invView", invView);
  45479. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45480. }
  45481. // VBOs
  45482. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45483. // Draw order
  45484. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45485. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45486. }
  45487. else {
  45488. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45489. }
  45490. if (this.forceDepthWrite) {
  45491. engine.setDepthWrite(true);
  45492. }
  45493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  45494. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45495. return this.particles.length;
  45496. };
  45497. ParticleSystem.prototype.dispose = function () {
  45498. if (this._vertexBuffer) {
  45499. this._vertexBuffer.dispose();
  45500. this._vertexBuffer = null;
  45501. }
  45502. if (this._indexBuffer) {
  45503. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45504. this._indexBuffer = null;
  45505. }
  45506. if (this.particleTexture) {
  45507. this.particleTexture.dispose();
  45508. this.particleTexture = null;
  45509. }
  45510. // Remove from scene
  45511. var index = this._scene.particleSystems.indexOf(this);
  45512. if (index > -1) {
  45513. this._scene.particleSystems.splice(index, 1);
  45514. }
  45515. // Callback
  45516. this.onDisposeObservable.notifyObservers(this);
  45517. this.onDisposeObservable.clear();
  45518. };
  45519. // Clone
  45520. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45521. var custom = null;
  45522. var program = null;
  45523. if (this.customShader != null) {
  45524. program = this.customShader;
  45525. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45526. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45527. }
  45528. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45529. result.customShader = program;
  45530. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45531. if (newEmitter === undefined) {
  45532. newEmitter = this.emitter;
  45533. }
  45534. result.emitter = newEmitter;
  45535. if (this.particleTexture) {
  45536. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45537. }
  45538. if (!this.preventAutoStart) {
  45539. result.start();
  45540. }
  45541. return result;
  45542. };
  45543. ParticleSystem.prototype.serialize = function () {
  45544. var serializationObject = {};
  45545. serializationObject.name = this.name;
  45546. serializationObject.id = this.id;
  45547. // Emitter
  45548. if (this.emitter.position) {
  45549. var emitterMesh = this.emitter;
  45550. serializationObject.emitterId = emitterMesh.id;
  45551. }
  45552. else {
  45553. var emitterPosition = this.emitter;
  45554. serializationObject.emitter = emitterPosition.asArray();
  45555. }
  45556. serializationObject.capacity = this.getCapacity();
  45557. if (this.particleTexture) {
  45558. serializationObject.textureName = this.particleTexture.name;
  45559. }
  45560. // Animations
  45561. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45562. // Particle system
  45563. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45564. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45565. serializationObject.minSize = this.minSize;
  45566. serializationObject.maxSize = this.maxSize;
  45567. serializationObject.minEmitPower = this.minEmitPower;
  45568. serializationObject.maxEmitPower = this.maxEmitPower;
  45569. serializationObject.minLifeTime = this.minLifeTime;
  45570. serializationObject.maxLifeTime = this.maxLifeTime;
  45571. serializationObject.emitRate = this.emitRate;
  45572. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45573. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45574. serializationObject.gravity = this.gravity.asArray();
  45575. serializationObject.direction1 = this.direction1.asArray();
  45576. serializationObject.direction2 = this.direction2.asArray();
  45577. serializationObject.color1 = this.color1.asArray();
  45578. serializationObject.color2 = this.color2.asArray();
  45579. serializationObject.colorDead = this.colorDead.asArray();
  45580. serializationObject.updateSpeed = this.updateSpeed;
  45581. serializationObject.targetStopDuration = this.targetStopDuration;
  45582. serializationObject.textureMask = this.textureMask.asArray();
  45583. serializationObject.blendMode = this.blendMode;
  45584. serializationObject.customShader = this.customShader;
  45585. serializationObject.preventAutoStart = this.preventAutoStart;
  45586. serializationObject.startSpriteCellID = this.startSpriteCellID;
  45587. serializationObject.endSpriteCellID = this.endSpriteCellID;
  45588. serializationObject.spriteCellLoop = this.spriteCellLoop;
  45589. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  45590. serializationObject.spriteCellWidth = this.spriteCellWidth;
  45591. serializationObject.spriteCellHeight = this.spriteCellHeight;
  45592. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  45593. return serializationObject;
  45594. };
  45595. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45596. var name = parsedParticleSystem.name;
  45597. var custom = null;
  45598. var program = null;
  45599. if (parsedParticleSystem.customShader) {
  45600. program = parsedParticleSystem.customShader;
  45601. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45602. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45603. }
  45604. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  45605. particleSystem.customShader = program;
  45606. if (parsedParticleSystem.id) {
  45607. particleSystem.id = parsedParticleSystem.id;
  45608. }
  45609. // Auto start
  45610. if (parsedParticleSystem.preventAutoStart) {
  45611. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45612. }
  45613. // Texture
  45614. if (parsedParticleSystem.textureName) {
  45615. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45616. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45617. }
  45618. // Emitter
  45619. if (parsedParticleSystem.emitterId) {
  45620. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45621. }
  45622. else {
  45623. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45624. }
  45625. // Animations
  45626. if (parsedParticleSystem.animations) {
  45627. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45628. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45629. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45630. }
  45631. }
  45632. if (parsedParticleSystem.autoAnimate) {
  45633. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45634. }
  45635. // Particle system
  45636. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45637. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45638. particleSystem.minSize = parsedParticleSystem.minSize;
  45639. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45640. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45641. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45642. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45643. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45644. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45645. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45646. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45647. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45648. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45649. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45650. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45651. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45652. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45653. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45654. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45655. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45656. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45657. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  45658. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  45659. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  45660. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  45661. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  45662. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  45663. if (!particleSystem.preventAutoStart) {
  45664. particleSystem.start();
  45665. }
  45666. return particleSystem;
  45667. };
  45668. // Statics
  45669. ParticleSystem.BLENDMODE_ONEONE = 0;
  45670. ParticleSystem.BLENDMODE_STANDARD = 1;
  45671. return ParticleSystem;
  45672. }());
  45673. BABYLON.ParticleSystem = ParticleSystem;
  45674. })(BABYLON || (BABYLON = {}));
  45675. //# sourceMappingURL=babylon.particleSystem.js.map
  45676. var BABYLON;
  45677. (function (BABYLON) {
  45678. var GPUParticleSystem = /** @class */ (function () {
  45679. function GPUParticleSystem(name, capacity, scene) {
  45680. this.name = name;
  45681. this.emitter = null;
  45682. this.renderingGroupId = 0;
  45683. this.layerMask = 0x0FFFFFFF; // TODO
  45684. this._updateVertexBuffers = {};
  45685. this._renderVertexBuffers = {};
  45686. this._currentRenderId = -1;
  45687. this._started = true;
  45688. /**
  45689. * An event triggered when the system is disposed.
  45690. * @type {BABYLON.Observable}
  45691. */
  45692. this.onDisposeObservable = new BABYLON.Observable();
  45693. this.id = name;
  45694. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45695. this._capacity = capacity;
  45696. this._engine = this._scene.getEngine();
  45697. this._scene.particleSystems.push(this);
  45698. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  45699. var updateEffectOptions = {
  45700. attributes: ["position", "age", "life", "velocity"],
  45701. uniformsNames: [],
  45702. uniformBuffersNames: [],
  45703. samplers: [],
  45704. defines: "",
  45705. fallbacks: null,
  45706. onCompiled: null,
  45707. onError: null,
  45708. indexParameters: null,
  45709. maxSimultaneousLights: 0,
  45710. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  45711. };
  45712. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  45713. }
  45714. GPUParticleSystem.prototype.isStarted = function () {
  45715. return this._started;
  45716. };
  45717. GPUParticleSystem.prototype.start = function () {
  45718. this._started = true;
  45719. };
  45720. GPUParticleSystem.prototype.stop = function () {
  45721. this._started = false;
  45722. };
  45723. GPUParticleSystem.prototype.animate = function () {
  45724. // Do nothing
  45725. };
  45726. GPUParticleSystem.prototype._initialize = function () {
  45727. if (this._renderVAO) {
  45728. return;
  45729. }
  45730. var data = new Array();
  45731. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  45732. // position
  45733. data.push(0.0);
  45734. data.push(0.0);
  45735. data.push(0.0);
  45736. var life = 1 + Math.random() * 10; // TODO: var
  45737. data.push(life + 1); // create the particle as a dead one to create a new one at start
  45738. data.push(life);
  45739. // velocity
  45740. data.push(0.0);
  45741. data.push(0.0);
  45742. data.push(0.0);
  45743. }
  45744. // Update VAO
  45745. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45746. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  45747. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  45748. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  45749. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45750. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  45751. this._engine.bindArrayBuffer(null);
  45752. // Render VAO
  45753. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45754. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  45755. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  45756. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  45757. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45758. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  45759. this._engine.bindArrayBuffer(null);
  45760. // Links
  45761. this._sourceVAO = this._updateVAO;
  45762. this._targetVAO = this._renderVAO;
  45763. this._sourceBuffer = this._updateBuffer;
  45764. this._targetBuffer = this._renderBuffer;
  45765. };
  45766. GPUParticleSystem.prototype.render = function () {
  45767. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  45768. return 0;
  45769. }
  45770. // Get everything ready to render
  45771. this._initialize();
  45772. if (this._currentRenderId === this._scene.getRenderId()) {
  45773. return 0;
  45774. }
  45775. this._currentRenderId = this._scene.getRenderId();
  45776. // Enable update effect
  45777. this._engine.enableEffect(this._updateEffect);
  45778. this._engine.setState(false);
  45779. // Bind source VAO
  45780. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  45781. // Update
  45782. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  45783. this._engine.setRasterizerState(false);
  45784. this._engine.beginTransformFeedback();
  45785. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  45786. this._engine.endTransformFeedback();
  45787. this._engine.setRasterizerState(true);
  45788. this._engine.bindTransformFeedbackBuffer(null);
  45789. // Enable render effect
  45790. this._engine.enableEffect(this._renderEffect);
  45791. // Bind source VAO
  45792. this._engine.bindVertexArrayObject(this._targetVAO, null);
  45793. // Render
  45794. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  45795. // Switch VAOs
  45796. var tmpVAO = this._sourceVAO;
  45797. this._sourceVAO = this._targetVAO;
  45798. this._targetVAO = tmpVAO;
  45799. // Switch buffers
  45800. var tmpBuffer = this._sourceBuffer;
  45801. this._sourceBuffer = this._targetBuffer;
  45802. this._targetBuffer = tmpBuffer;
  45803. return 0;
  45804. };
  45805. GPUParticleSystem.prototype.rebuild = function () {
  45806. };
  45807. GPUParticleSystem.prototype.dispose = function () {
  45808. var index = this._scene.particleSystems.indexOf(this);
  45809. if (index > -1) {
  45810. this._scene.particleSystems.splice(index, 1);
  45811. }
  45812. //TODO: this._dataBuffer.dispose();
  45813. // Callback
  45814. this.onDisposeObservable.notifyObservers(this);
  45815. this.onDisposeObservable.clear();
  45816. };
  45817. //TODO: Clone / Parse / serialize
  45818. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  45819. return null;
  45820. };
  45821. GPUParticleSystem.prototype.serialize = function () {
  45822. };
  45823. return GPUParticleSystem;
  45824. }());
  45825. BABYLON.GPUParticleSystem = GPUParticleSystem;
  45826. })(BABYLON || (BABYLON = {}));
  45827. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  45828. var BABYLON;
  45829. (function (BABYLON) {
  45830. var SolidParticle = /** @class */ (function () {
  45831. /**
  45832. * Creates a Solid Particle object.
  45833. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45834. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45835. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45836. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45837. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45838. * `shapeId` (integer) is the model shape identifier in the SPS.
  45839. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45840. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45841. */
  45842. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45843. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45844. this.idx = 0; // particle global index
  45845. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45846. this.position = BABYLON.Vector3.Zero(); // position
  45847. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45848. this.scaling = BABYLON.Vector3.One(); // scaling
  45849. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45850. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45851. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45852. this.alive = true; // alive
  45853. this.isVisible = true; // visibility
  45854. this._pos = 0; // index of this particle in the global "positions" array
  45855. this._ind = 0; // index of this particle in the global "indices" array
  45856. this.shapeId = 0; // model shape id
  45857. this.idxInShape = 0; // index of the particle in its shape id
  45858. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45859. this.idx = particleIndex;
  45860. this._pos = positionIndex;
  45861. this._ind = indiceIndex;
  45862. this._model = model;
  45863. this.shapeId = shapeId;
  45864. this.idxInShape = idxInShape;
  45865. this._sps = sps;
  45866. if (modelBoundingInfo) {
  45867. this._modelBoundingInfo = modelBoundingInfo;
  45868. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45869. }
  45870. }
  45871. Object.defineProperty(SolidParticle.prototype, "scale", {
  45872. /**
  45873. * legacy support, changed scale to scaling
  45874. */
  45875. get: function () {
  45876. return this.scaling;
  45877. },
  45878. set: function (scale) {
  45879. this.scaling = scale;
  45880. },
  45881. enumerable: true,
  45882. configurable: true
  45883. });
  45884. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45885. /**
  45886. * legacy support, changed quaternion to rotationQuaternion
  45887. */
  45888. get: function () {
  45889. return this.rotationQuaternion;
  45890. },
  45891. set: function (q) {
  45892. this.rotationQuaternion = q;
  45893. },
  45894. enumerable: true,
  45895. configurable: true
  45896. });
  45897. /**
  45898. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45899. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45900. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45901. */
  45902. SolidParticle.prototype.intersectsMesh = function (target) {
  45903. if (!this._boundingInfo || !target._boundingInfo) {
  45904. return false;
  45905. }
  45906. if (this._sps._bSphereOnly) {
  45907. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45908. }
  45909. return this._boundingInfo.intersects(target._boundingInfo, false);
  45910. };
  45911. return SolidParticle;
  45912. }());
  45913. BABYLON.SolidParticle = SolidParticle;
  45914. var ModelShape = /** @class */ (function () {
  45915. /**
  45916. * 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.
  45917. * SPS internal tool, don't use it manually.
  45918. */
  45919. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45920. this._indicesLength = 0; // length of the shape in the model indices array
  45921. this.shapeID = id;
  45922. this._shape = shape;
  45923. this._indicesLength = indicesLength;
  45924. this._shapeUV = shapeUV;
  45925. this._positionFunction = posFunction;
  45926. this._vertexFunction = vtxFunction;
  45927. }
  45928. return ModelShape;
  45929. }());
  45930. BABYLON.ModelShape = ModelShape;
  45931. var DepthSortedParticle = /** @class */ (function () {
  45932. function DepthSortedParticle() {
  45933. this.ind = 0; // index of the particle in the "indices" array
  45934. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45935. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45936. }
  45937. return DepthSortedParticle;
  45938. }());
  45939. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45940. })(BABYLON || (BABYLON = {}));
  45941. //# sourceMappingURL=babylon.solidParticle.js.map
  45942. var BABYLON;
  45943. (function (BABYLON) {
  45944. /**
  45945. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45946. */
  45947. var SolidParticleSystem = /** @class */ (function () {
  45948. /**
  45949. * Creates a SPS (Solid Particle System) object.
  45950. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45951. * `scene` (Scene) is the scene in which the SPS is added.
  45952. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45953. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45954. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45955. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45956. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45957. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45958. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45959. */
  45960. function SolidParticleSystem(name, scene, options) {
  45961. // public members
  45962. /**
  45963. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45964. * Example : var p = SPS.particles[i];
  45965. */
  45966. this.particles = new Array();
  45967. /**
  45968. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45969. */
  45970. this.nbParticles = 0;
  45971. /**
  45972. * If the particles must ever face the camera (default false). Useful for planar particles.
  45973. */
  45974. this.billboard = false;
  45975. /**
  45976. * Recompute normals when adding a shape
  45977. */
  45978. this.recomputeNormals = true;
  45979. /**
  45980. * This a counter ofr your own usage. It's not set by any SPS functions.
  45981. */
  45982. this.counter = 0;
  45983. /**
  45984. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45985. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45986. */
  45987. this.vars = {};
  45988. this._positions = new Array();
  45989. this._indices = new Array();
  45990. this._normals = new Array();
  45991. this._colors = new Array();
  45992. this._uvs = new Array();
  45993. this._index = 0; // indices index
  45994. this._updatable = true;
  45995. this._pickable = false;
  45996. this._isVisibilityBoxLocked = false;
  45997. this._alwaysVisible = false;
  45998. this._depthSort = false;
  45999. this._shapeCounter = 0;
  46000. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46001. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46002. this._computeParticleColor = true;
  46003. this._computeParticleTexture = true;
  46004. this._computeParticleRotation = true;
  46005. this._computeParticleVertex = false;
  46006. this._computeBoundingBox = false;
  46007. this._depthSortParticles = true;
  46008. this._cam_axisZ = BABYLON.Vector3.Zero();
  46009. this._cam_axisY = BABYLON.Vector3.Zero();
  46010. this._cam_axisX = BABYLON.Vector3.Zero();
  46011. this._axisZ = BABYLON.Axis.Z;
  46012. this._camDir = BABYLON.Vector3.Zero();
  46013. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46014. this._rotMatrix = new BABYLON.Matrix();
  46015. this._invertMatrix = new BABYLON.Matrix();
  46016. this._rotated = BABYLON.Vector3.Zero();
  46017. this._quaternion = new BABYLON.Quaternion();
  46018. this._vertex = BABYLON.Vector3.Zero();
  46019. this._normal = BABYLON.Vector3.Zero();
  46020. this._yaw = 0.0;
  46021. this._pitch = 0.0;
  46022. this._roll = 0.0;
  46023. this._halfroll = 0.0;
  46024. this._halfpitch = 0.0;
  46025. this._halfyaw = 0.0;
  46026. this._sinRoll = 0.0;
  46027. this._cosRoll = 0.0;
  46028. this._sinPitch = 0.0;
  46029. this._cosPitch = 0.0;
  46030. this._sinYaw = 0.0;
  46031. this._cosYaw = 0.0;
  46032. this._mustUnrotateFixedNormals = false;
  46033. this._minimum = BABYLON.Tmp.Vector3[0];
  46034. this._maximum = BABYLON.Tmp.Vector3[1];
  46035. this._minBbox = BABYLON.Tmp.Vector3[4];
  46036. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46037. this._particlesIntersect = false;
  46038. this._depthSortFunction = function (p1, p2) {
  46039. return (p2.sqDistance - p1.sqDistance);
  46040. };
  46041. this._needs32Bits = false;
  46042. this._bSphereOnly = false;
  46043. this._bSphereRadiusFactor = 1.0;
  46044. this.name = name;
  46045. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46046. this._camera = scene.activeCamera;
  46047. this._pickable = options ? options.isPickable : false;
  46048. this._depthSort = options ? options.enableDepthSort : false;
  46049. this._particlesIntersect = options ? options.particleIntersection : false;
  46050. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46051. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46052. if (options && options.updatable) {
  46053. this._updatable = options.updatable;
  46054. }
  46055. else {
  46056. this._updatable = true;
  46057. }
  46058. if (this._pickable) {
  46059. this.pickedParticles = [];
  46060. }
  46061. if (this._depthSort) {
  46062. this.depthSortedParticles = [];
  46063. }
  46064. }
  46065. /**
  46066. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46067. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46068. */
  46069. SolidParticleSystem.prototype.buildMesh = function () {
  46070. if (this.nbParticles === 0) {
  46071. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46072. this.addShape(triangle, 1);
  46073. triangle.dispose();
  46074. }
  46075. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  46076. this._positions32 = new Float32Array(this._positions);
  46077. this._uvs32 = new Float32Array(this._uvs);
  46078. this._colors32 = new Float32Array(this._colors);
  46079. if (this.recomputeNormals) {
  46080. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46081. }
  46082. this._normals32 = new Float32Array(this._normals);
  46083. this._fixedNormal32 = new Float32Array(this._normals);
  46084. if (this._mustUnrotateFixedNormals) {
  46085. this._unrotateFixedNormals();
  46086. }
  46087. var vertexData = new BABYLON.VertexData();
  46088. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  46089. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46090. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46091. if (this._uvs32) {
  46092. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46093. ;
  46094. }
  46095. if (this._colors32) {
  46096. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46097. }
  46098. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46099. vertexData.applyToMesh(mesh, this._updatable);
  46100. this.mesh = mesh;
  46101. this.mesh.isPickable = this._pickable;
  46102. // free memory
  46103. if (!this._depthSort) {
  46104. this._indices = null;
  46105. }
  46106. this._positions = null;
  46107. this._normals = null;
  46108. this._uvs = null;
  46109. this._colors = null;
  46110. if (!this._updatable) {
  46111. this.particles.length = 0;
  46112. }
  46113. return mesh;
  46114. };
  46115. /**
  46116. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  46117. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  46118. * Thus the particles generated from `digest()` have their property `position` set yet.
  46119. * `mesh` ( Mesh ) is the mesh to be digested
  46120. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  46121. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  46122. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  46123. */
  46124. SolidParticleSystem.prototype.digest = function (mesh, options) {
  46125. var size = (options && options.facetNb) || 1;
  46126. var number = (options && options.number) || 0;
  46127. var delta = (options && options.delta) || 0;
  46128. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46129. var meshInd = mesh.getIndices();
  46130. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46131. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46132. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46133. var f = 0; // facet counter
  46134. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  46135. // compute size from number
  46136. if (number) {
  46137. number = (number > totalFacets) ? totalFacets : number;
  46138. size = Math.round(totalFacets / number);
  46139. delta = 0;
  46140. }
  46141. else {
  46142. size = (size > totalFacets) ? totalFacets : size;
  46143. }
  46144. var facetPos = []; // submesh positions
  46145. var facetInd = []; // submesh indices
  46146. var facetUV = []; // submesh UV
  46147. var facetCol = []; // submesh colors
  46148. var barycenter = BABYLON.Tmp.Vector3[0];
  46149. var sizeO = size;
  46150. while (f < totalFacets) {
  46151. size = sizeO + Math.floor((1 + delta) * Math.random());
  46152. if (f > totalFacets - size) {
  46153. size = totalFacets - f;
  46154. }
  46155. // reset temp arrays
  46156. facetPos.length = 0;
  46157. facetInd.length = 0;
  46158. facetUV.length = 0;
  46159. facetCol.length = 0;
  46160. // iterate over "size" facets
  46161. var fi = 0;
  46162. for (var j = f * 3; j < (f + size) * 3; j++) {
  46163. facetInd.push(fi);
  46164. var i = meshInd[j];
  46165. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  46166. if (meshUV) {
  46167. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  46168. }
  46169. if (meshCol) {
  46170. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  46171. }
  46172. fi++;
  46173. }
  46174. // create a model shape for each single particle
  46175. var idx = this.nbParticles;
  46176. var shape = this._posToShape(facetPos);
  46177. var shapeUV = this._uvsToShapeUV(facetUV);
  46178. // compute the barycenter of the shape
  46179. var v;
  46180. for (v = 0; v < shape.length; v++) {
  46181. barycenter.addInPlace(shape[v]);
  46182. }
  46183. barycenter.scaleInPlace(1 / shape.length);
  46184. // shift the shape from its barycenter to the origin
  46185. for (v = 0; v < shape.length; v++) {
  46186. shape[v].subtractInPlace(barycenter);
  46187. }
  46188. var bInfo;
  46189. if (this._particlesIntersect) {
  46190. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  46191. }
  46192. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  46193. // add the particle in the SPS
  46194. var currentPos = this._positions.length;
  46195. var currentInd = this._indices.length;
  46196. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  46197. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  46198. // initialize the particle position
  46199. this.particles[this.nbParticles].position.addInPlace(barycenter);
  46200. this._index += shape.length;
  46201. idx++;
  46202. this.nbParticles++;
  46203. this._shapeCounter++;
  46204. f += size;
  46205. }
  46206. return this;
  46207. };
  46208. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  46209. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  46210. var index = 0;
  46211. var idx = 0;
  46212. for (var p = 0; p < this.particles.length; p++) {
  46213. this._particle = this.particles[p];
  46214. this._shape = this._particle._model._shape;
  46215. if (this._particle.rotationQuaternion) {
  46216. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46217. }
  46218. else {
  46219. this._yaw = this._particle.rotation.y;
  46220. this._pitch = this._particle.rotation.x;
  46221. this._roll = this._particle.rotation.z;
  46222. this._quaternionRotationYPR();
  46223. }
  46224. this._quaternionToRotationMatrix();
  46225. this._rotMatrix.invertToRef(this._invertMatrix);
  46226. for (var pt = 0; pt < this._shape.length; pt++) {
  46227. idx = index + pt * 3;
  46228. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  46229. this._fixedNormal32[idx] = this._normal.x;
  46230. this._fixedNormal32[idx + 1] = this._normal.y;
  46231. this._fixedNormal32[idx + 2] = this._normal.z;
  46232. }
  46233. index = idx + 3;
  46234. }
  46235. };
  46236. //reset copy
  46237. SolidParticleSystem.prototype._resetCopy = function () {
  46238. this._copy.position.x = 0;
  46239. this._copy.position.y = 0;
  46240. this._copy.position.z = 0;
  46241. this._copy.rotation.x = 0;
  46242. this._copy.rotation.y = 0;
  46243. this._copy.rotation.z = 0;
  46244. this._copy.rotationQuaternion = null;
  46245. this._copy.scaling.x = 1.0;
  46246. this._copy.scaling.y = 1.0;
  46247. this._copy.scaling.z = 1.0;
  46248. this._copy.uvs.x = 0;
  46249. this._copy.uvs.y = 0;
  46250. this._copy.uvs.z = 1.0;
  46251. this._copy.uvs.w = 1.0;
  46252. this._copy.color = null;
  46253. };
  46254. // _meshBuilder : inserts the shape model in the global SPS mesh
  46255. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  46256. var i;
  46257. var u = 0;
  46258. var c = 0;
  46259. var n = 0;
  46260. this._resetCopy();
  46261. if (options && options.positionFunction) {
  46262. options.positionFunction(this._copy, idx, idxInShape);
  46263. this._mustUnrotateFixedNormals = true;
  46264. }
  46265. if (this._copy.rotationQuaternion) {
  46266. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46267. }
  46268. else {
  46269. this._yaw = this._copy.rotation.y;
  46270. this._pitch = this._copy.rotation.x;
  46271. this._roll = this._copy.rotation.z;
  46272. this._quaternionRotationYPR();
  46273. }
  46274. this._quaternionToRotationMatrix();
  46275. for (i = 0; i < shape.length; i++) {
  46276. this._vertex.x = shape[i].x;
  46277. this._vertex.y = shape[i].y;
  46278. this._vertex.z = shape[i].z;
  46279. if (options && options.vertexFunction) {
  46280. options.vertexFunction(this._copy, this._vertex, i);
  46281. }
  46282. this._vertex.x *= this._copy.scaling.x;
  46283. this._vertex.y *= this._copy.scaling.y;
  46284. this._vertex.z *= this._copy.scaling.z;
  46285. this._vertex.x += this._copy.pivot.x;
  46286. this._vertex.y += this._copy.pivot.y;
  46287. this._vertex.z += this._copy.pivot.z;
  46288. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46289. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  46290. if (meshUV) {
  46291. 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);
  46292. u += 2;
  46293. }
  46294. if (this._copy.color) {
  46295. this._color = this._copy.color;
  46296. }
  46297. else if (meshCol && meshCol[c] !== undefined) {
  46298. this._color.r = meshCol[c];
  46299. this._color.g = meshCol[c + 1];
  46300. this._color.b = meshCol[c + 2];
  46301. this._color.a = meshCol[c + 3];
  46302. }
  46303. else {
  46304. this._color.r = 1.0;
  46305. this._color.g = 1.0;
  46306. this._color.b = 1.0;
  46307. this._color.a = 1.0;
  46308. }
  46309. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  46310. c += 4;
  46311. if (!this.recomputeNormals && meshNor) {
  46312. this._normal.x = meshNor[n];
  46313. this._normal.y = meshNor[n + 1];
  46314. this._normal.z = meshNor[n + 2];
  46315. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  46316. normals.push(this._normal.x, this._normal.y, this._normal.z);
  46317. n += 3;
  46318. }
  46319. }
  46320. for (i = 0; i < meshInd.length; i++) {
  46321. var current_ind = p + meshInd[i];
  46322. indices.push(current_ind);
  46323. if (current_ind > 65535) {
  46324. this._needs32Bits = true;
  46325. }
  46326. }
  46327. if (this._pickable) {
  46328. var nbfaces = meshInd.length / 3;
  46329. for (i = 0; i < nbfaces; i++) {
  46330. this.pickedParticles.push({ idx: idx, faceId: i });
  46331. }
  46332. }
  46333. if (this._depthSort) {
  46334. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  46335. }
  46336. return this._copy;
  46337. };
  46338. // returns a shape array from positions array
  46339. SolidParticleSystem.prototype._posToShape = function (positions) {
  46340. var shape = [];
  46341. for (var i = 0; i < positions.length; i += 3) {
  46342. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  46343. }
  46344. return shape;
  46345. };
  46346. // returns a shapeUV array from a Vector4 uvs
  46347. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  46348. var shapeUV = [];
  46349. if (uvs) {
  46350. for (var i = 0; i < uvs.length; i++)
  46351. shapeUV.push(uvs[i]);
  46352. }
  46353. return shapeUV;
  46354. };
  46355. // adds a new particle object in the particles array
  46356. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  46357. if (bInfo === void 0) { bInfo = null; }
  46358. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  46359. this.particles.push(sp);
  46360. return sp;
  46361. };
  46362. /**
  46363. * Adds some particles to the SPS from the model shape. Returns the shape id.
  46364. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  46365. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  46366. * `nb` (positive integer) the number of particles to be created from this model
  46367. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  46368. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46369. */
  46370. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46371. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46372. var meshInd = mesh.getIndices();
  46373. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46374. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46375. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46376. var bbInfo;
  46377. if (this._particlesIntersect) {
  46378. bbInfo = mesh.getBoundingInfo();
  46379. }
  46380. var shape = this._posToShape(meshPos);
  46381. var shapeUV = this._uvsToShapeUV(meshUV);
  46382. var posfunc = options ? options.positionFunction : null;
  46383. var vtxfunc = options ? options.vertexFunction : null;
  46384. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46385. // particles
  46386. var sp;
  46387. var currentCopy;
  46388. var idx = this.nbParticles;
  46389. for (var i = 0; i < nb; i++) {
  46390. var currentPos = this._positions.length;
  46391. var currentInd = this._indices.length;
  46392. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46393. if (this._updatable) {
  46394. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46395. sp.position.copyFrom(currentCopy.position);
  46396. sp.rotation.copyFrom(currentCopy.rotation);
  46397. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46398. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46399. }
  46400. if (currentCopy.color && sp.color) {
  46401. sp.color.copyFrom(currentCopy.color);
  46402. }
  46403. sp.scaling.copyFrom(currentCopy.scaling);
  46404. sp.uvs.copyFrom(currentCopy.uvs);
  46405. }
  46406. this._index += shape.length;
  46407. idx++;
  46408. }
  46409. this.nbParticles += nb;
  46410. this._shapeCounter++;
  46411. return this._shapeCounter - 1;
  46412. };
  46413. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46414. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46415. this._resetCopy();
  46416. if (particle._model._positionFunction) {
  46417. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46418. }
  46419. if (this._copy.rotationQuaternion) {
  46420. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46421. }
  46422. else {
  46423. this._yaw = this._copy.rotation.y;
  46424. this._pitch = this._copy.rotation.x;
  46425. this._roll = this._copy.rotation.z;
  46426. this._quaternionRotationYPR();
  46427. }
  46428. this._quaternionToRotationMatrix();
  46429. this._shape = particle._model._shape;
  46430. for (var pt = 0; pt < this._shape.length; pt++) {
  46431. this._vertex.x = this._shape[pt].x;
  46432. this._vertex.y = this._shape[pt].y;
  46433. this._vertex.z = this._shape[pt].z;
  46434. if (particle._model._vertexFunction) {
  46435. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  46436. }
  46437. this._vertex.x *= this._copy.scaling.x;
  46438. this._vertex.y *= this._copy.scaling.y;
  46439. this._vertex.z *= this._copy.scaling.z;
  46440. this._vertex.x += this._copy.pivot.x;
  46441. this._vertex.y += this._copy.pivot.y;
  46442. this._vertex.z += this._copy.pivot.z;
  46443. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46444. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46445. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46446. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46447. }
  46448. particle.position.x = 0.0;
  46449. particle.position.y = 0.0;
  46450. particle.position.z = 0.0;
  46451. particle.rotation.x = 0.0;
  46452. particle.rotation.y = 0.0;
  46453. particle.rotation.z = 0.0;
  46454. particle.rotationQuaternion = null;
  46455. particle.scaling.x = 1.0;
  46456. particle.scaling.y = 1.0;
  46457. particle.scaling.z = 1.0;
  46458. };
  46459. /**
  46460. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46461. * Returns the SPS.
  46462. */
  46463. SolidParticleSystem.prototype.rebuildMesh = function () {
  46464. for (var p = 0; p < this.particles.length; p++) {
  46465. this._rebuildParticle(this.particles[p]);
  46466. }
  46467. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46468. return this;
  46469. };
  46470. /**
  46471. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46472. * This method calls `updateParticle()` for each particle of the SPS.
  46473. * For an animated SPS, it is usually called within the render loop.
  46474. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46475. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46476. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46477. * Returns the SPS.
  46478. */
  46479. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46480. if (start === void 0) { start = 0; }
  46481. if (end === void 0) { end = this.nbParticles - 1; }
  46482. if (update === void 0) { update = true; }
  46483. if (!this._updatable) {
  46484. return this;
  46485. }
  46486. // custom beforeUpdate
  46487. this.beforeUpdateParticles(start, end, update);
  46488. this._cam_axisX.x = 1.0;
  46489. this._cam_axisX.y = 0.0;
  46490. this._cam_axisX.z = 0.0;
  46491. this._cam_axisY.x = 0.0;
  46492. this._cam_axisY.y = 1.0;
  46493. this._cam_axisY.z = 0.0;
  46494. this._cam_axisZ.x = 0.0;
  46495. this._cam_axisZ.y = 0.0;
  46496. this._cam_axisZ.z = 1.0;
  46497. // cases when the World Matrix is to be computed first
  46498. if (this.billboard || this._depthSort) {
  46499. this.mesh.computeWorldMatrix(true);
  46500. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46501. }
  46502. // if the particles will always face the camera
  46503. if (this.billboard) {
  46504. // compute the camera position and un-rotate it by the current mesh rotation
  46505. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46506. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46507. this._cam_axisZ.normalize();
  46508. // same for camera up vector extracted from the cam view matrix
  46509. var view = this._camera.getViewMatrix(true);
  46510. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46511. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46512. this._cam_axisY.normalize();
  46513. this._cam_axisX.normalize();
  46514. }
  46515. // if depthSort, compute the camera global position in the mesh local system
  46516. if (this._depthSort) {
  46517. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46518. }
  46519. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46520. var idx = 0; // current position index in the global array positions32
  46521. var index = 0; // position start index in the global array positions32 of the current particle
  46522. var colidx = 0; // current color index in the global array colors32
  46523. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46524. var uvidx = 0; // current uv index in the global array uvs32
  46525. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46526. var pt = 0; // current index in the particle model shape
  46527. if (this.mesh.isFacetDataEnabled) {
  46528. this._computeBoundingBox = true;
  46529. }
  46530. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46531. if (this._computeBoundingBox) {
  46532. if (start == 0 && end == this.nbParticles - 1) {
  46533. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46534. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46535. }
  46536. else {
  46537. if (this.mesh._boundingInfo) {
  46538. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46539. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46540. }
  46541. }
  46542. }
  46543. // particle loop
  46544. index = this.particles[start]._pos;
  46545. var vpos = (index / 3) | 0;
  46546. colorIndex = vpos * 4;
  46547. uvIndex = vpos * 2;
  46548. for (var p = start; p <= end; p++) {
  46549. this._particle = this.particles[p];
  46550. this._shape = this._particle._model._shape;
  46551. this._shapeUV = this._particle._model._shapeUV;
  46552. // call to custom user function to update the particle properties
  46553. this.updateParticle(this._particle);
  46554. // camera-particle distance for depth sorting
  46555. if (this._depthSort && this._depthSortParticles) {
  46556. var dsp = this.depthSortedParticles[p];
  46557. dsp.ind = this._particle._ind;
  46558. dsp.indicesLength = this._particle._model._indicesLength;
  46559. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46560. }
  46561. // skip the computations for inactive or already invisible particles
  46562. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46563. // increment indexes for the next particle
  46564. pt = this._shape.length;
  46565. index += pt * 3;
  46566. colorIndex += pt * 4;
  46567. uvIndex += pt * 2;
  46568. continue;
  46569. }
  46570. if (this._particle.isVisible) {
  46571. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46572. // particle rotation matrix
  46573. if (this.billboard) {
  46574. this._particle.rotation.x = 0.0;
  46575. this._particle.rotation.y = 0.0;
  46576. }
  46577. if (this._computeParticleRotation || this.billboard) {
  46578. if (this._particle.rotationQuaternion) {
  46579. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46580. }
  46581. else {
  46582. this._yaw = this._particle.rotation.y;
  46583. this._pitch = this._particle.rotation.x;
  46584. this._roll = this._particle.rotation.z;
  46585. this._quaternionRotationYPR();
  46586. }
  46587. this._quaternionToRotationMatrix();
  46588. }
  46589. // particle vertex loop
  46590. for (pt = 0; pt < this._shape.length; pt++) {
  46591. idx = index + pt * 3;
  46592. colidx = colorIndex + pt * 4;
  46593. uvidx = uvIndex + pt * 2;
  46594. this._vertex.x = this._shape[pt].x;
  46595. this._vertex.y = this._shape[pt].y;
  46596. this._vertex.z = this._shape[pt].z;
  46597. if (this._computeParticleVertex) {
  46598. this.updateParticleVertex(this._particle, this._vertex, pt);
  46599. }
  46600. // positions
  46601. this._vertex.x *= this._particle.scaling.x;
  46602. this._vertex.y *= this._particle.scaling.y;
  46603. this._vertex.z *= this._particle.scaling.z;
  46604. this._vertex.x += this._particle.pivot.x;
  46605. this._vertex.y += this._particle.pivot.y;
  46606. this._vertex.z += this._particle.pivot.z;
  46607. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46608. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46609. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46610. 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;
  46611. 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;
  46612. 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;
  46613. if (this._computeBoundingBox) {
  46614. if (this._positions32[idx] < this._minimum.x) {
  46615. this._minimum.x = this._positions32[idx];
  46616. }
  46617. if (this._positions32[idx] > this._maximum.x) {
  46618. this._maximum.x = this._positions32[idx];
  46619. }
  46620. if (this._positions32[idx + 1] < this._minimum.y) {
  46621. this._minimum.y = this._positions32[idx + 1];
  46622. }
  46623. if (this._positions32[idx + 1] > this._maximum.y) {
  46624. this._maximum.y = this._positions32[idx + 1];
  46625. }
  46626. if (this._positions32[idx + 2] < this._minimum.z) {
  46627. this._minimum.z = this._positions32[idx + 2];
  46628. }
  46629. if (this._positions32[idx + 2] > this._maximum.z) {
  46630. this._maximum.z = this._positions32[idx + 2];
  46631. }
  46632. }
  46633. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46634. if (!this._computeParticleVertex) {
  46635. this._normal.x = this._fixedNormal32[idx];
  46636. this._normal.y = this._fixedNormal32[idx + 1];
  46637. this._normal.z = this._fixedNormal32[idx + 2];
  46638. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46639. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46640. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46641. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46642. 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;
  46643. 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;
  46644. }
  46645. if (this._computeParticleColor && this._particle.color) {
  46646. this._colors32[colidx] = this._particle.color.r;
  46647. this._colors32[colidx + 1] = this._particle.color.g;
  46648. this._colors32[colidx + 2] = this._particle.color.b;
  46649. this._colors32[colidx + 3] = this._particle.color.a;
  46650. }
  46651. if (this._computeParticleTexture) {
  46652. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46653. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46654. }
  46655. }
  46656. }
  46657. else {
  46658. this._particle._stillInvisible = true; // mark the particle as invisible
  46659. for (pt = 0; pt < this._shape.length; pt++) {
  46660. idx = index + pt * 3;
  46661. colidx = colorIndex + pt * 4;
  46662. uvidx = uvIndex + pt * 2;
  46663. this._positions32[idx] = 0.0;
  46664. this._positions32[idx + 1] = 0.0;
  46665. this._positions32[idx + 2] = 0.0;
  46666. this._normals32[idx] = 0.0;
  46667. this._normals32[idx + 1] = 0.0;
  46668. this._normals32[idx + 2] = 0.0;
  46669. if (this._computeParticleColor && this._particle.color) {
  46670. this._colors32[colidx] = this._particle.color.r;
  46671. this._colors32[colidx + 1] = this._particle.color.g;
  46672. this._colors32[colidx + 2] = this._particle.color.b;
  46673. this._colors32[colidx + 3] = this._particle.color.a;
  46674. }
  46675. if (this._computeParticleTexture) {
  46676. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46677. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46678. }
  46679. }
  46680. }
  46681. // if the particle intersections must be computed : update the bbInfo
  46682. if (this._particlesIntersect) {
  46683. var bInfo = this._particle._boundingInfo;
  46684. var bBox = bInfo.boundingBox;
  46685. var bSphere = bInfo.boundingSphere;
  46686. if (!this._bSphereOnly) {
  46687. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46688. for (var b = 0; b < bBox.vectors.length; b++) {
  46689. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46690. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46691. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46692. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46693. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46694. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46695. 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;
  46696. 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;
  46697. 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;
  46698. }
  46699. bBox._update(this.mesh._worldMatrix);
  46700. }
  46701. // place and scale the particle bouding sphere in the SPS local system, then update it
  46702. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46703. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46704. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46705. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46706. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46707. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46708. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46709. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46710. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46711. 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));
  46712. bSphere._update(this.mesh._worldMatrix);
  46713. }
  46714. // increment indexes for the next particle
  46715. index = idx + 3;
  46716. colorIndex = colidx + 4;
  46717. uvIndex = uvidx + 2;
  46718. }
  46719. // if the VBO must be updated
  46720. if (update) {
  46721. if (this._computeParticleColor) {
  46722. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46723. }
  46724. if (this._computeParticleTexture) {
  46725. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46726. }
  46727. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46728. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46729. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46730. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46731. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46732. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46733. for (var i = 0; i < this._normals32.length; i++) {
  46734. this._fixedNormal32[i] = this._normals32[i];
  46735. }
  46736. }
  46737. if (!this.mesh.areNormalsFrozen) {
  46738. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46739. }
  46740. }
  46741. if (this._depthSort && this._depthSortParticles) {
  46742. this.depthSortedParticles.sort(this._depthSortFunction);
  46743. var dspl = this.depthSortedParticles.length;
  46744. var sorted = 0;
  46745. var lind = 0;
  46746. var sind = 0;
  46747. var sid = 0;
  46748. for (sorted = 0; sorted < dspl; sorted++) {
  46749. lind = this.depthSortedParticles[sorted].indicesLength;
  46750. sind = this.depthSortedParticles[sorted].ind;
  46751. for (var i = 0; i < lind; i++) {
  46752. this._indices32[sid] = this._indices[sind + i];
  46753. sid++;
  46754. }
  46755. }
  46756. this.mesh.updateIndices(this._indices32);
  46757. }
  46758. }
  46759. if (this._computeBoundingBox) {
  46760. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46761. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46762. }
  46763. this.afterUpdateParticles(start, end, update);
  46764. return this;
  46765. };
  46766. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46767. this._halfroll = this._roll * 0.5;
  46768. this._halfpitch = this._pitch * 0.5;
  46769. this._halfyaw = this._yaw * 0.5;
  46770. this._sinRoll = Math.sin(this._halfroll);
  46771. this._cosRoll = Math.cos(this._halfroll);
  46772. this._sinPitch = Math.sin(this._halfpitch);
  46773. this._cosPitch = Math.cos(this._halfpitch);
  46774. this._sinYaw = Math.sin(this._halfyaw);
  46775. this._cosYaw = Math.cos(this._halfyaw);
  46776. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46777. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46778. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46779. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46780. };
  46781. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46782. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46783. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46784. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46785. this._rotMatrix.m[3] = 0;
  46786. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46787. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46788. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46789. this._rotMatrix.m[7] = 0;
  46790. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46791. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46792. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46793. this._rotMatrix.m[11] = 0;
  46794. this._rotMatrix.m[12] = 0;
  46795. this._rotMatrix.m[13] = 0;
  46796. this._rotMatrix.m[14] = 0;
  46797. this._rotMatrix.m[15] = 1.0;
  46798. };
  46799. /**
  46800. * Disposes the SPS.
  46801. * Returns nothing.
  46802. */
  46803. SolidParticleSystem.prototype.dispose = function () {
  46804. this.mesh.dispose();
  46805. this.vars = null;
  46806. // drop references to internal big arrays for the GC
  46807. this._positions = null;
  46808. this._indices = null;
  46809. this._normals = null;
  46810. this._uvs = null;
  46811. this._colors = null;
  46812. this._indices32 = null;
  46813. this._positions32 = null;
  46814. this._normals32 = null;
  46815. this._fixedNormal32 = null;
  46816. this._uvs32 = null;
  46817. this._colors32 = null;
  46818. this.pickedParticles = null;
  46819. };
  46820. /**
  46821. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46822. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46823. * Returns the SPS.
  46824. */
  46825. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46826. if (!this._isVisibilityBoxLocked) {
  46827. this.mesh.refreshBoundingInfo();
  46828. }
  46829. return this;
  46830. };
  46831. /**
  46832. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46833. * @param size the size (float) of the visibility box
  46834. * note : this doesn't lock the SPS mesh bounding box.
  46835. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46836. */
  46837. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46838. var vis = size / 2;
  46839. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46840. };
  46841. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46842. // getter and setter
  46843. get: function () {
  46844. return this._alwaysVisible;
  46845. },
  46846. /**
  46847. * Sets the SPS as always visible or not
  46848. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46849. */
  46850. set: function (val) {
  46851. this._alwaysVisible = val;
  46852. this.mesh.alwaysSelectAsActiveMesh = val;
  46853. },
  46854. enumerable: true,
  46855. configurable: true
  46856. });
  46857. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46858. get: function () {
  46859. return this._isVisibilityBoxLocked;
  46860. },
  46861. /**
  46862. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46863. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46864. */
  46865. set: function (val) {
  46866. this._isVisibilityBoxLocked = val;
  46867. var boundingInfo = this.mesh.getBoundingInfo();
  46868. boundingInfo.isLocked = val;
  46869. },
  46870. enumerable: true,
  46871. configurable: true
  46872. });
  46873. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46874. // getters
  46875. get: function () {
  46876. return this._computeParticleRotation;
  46877. },
  46878. // Optimizer setters
  46879. /**
  46880. * Tells to `setParticles()` to compute the particle rotations or not.
  46881. * Default value : true. The SPS is faster when it's set to false.
  46882. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46883. */
  46884. set: function (val) {
  46885. this._computeParticleRotation = val;
  46886. },
  46887. enumerable: true,
  46888. configurable: true
  46889. });
  46890. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46891. get: function () {
  46892. return this._computeParticleColor;
  46893. },
  46894. /**
  46895. * Tells to `setParticles()` to compute the particle colors or not.
  46896. * Default value : true. The SPS is faster when it's set to false.
  46897. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46898. */
  46899. set: function (val) {
  46900. this._computeParticleColor = val;
  46901. },
  46902. enumerable: true,
  46903. configurable: true
  46904. });
  46905. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46906. get: function () {
  46907. return this._computeParticleTexture;
  46908. },
  46909. /**
  46910. * Tells to `setParticles()` to compute the particle textures or not.
  46911. * Default value : true. The SPS is faster when it's set to false.
  46912. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46913. */
  46914. set: function (val) {
  46915. this._computeParticleTexture = val;
  46916. },
  46917. enumerable: true,
  46918. configurable: true
  46919. });
  46920. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46921. get: function () {
  46922. return this._computeParticleVertex;
  46923. },
  46924. /**
  46925. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46926. * Default value : false. The SPS is faster when it's set to false.
  46927. * Note : the particle custom vertex positions aren't stored values.
  46928. */
  46929. set: function (val) {
  46930. this._computeParticleVertex = val;
  46931. },
  46932. enumerable: true,
  46933. configurable: true
  46934. });
  46935. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46936. get: function () {
  46937. return this._computeBoundingBox;
  46938. },
  46939. /**
  46940. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46941. */
  46942. set: function (val) {
  46943. this._computeBoundingBox = val;
  46944. },
  46945. enumerable: true,
  46946. configurable: true
  46947. });
  46948. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46949. get: function () {
  46950. return this._depthSortParticles;
  46951. },
  46952. /**
  46953. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46954. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46955. * Default : `true`
  46956. */
  46957. set: function (val) {
  46958. this._depthSortParticles = val;
  46959. },
  46960. enumerable: true,
  46961. configurable: true
  46962. });
  46963. // =======================================================================
  46964. // Particle behavior logic
  46965. // these following methods may be overwritten by the user to fit his needs
  46966. /**
  46967. * This function does nothing. It may be overwritten to set all the particle first values.
  46968. * The SPS doesn't call this function, you may have to call it by your own.
  46969. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46970. */
  46971. SolidParticleSystem.prototype.initParticles = function () {
  46972. };
  46973. /**
  46974. * This function does nothing. It may be overwritten to recycle a particle.
  46975. * The SPS doesn't call this function, you may have to call it by your own.
  46976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46977. */
  46978. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46979. return particle;
  46980. };
  46981. /**
  46982. * Updates a particle : this function should be overwritten by the user.
  46983. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46984. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46985. * ex : just set a particle position or velocity and recycle conditions
  46986. */
  46987. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46988. return particle;
  46989. };
  46990. /**
  46991. * Updates a vertex of a particle : it can be overwritten by the user.
  46992. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46993. * @param particle the current particle
  46994. * @param vertex the current index of the current particle
  46995. * @param pt the index of the current vertex in the particle shape
  46996. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46997. * ex : just set a vertex particle position
  46998. */
  46999. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47000. return vertex;
  47001. };
  47002. /**
  47003. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47004. * This does nothing and may be overwritten by the user.
  47005. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47006. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47007. * @param update the boolean update value actually passed to setParticles()
  47008. */
  47009. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47010. };
  47011. /**
  47012. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47013. * This will be passed three parameters.
  47014. * This does nothing and may be overwritten by the user.
  47015. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47016. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47017. * @param update the boolean update value actually passed to setParticles()
  47018. */
  47019. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47020. };
  47021. return SolidParticleSystem;
  47022. }());
  47023. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47024. })(BABYLON || (BABYLON = {}));
  47025. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47026. var BABYLON;
  47027. (function (BABYLON) {
  47028. var GroundMesh = /** @class */ (function (_super) {
  47029. __extends(GroundMesh, _super);
  47030. function GroundMesh(name, scene) {
  47031. var _this = _super.call(this, name, scene) || this;
  47032. _this.generateOctree = false;
  47033. return _this;
  47034. }
  47035. GroundMesh.prototype.getClassName = function () {
  47036. return "GroundMesh";
  47037. };
  47038. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  47039. get: function () {
  47040. return Math.min(this._subdivisionsX, this._subdivisionsY);
  47041. },
  47042. enumerable: true,
  47043. configurable: true
  47044. });
  47045. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  47046. get: function () {
  47047. return this._subdivisionsX;
  47048. },
  47049. enumerable: true,
  47050. configurable: true
  47051. });
  47052. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  47053. get: function () {
  47054. return this._subdivisionsY;
  47055. },
  47056. enumerable: true,
  47057. configurable: true
  47058. });
  47059. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  47060. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  47061. this._subdivisionsX = chunksCount;
  47062. this._subdivisionsY = chunksCount;
  47063. this.subdivide(chunksCount);
  47064. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  47065. };
  47066. /**
  47067. * Returns a height (y) value in the Worl system :
  47068. * the ground altitude at the coordinates (x, z) expressed in the World system.
  47069. * Returns the ground y position if (x, z) are outside the ground surface.
  47070. */
  47071. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  47072. var world = this.getWorldMatrix();
  47073. var invMat = BABYLON.Tmp.Matrix[5];
  47074. world.invertToRef(invMat);
  47075. var tmpVect = BABYLON.Tmp.Vector3[8];
  47076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  47077. x = tmpVect.x;
  47078. z = tmpVect.z;
  47079. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47080. return this.position.y;
  47081. }
  47082. if (!this._heightQuads || this._heightQuads.length == 0) {
  47083. this._initHeightQuads();
  47084. this._computeHeightQuads();
  47085. }
  47086. var facet = this._getFacetAt(x, z);
  47087. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  47088. // return y in the World system
  47089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  47090. return tmpVect.y;
  47091. };
  47092. /**
  47093. * Returns a normalized vector (Vector3) orthogonal to the ground
  47094. * at the ground coordinates (x, z) expressed in the World system.
  47095. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  47096. */
  47097. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  47098. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  47099. this.getNormalAtCoordinatesToRef(x, z, normal);
  47100. return normal;
  47101. };
  47102. /**
  47103. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  47104. * at the ground coordinates (x, z) expressed in the World system.
  47105. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  47106. * Returns the GroundMesh.
  47107. */
  47108. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  47109. var world = this.getWorldMatrix();
  47110. var tmpMat = BABYLON.Tmp.Matrix[5];
  47111. world.invertToRef(tmpMat);
  47112. var tmpVect = BABYLON.Tmp.Vector3[8];
  47113. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  47114. x = tmpVect.x;
  47115. z = tmpVect.z;
  47116. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47117. return this;
  47118. }
  47119. if (!this._heightQuads || this._heightQuads.length == 0) {
  47120. this._initHeightQuads();
  47121. this._computeHeightQuads();
  47122. }
  47123. var facet = this._getFacetAt(x, z);
  47124. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  47125. return this;
  47126. };
  47127. /**
  47128. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  47129. * if the ground has been updated.
  47130. * This can be used in the render loop.
  47131. * Returns the GroundMesh.
  47132. */
  47133. GroundMesh.prototype.updateCoordinateHeights = function () {
  47134. if (!this._heightQuads || this._heightQuads.length == 0) {
  47135. this._initHeightQuads();
  47136. }
  47137. this._computeHeightQuads();
  47138. return this;
  47139. };
  47140. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  47141. GroundMesh.prototype._getFacetAt = function (x, z) {
  47142. // retrieve col and row from x, z coordinates in the ground local system
  47143. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  47144. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  47145. var quad = this._heightQuads[row * this._subdivisionsX + col];
  47146. var facet;
  47147. if (z < quad.slope.x * x + quad.slope.y) {
  47148. facet = quad.facet1;
  47149. }
  47150. else {
  47151. facet = quad.facet2;
  47152. }
  47153. return facet;
  47154. };
  47155. // Creates and populates the heightMap array with "facet" elements :
  47156. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  47157. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47158. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47159. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47160. // Returns the GroundMesh.
  47161. GroundMesh.prototype._initHeightQuads = function () {
  47162. var subdivisionsX = this._subdivisionsX;
  47163. var subdivisionsY = this._subdivisionsY;
  47164. this._heightQuads = new Array();
  47165. for (var row = 0; row < subdivisionsY; row++) {
  47166. for (var col = 0; col < subdivisionsX; col++) {
  47167. 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) };
  47168. this._heightQuads[row * subdivisionsX + col] = quad;
  47169. }
  47170. }
  47171. return this;
  47172. };
  47173. // Compute each quad element values and update the the heightMap array :
  47174. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47175. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47176. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47177. // Returns the GroundMesh.
  47178. GroundMesh.prototype._computeHeightQuads = function () {
  47179. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47180. if (!positions) {
  47181. return this;
  47182. }
  47183. var v1 = BABYLON.Tmp.Vector3[3];
  47184. var v2 = BABYLON.Tmp.Vector3[2];
  47185. var v3 = BABYLON.Tmp.Vector3[1];
  47186. var v4 = BABYLON.Tmp.Vector3[0];
  47187. var v1v2 = BABYLON.Tmp.Vector3[4];
  47188. var v1v3 = BABYLON.Tmp.Vector3[5];
  47189. var v1v4 = BABYLON.Tmp.Vector3[6];
  47190. var norm1 = BABYLON.Tmp.Vector3[7];
  47191. var norm2 = BABYLON.Tmp.Vector3[8];
  47192. var i = 0;
  47193. var j = 0;
  47194. var k = 0;
  47195. var cd = 0; // 2D slope coefficient : z = cd * x + h
  47196. var h = 0;
  47197. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  47198. var d2 = 0;
  47199. var subdivisionsX = this._subdivisionsX;
  47200. var subdivisionsY = this._subdivisionsY;
  47201. for (var row = 0; row < subdivisionsY; row++) {
  47202. for (var col = 0; col < subdivisionsX; col++) {
  47203. i = col * 3;
  47204. j = row * (subdivisionsX + 1) * 3;
  47205. k = (row + 1) * (subdivisionsX + 1) * 3;
  47206. v1.x = positions[j + i];
  47207. v1.y = positions[j + i + 1];
  47208. v1.z = positions[j + i + 2];
  47209. v2.x = positions[j + i + 3];
  47210. v2.y = positions[j + i + 4];
  47211. v2.z = positions[j + i + 5];
  47212. v3.x = positions[k + i];
  47213. v3.y = positions[k + i + 1];
  47214. v3.z = positions[k + i + 2];
  47215. v4.x = positions[k + i + 3];
  47216. v4.y = positions[k + i + 4];
  47217. v4.z = positions[k + i + 5];
  47218. // 2D slope V1V4
  47219. cd = (v4.z - v1.z) / (v4.x - v1.x);
  47220. h = v1.z - cd * v1.x; // v1 belongs to the slope
  47221. // facet equations :
  47222. // we compute each facet normal vector
  47223. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  47224. // we compute the value d by applying the equation to v1 which belongs to the plane
  47225. // then we store the facet equation in a Vector4
  47226. v2.subtractToRef(v1, v1v2);
  47227. v3.subtractToRef(v1, v1v3);
  47228. v4.subtractToRef(v1, v1v4);
  47229. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  47230. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  47231. norm1.normalize();
  47232. norm2.normalize();
  47233. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  47234. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  47235. var quad = this._heightQuads[row * subdivisionsX + col];
  47236. quad.slope.copyFromFloats(cd, h);
  47237. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  47238. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  47239. }
  47240. }
  47241. return this;
  47242. };
  47243. GroundMesh.prototype.serialize = function (serializationObject) {
  47244. _super.prototype.serialize.call(this, serializationObject);
  47245. serializationObject.subdivisionsX = this._subdivisionsX;
  47246. serializationObject.subdivisionsY = this._subdivisionsY;
  47247. serializationObject.minX = this._minX;
  47248. serializationObject.maxX = this._maxX;
  47249. serializationObject.minZ = this._minZ;
  47250. serializationObject.maxZ = this._maxZ;
  47251. serializationObject.width = this._width;
  47252. serializationObject.height = this._height;
  47253. };
  47254. GroundMesh.Parse = function (parsedMesh, scene) {
  47255. var result = new GroundMesh(parsedMesh.name, scene);
  47256. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  47257. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  47258. result._minX = parsedMesh.minX;
  47259. result._maxX = parsedMesh.maxX;
  47260. result._minZ = parsedMesh.minZ;
  47261. result._maxZ = parsedMesh.maxZ;
  47262. result._width = parsedMesh.width;
  47263. result._height = parsedMesh.height;
  47264. return result;
  47265. };
  47266. return GroundMesh;
  47267. }(BABYLON.Mesh));
  47268. BABYLON.GroundMesh = GroundMesh;
  47269. })(BABYLON || (BABYLON = {}));
  47270. //# sourceMappingURL=babylon.groundMesh.js.map
  47271. var BABYLON;
  47272. (function (BABYLON) {
  47273. /**
  47274. * Creates an instance based on a source mesh.
  47275. */
  47276. var InstancedMesh = /** @class */ (function (_super) {
  47277. __extends(InstancedMesh, _super);
  47278. function InstancedMesh(name, source) {
  47279. var _this = _super.call(this, name, source.getScene()) || this;
  47280. source.instances.push(_this);
  47281. _this._sourceMesh = source;
  47282. _this.position.copyFrom(source.position);
  47283. _this.rotation.copyFrom(source.rotation);
  47284. _this.scaling.copyFrom(source.scaling);
  47285. if (source.rotationQuaternion) {
  47286. _this.rotationQuaternion = source.rotationQuaternion.clone();
  47287. }
  47288. _this.infiniteDistance = source.infiniteDistance;
  47289. _this.setPivotMatrix(source.getPivotMatrix());
  47290. _this.refreshBoundingInfo();
  47291. _this._syncSubMeshes();
  47292. return _this;
  47293. }
  47294. /**
  47295. * Returns the string "InstancedMesh".
  47296. */
  47297. InstancedMesh.prototype.getClassName = function () {
  47298. return "InstancedMesh";
  47299. };
  47300. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  47301. // Methods
  47302. get: function () {
  47303. return this._sourceMesh.receiveShadows;
  47304. },
  47305. enumerable: true,
  47306. configurable: true
  47307. });
  47308. Object.defineProperty(InstancedMesh.prototype, "material", {
  47309. get: function () {
  47310. return this._sourceMesh.material;
  47311. },
  47312. enumerable: true,
  47313. configurable: true
  47314. });
  47315. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  47316. get: function () {
  47317. return this._sourceMesh.visibility;
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  47323. get: function () {
  47324. return this._sourceMesh.skeleton;
  47325. },
  47326. enumerable: true,
  47327. configurable: true
  47328. });
  47329. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  47330. get: function () {
  47331. return this._sourceMesh.renderingGroupId;
  47332. },
  47333. enumerable: true,
  47334. configurable: true
  47335. });
  47336. /**
  47337. * Returns the total number of vertices (integer).
  47338. */
  47339. InstancedMesh.prototype.getTotalVertices = function () {
  47340. return this._sourceMesh.getTotalVertices();
  47341. };
  47342. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  47343. get: function () {
  47344. return this._sourceMesh;
  47345. },
  47346. enumerable: true,
  47347. configurable: true
  47348. });
  47349. /**
  47350. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  47351. */
  47352. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  47353. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  47354. };
  47355. /**
  47356. * Sets the vertex data of the mesh geometry for the requested `kind`.
  47357. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  47358. * The `data` are either a numeric array either a Float32Array.
  47359. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  47360. * 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).
  47361. * Note that a new underlying VertexBuffer object is created each call.
  47362. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  47363. *
  47364. * Possible `kind` values :
  47365. * - BABYLON.VertexBuffer.PositionKind
  47366. * - BABYLON.VertexBuffer.UVKind
  47367. * - BABYLON.VertexBuffer.UV2Kind
  47368. * - BABYLON.VertexBuffer.UV3Kind
  47369. * - BABYLON.VertexBuffer.UV4Kind
  47370. * - BABYLON.VertexBuffer.UV5Kind
  47371. * - BABYLON.VertexBuffer.UV6Kind
  47372. * - BABYLON.VertexBuffer.ColorKind
  47373. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47374. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47375. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47376. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47377. *
  47378. * Returns the Mesh.
  47379. */
  47380. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47381. if (this.sourceMesh) {
  47382. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47383. }
  47384. return this.sourceMesh;
  47385. };
  47386. /**
  47387. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47388. * If the mesh has no geometry, it is simply returned as it is.
  47389. * The `data` are either a numeric array either a Float32Array.
  47390. * No new underlying VertexBuffer object is created.
  47391. * 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.
  47392. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47393. *
  47394. * Possible `kind` values :
  47395. * - BABYLON.VertexBuffer.PositionKind
  47396. * - BABYLON.VertexBuffer.UVKind
  47397. * - BABYLON.VertexBuffer.UV2Kind
  47398. * - BABYLON.VertexBuffer.UV3Kind
  47399. * - BABYLON.VertexBuffer.UV4Kind
  47400. * - BABYLON.VertexBuffer.UV5Kind
  47401. * - BABYLON.VertexBuffer.UV6Kind
  47402. * - BABYLON.VertexBuffer.ColorKind
  47403. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47404. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47405. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47406. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47407. *
  47408. * Returns the Mesh.
  47409. */
  47410. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47411. if (this.sourceMesh) {
  47412. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47413. }
  47414. return this.sourceMesh;
  47415. };
  47416. /**
  47417. * Sets the mesh indices.
  47418. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47419. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47420. * This method creates a new index buffer each call.
  47421. * Returns the Mesh.
  47422. */
  47423. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47424. if (totalVertices === void 0) { totalVertices = null; }
  47425. if (this.sourceMesh) {
  47426. this.sourceMesh.setIndices(indices, totalVertices);
  47427. }
  47428. return this.sourceMesh;
  47429. };
  47430. /**
  47431. * Boolean : True if the mesh owns the requested kind of data.
  47432. */
  47433. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  47434. return this._sourceMesh.isVerticesDataPresent(kind);
  47435. };
  47436. /**
  47437. * Returns an array of indices (IndicesArray).
  47438. */
  47439. InstancedMesh.prototype.getIndices = function () {
  47440. return this._sourceMesh.getIndices();
  47441. };
  47442. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47443. get: function () {
  47444. return this._sourceMesh._positions;
  47445. },
  47446. enumerable: true,
  47447. configurable: true
  47448. });
  47449. /**
  47450. * Sets a new updated BoundingInfo to the mesh.
  47451. * Returns the mesh.
  47452. */
  47453. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47454. var meshBB = this._sourceMesh.getBoundingInfo();
  47455. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47456. this._updateBoundingInfo();
  47457. return this;
  47458. };
  47459. InstancedMesh.prototype._preActivate = function () {
  47460. if (this._currentLOD) {
  47461. this._currentLOD._preActivate();
  47462. }
  47463. return this;
  47464. };
  47465. InstancedMesh.prototype._activate = function (renderId) {
  47466. if (this._currentLOD) {
  47467. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47468. }
  47469. return this;
  47470. };
  47471. /**
  47472. * Returns the current associated LOD AbstractMesh.
  47473. */
  47474. InstancedMesh.prototype.getLOD = function (camera) {
  47475. if (!camera) {
  47476. return this;
  47477. }
  47478. var boundingInfo = this.getBoundingInfo();
  47479. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47480. if (this._currentLOD === this.sourceMesh) {
  47481. return this;
  47482. }
  47483. return this._currentLOD;
  47484. };
  47485. InstancedMesh.prototype._syncSubMeshes = function () {
  47486. this.releaseSubMeshes();
  47487. if (this._sourceMesh.subMeshes) {
  47488. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47489. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47490. }
  47491. }
  47492. return this;
  47493. };
  47494. InstancedMesh.prototype._generatePointsArray = function () {
  47495. return this._sourceMesh._generatePointsArray();
  47496. };
  47497. /**
  47498. * Creates a new InstancedMesh from the current mesh.
  47499. * - name (string) : the cloned mesh name
  47500. * - newParent (optional Node) : the optional Node to parent the clone to.
  47501. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47502. *
  47503. * Returns the clone.
  47504. */
  47505. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47506. var result = this._sourceMesh.createInstance(name);
  47507. // Deep copy
  47508. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47509. // Bounding info
  47510. this.refreshBoundingInfo();
  47511. // Parent
  47512. if (newParent) {
  47513. result.parent = newParent;
  47514. }
  47515. if (!doNotCloneChildren) {
  47516. // Children
  47517. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47518. var mesh = this.getScene().meshes[index];
  47519. if (mesh.parent === this) {
  47520. mesh.clone(mesh.name, result);
  47521. }
  47522. }
  47523. }
  47524. result.computeWorldMatrix(true);
  47525. return result;
  47526. };
  47527. /**
  47528. * Disposes the InstancedMesh.
  47529. * Returns nothing.
  47530. */
  47531. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47532. // Remove from mesh
  47533. var index = this._sourceMesh.instances.indexOf(this);
  47534. this._sourceMesh.instances.splice(index, 1);
  47535. _super.prototype.dispose.call(this, doNotRecurse);
  47536. };
  47537. return InstancedMesh;
  47538. }(BABYLON.AbstractMesh));
  47539. BABYLON.InstancedMesh = InstancedMesh;
  47540. })(BABYLON || (BABYLON = {}));
  47541. //# sourceMappingURL=babylon.instancedMesh.js.map
  47542. var BABYLON;
  47543. (function (BABYLON) {
  47544. var LinesMesh = /** @class */ (function (_super) {
  47545. __extends(LinesMesh, _super);
  47546. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47547. if (scene === void 0) { scene = null; }
  47548. if (parent === void 0) { parent = null; }
  47549. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47550. _this.useVertexColor = useVertexColor;
  47551. _this.useVertexAlpha = useVertexAlpha;
  47552. _this.color = new BABYLON.Color3(1, 1, 1);
  47553. _this.alpha = 1;
  47554. if (source) {
  47555. _this.color = source.color.clone();
  47556. _this.alpha = source.alpha;
  47557. _this.useVertexColor = source.useVertexColor;
  47558. _this.useVertexAlpha = source.useVertexAlpha;
  47559. }
  47560. _this._intersectionThreshold = 0.1;
  47561. var defines = [];
  47562. var options = {
  47563. attributes: [BABYLON.VertexBuffer.PositionKind],
  47564. uniforms: ["world", "viewProjection"],
  47565. needAlphaBlending: true,
  47566. defines: defines
  47567. };
  47568. if (useVertexAlpha === false) {
  47569. options.needAlphaBlending = false;
  47570. }
  47571. if (!useVertexColor) {
  47572. options.uniforms.push("color");
  47573. }
  47574. else {
  47575. options.defines.push("#define VERTEXCOLOR");
  47576. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47577. }
  47578. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47579. return _this;
  47580. }
  47581. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47582. /**
  47583. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47584. * This margin is expressed in world space coordinates, so its value may vary.
  47585. * Default value is 0.1
  47586. * @returns the intersection Threshold value.
  47587. */
  47588. get: function () {
  47589. return this._intersectionThreshold;
  47590. },
  47591. /**
  47592. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47593. * This margin is expressed in world space coordinates, so its value may vary.
  47594. * @param value the new threshold to apply
  47595. */
  47596. set: function (value) {
  47597. if (this._intersectionThreshold === value) {
  47598. return;
  47599. }
  47600. this._intersectionThreshold = value;
  47601. if (this.geometry) {
  47602. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47603. }
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. /**
  47609. * Returns the string "LineMesh"
  47610. */
  47611. LinesMesh.prototype.getClassName = function () {
  47612. return "LinesMesh";
  47613. };
  47614. Object.defineProperty(LinesMesh.prototype, "material", {
  47615. get: function () {
  47616. return this._colorShader;
  47617. },
  47618. set: function (value) {
  47619. // Do nothing
  47620. },
  47621. enumerable: true,
  47622. configurable: true
  47623. });
  47624. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47625. get: function () {
  47626. return false;
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. LinesMesh.prototype.createInstance = function (name) {
  47632. throw new Error("LinesMeshes do not support createInstance.");
  47633. };
  47634. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47635. if (!this._geometry) {
  47636. return this;
  47637. }
  47638. // VBOs
  47639. this._geometry._bind(this._colorShader.getEffect());
  47640. // Color
  47641. if (!this.useVertexColor) {
  47642. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47643. }
  47644. return this;
  47645. };
  47646. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47647. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47648. return this;
  47649. }
  47650. var engine = this.getScene().getEngine();
  47651. // Draw order
  47652. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  47653. return this;
  47654. };
  47655. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47656. this._colorShader.dispose();
  47657. _super.prototype.dispose.call(this, doNotRecurse);
  47658. };
  47659. /**
  47660. * Returns a new LineMesh object cloned from the current one.
  47661. */
  47662. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47663. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47664. };
  47665. return LinesMesh;
  47666. }(BABYLON.Mesh));
  47667. BABYLON.LinesMesh = LinesMesh;
  47668. })(BABYLON || (BABYLON = {}));
  47669. //# sourceMappingURL=babylon.linesMesh.js.map
  47670. var BABYLON;
  47671. (function (BABYLON) {
  47672. var ShaderMaterial = /** @class */ (function (_super) {
  47673. __extends(ShaderMaterial, _super);
  47674. function ShaderMaterial(name, scene, shaderPath, options) {
  47675. var _this = _super.call(this, name, scene) || this;
  47676. _this._textures = {};
  47677. _this._textureArrays = {};
  47678. _this._floats = {};
  47679. _this._floatsArrays = {};
  47680. _this._colors3 = {};
  47681. _this._colors3Arrays = {};
  47682. _this._colors4 = {};
  47683. _this._vectors2 = {};
  47684. _this._vectors3 = {};
  47685. _this._vectors4 = {};
  47686. _this._matrices = {};
  47687. _this._matrices3x3 = {};
  47688. _this._matrices2x2 = {};
  47689. _this._vectors2Arrays = {};
  47690. _this._vectors3Arrays = {};
  47691. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47692. _this._shaderPath = shaderPath;
  47693. options.needAlphaBlending = options.needAlphaBlending || false;
  47694. options.needAlphaTesting = options.needAlphaTesting || false;
  47695. options.attributes = options.attributes || ["position", "normal", "uv"];
  47696. options.uniforms = options.uniforms || ["worldViewProjection"];
  47697. options.uniformBuffers = options.uniformBuffers || [];
  47698. options.samplers = options.samplers || [];
  47699. options.defines = options.defines || [];
  47700. _this._options = options;
  47701. return _this;
  47702. }
  47703. ShaderMaterial.prototype.getClassName = function () {
  47704. return "ShaderMaterial";
  47705. };
  47706. ShaderMaterial.prototype.needAlphaBlending = function () {
  47707. return this._options.needAlphaBlending;
  47708. };
  47709. ShaderMaterial.prototype.needAlphaTesting = function () {
  47710. return this._options.needAlphaTesting;
  47711. };
  47712. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47713. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47714. this._options.uniforms.push(uniformName);
  47715. }
  47716. };
  47717. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47718. if (this._options.samplers.indexOf(name) === -1) {
  47719. this._options.samplers.push(name);
  47720. }
  47721. this._textures[name] = texture;
  47722. return this;
  47723. };
  47724. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47725. if (this._options.samplers.indexOf(name) === -1) {
  47726. this._options.samplers.push(name);
  47727. }
  47728. this._checkUniform(name);
  47729. this._textureArrays[name] = textures;
  47730. return this;
  47731. };
  47732. ShaderMaterial.prototype.setFloat = function (name, value) {
  47733. this._checkUniform(name);
  47734. this._floats[name] = value;
  47735. return this;
  47736. };
  47737. ShaderMaterial.prototype.setFloats = function (name, value) {
  47738. this._checkUniform(name);
  47739. this._floatsArrays[name] = value;
  47740. return this;
  47741. };
  47742. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47743. this._checkUniform(name);
  47744. this._colors3[name] = value;
  47745. return this;
  47746. };
  47747. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47748. this._checkUniform(name);
  47749. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47750. color.toArray(arr, arr.length);
  47751. return arr;
  47752. }, []);
  47753. return this;
  47754. };
  47755. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47756. this._checkUniform(name);
  47757. this._colors4[name] = value;
  47758. return this;
  47759. };
  47760. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47761. this._checkUniform(name);
  47762. this._vectors2[name] = value;
  47763. return this;
  47764. };
  47765. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47766. this._checkUniform(name);
  47767. this._vectors3[name] = value;
  47768. return this;
  47769. };
  47770. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47771. this._checkUniform(name);
  47772. this._vectors4[name] = value;
  47773. return this;
  47774. };
  47775. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47776. this._checkUniform(name);
  47777. this._matrices[name] = value;
  47778. return this;
  47779. };
  47780. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47781. this._checkUniform(name);
  47782. this._matrices3x3[name] = value;
  47783. return this;
  47784. };
  47785. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47786. this._checkUniform(name);
  47787. this._matrices2x2[name] = value;
  47788. return this;
  47789. };
  47790. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47791. this._checkUniform(name);
  47792. this._vectors2Arrays[name] = value;
  47793. return this;
  47794. };
  47795. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47796. this._checkUniform(name);
  47797. this._vectors3Arrays[name] = value;
  47798. return this;
  47799. };
  47800. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47801. if (!mesh) {
  47802. return true;
  47803. }
  47804. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47805. return false;
  47806. }
  47807. return false;
  47808. };
  47809. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47810. var scene = this.getScene();
  47811. var engine = scene.getEngine();
  47812. if (!this.checkReadyOnEveryCall) {
  47813. if (this._renderId === scene.getRenderId()) {
  47814. if (this._checkCache(scene, mesh, useInstances)) {
  47815. return true;
  47816. }
  47817. }
  47818. }
  47819. // Instances
  47820. var defines = [];
  47821. var attribs = [];
  47822. var fallbacks = new BABYLON.EffectFallbacks();
  47823. if (useInstances) {
  47824. defines.push("#define INSTANCES");
  47825. }
  47826. for (var index = 0; index < this._options.defines.length; index++) {
  47827. defines.push(this._options.defines[index]);
  47828. }
  47829. for (var index = 0; index < this._options.attributes.length; index++) {
  47830. attribs.push(this._options.attributes[index]);
  47831. }
  47832. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47833. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47834. defines.push("#define VERTEXCOLOR");
  47835. }
  47836. // Bones
  47837. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47838. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47839. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47840. if (mesh.numBoneInfluencers > 4) {
  47841. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47842. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47843. }
  47844. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47845. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47846. fallbacks.addCPUSkinningFallback(0, mesh);
  47847. if (this._options.uniforms.indexOf("mBones") === -1) {
  47848. this._options.uniforms.push("mBones");
  47849. }
  47850. }
  47851. else {
  47852. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47853. }
  47854. // Textures
  47855. for (var name in this._textures) {
  47856. if (!this._textures[name].isReady()) {
  47857. return false;
  47858. }
  47859. }
  47860. // Alpha test
  47861. if (engine.getAlphaTesting()) {
  47862. defines.push("#define ALPHATEST");
  47863. }
  47864. var previousEffect = this._effect;
  47865. var join = defines.join("\n");
  47866. this._effect = engine.createEffect(this._shaderPath, {
  47867. attributes: attribs,
  47868. uniformsNames: this._options.uniforms,
  47869. uniformBuffersNames: this._options.uniformBuffers,
  47870. samplers: this._options.samplers,
  47871. defines: join,
  47872. fallbacks: fallbacks,
  47873. onCompiled: this.onCompiled,
  47874. onError: this.onError
  47875. }, engine);
  47876. if (!this._effect.isReady()) {
  47877. return false;
  47878. }
  47879. if (previousEffect !== this._effect) {
  47880. scene.resetCachedMaterial();
  47881. }
  47882. this._renderId = scene.getRenderId();
  47883. return true;
  47884. };
  47885. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47886. var scene = this.getScene();
  47887. if (!this._effect) {
  47888. return;
  47889. }
  47890. if (this._options.uniforms.indexOf("world") !== -1) {
  47891. this._effect.setMatrix("world", world);
  47892. }
  47893. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47894. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47895. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47896. }
  47897. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47898. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47899. }
  47900. };
  47901. ShaderMaterial.prototype.bind = function (world, mesh) {
  47902. // Std values
  47903. this.bindOnlyWorldMatrix(world);
  47904. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47905. if (this._options.uniforms.indexOf("view") !== -1) {
  47906. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47907. }
  47908. if (this._options.uniforms.indexOf("projection") !== -1) {
  47909. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47910. }
  47911. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47912. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47913. }
  47914. // Bones
  47915. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47916. var name;
  47917. // Texture
  47918. for (name in this._textures) {
  47919. this._effect.setTexture(name, this._textures[name]);
  47920. }
  47921. // Texture arrays
  47922. for (name in this._textureArrays) {
  47923. this._effect.setTextureArray(name, this._textureArrays[name]);
  47924. }
  47925. // Float
  47926. for (name in this._floats) {
  47927. this._effect.setFloat(name, this._floats[name]);
  47928. }
  47929. // Float s
  47930. for (name in this._floatsArrays) {
  47931. this._effect.setArray(name, this._floatsArrays[name]);
  47932. }
  47933. // Color3
  47934. for (name in this._colors3) {
  47935. this._effect.setColor3(name, this._colors3[name]);
  47936. }
  47937. for (name in this._colors3Arrays) {
  47938. this._effect.setArray3(name, this._colors3Arrays[name]);
  47939. }
  47940. // Color4
  47941. for (name in this._colors4) {
  47942. var color = this._colors4[name];
  47943. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47944. }
  47945. // Vector2
  47946. for (name in this._vectors2) {
  47947. this._effect.setVector2(name, this._vectors2[name]);
  47948. }
  47949. // Vector3
  47950. for (name in this._vectors3) {
  47951. this._effect.setVector3(name, this._vectors3[name]);
  47952. }
  47953. // Vector4
  47954. for (name in this._vectors4) {
  47955. this._effect.setVector4(name, this._vectors4[name]);
  47956. }
  47957. // Matrix
  47958. for (name in this._matrices) {
  47959. this._effect.setMatrix(name, this._matrices[name]);
  47960. }
  47961. // Matrix 3x3
  47962. for (name in this._matrices3x3) {
  47963. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47964. }
  47965. // Matrix 2x2
  47966. for (name in this._matrices2x2) {
  47967. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47968. }
  47969. // Vector2Array
  47970. for (name in this._vectors2Arrays) {
  47971. this._effect.setArray2(name, this._vectors2Arrays[name]);
  47972. }
  47973. // Vector3Array
  47974. for (name in this._vectors3Arrays) {
  47975. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47976. }
  47977. }
  47978. this._afterBind(mesh);
  47979. };
  47980. ShaderMaterial.prototype.getActiveTextures = function () {
  47981. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47982. for (var name in this._textures) {
  47983. activeTextures.push(this._textures[name]);
  47984. }
  47985. for (var name in this._textureArrays) {
  47986. var array = this._textureArrays[name];
  47987. for (var index = 0; index < array.length; index++) {
  47988. activeTextures.push(array[index]);
  47989. }
  47990. }
  47991. return activeTextures;
  47992. };
  47993. ShaderMaterial.prototype.hasTexture = function (texture) {
  47994. if (_super.prototype.hasTexture.call(this, texture)) {
  47995. return true;
  47996. }
  47997. for (var name in this._textures) {
  47998. if (this._textures[name] === texture) {
  47999. return true;
  48000. }
  48001. }
  48002. for (var name in this._textureArrays) {
  48003. var array = this._textureArrays[name];
  48004. for (var index = 0; index < array.length; index++) {
  48005. if (array[index] === texture) {
  48006. return true;
  48007. }
  48008. }
  48009. }
  48010. return false;
  48011. };
  48012. ShaderMaterial.prototype.clone = function (name) {
  48013. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48014. return newShaderMaterial;
  48015. };
  48016. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48017. if (forceDisposeTextures) {
  48018. var name;
  48019. for (name in this._textures) {
  48020. this._textures[name].dispose();
  48021. }
  48022. for (name in this._textureArrays) {
  48023. var array = this._textureArrays[name];
  48024. for (var index = 0; index < array.length; index++) {
  48025. array[index].dispose();
  48026. }
  48027. }
  48028. }
  48029. this._textures = {};
  48030. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48031. };
  48032. ShaderMaterial.prototype.serialize = function () {
  48033. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48034. serializationObject.customType = "BABYLON.ShaderMaterial";
  48035. serializationObject.options = this._options;
  48036. serializationObject.shaderPath = this._shaderPath;
  48037. var name;
  48038. // Texture
  48039. serializationObject.textures = {};
  48040. for (name in this._textures) {
  48041. serializationObject.textures[name] = this._textures[name].serialize();
  48042. }
  48043. // Texture arrays
  48044. serializationObject.textureArrays = {};
  48045. for (name in this._textureArrays) {
  48046. serializationObject.textureArrays[name] = [];
  48047. var array = this._textureArrays[name];
  48048. for (var index = 0; index < array.length; index++) {
  48049. serializationObject.textureArrays[name].push(array[index].serialize());
  48050. }
  48051. }
  48052. // Float
  48053. serializationObject.floats = {};
  48054. for (name in this._floats) {
  48055. serializationObject.floats[name] = this._floats[name];
  48056. }
  48057. // Float s
  48058. serializationObject.FloatArrays = {};
  48059. for (name in this._floatsArrays) {
  48060. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48061. }
  48062. // Color3
  48063. serializationObject.colors3 = {};
  48064. for (name in this._colors3) {
  48065. serializationObject.colors3[name] = this._colors3[name].asArray();
  48066. }
  48067. // Color3 array
  48068. serializationObject.colors3Arrays = {};
  48069. for (name in this._colors3Arrays) {
  48070. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48071. }
  48072. // Color4
  48073. serializationObject.colors4 = {};
  48074. for (name in this._colors4) {
  48075. serializationObject.colors4[name] = this._colors4[name].asArray();
  48076. }
  48077. // Vector2
  48078. serializationObject.vectors2 = {};
  48079. for (name in this._vectors2) {
  48080. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48081. }
  48082. // Vector3
  48083. serializationObject.vectors3 = {};
  48084. for (name in this._vectors3) {
  48085. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48086. }
  48087. // Vector4
  48088. serializationObject.vectors4 = {};
  48089. for (name in this._vectors4) {
  48090. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48091. }
  48092. // Matrix
  48093. serializationObject.matrices = {};
  48094. for (name in this._matrices) {
  48095. serializationObject.matrices[name] = this._matrices[name].asArray();
  48096. }
  48097. // Matrix 3x3
  48098. serializationObject.matrices3x3 = {};
  48099. for (name in this._matrices3x3) {
  48100. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48101. }
  48102. // Matrix 2x2
  48103. serializationObject.matrices2x2 = {};
  48104. for (name in this._matrices2x2) {
  48105. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48106. }
  48107. // Vector2Array
  48108. serializationObject.vectors2Arrays = {};
  48109. for (name in this._vectors2Arrays) {
  48110. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48111. }
  48112. // Vector3Array
  48113. serializationObject.vectors3Arrays = {};
  48114. for (name in this._vectors3Arrays) {
  48115. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48116. }
  48117. return serializationObject;
  48118. };
  48119. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48120. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48121. var name;
  48122. // Texture
  48123. for (name in source.textures) {
  48124. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48125. }
  48126. // Texture arrays
  48127. for (name in source.textureArrays) {
  48128. var array = source.textureArrays[name];
  48129. var textureArray = new Array();
  48130. for (var index = 0; index < array.length; index++) {
  48131. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48132. }
  48133. material.setTextureArray(name, textureArray);
  48134. }
  48135. // Float
  48136. for (name in source.floats) {
  48137. material.setFloat(name, source.floats[name]);
  48138. }
  48139. // Float s
  48140. for (name in source.floatsArrays) {
  48141. material.setFloats(name, source.floatsArrays[name]);
  48142. }
  48143. // Color3
  48144. for (name in source.colors3) {
  48145. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48146. }
  48147. // Color3 arrays
  48148. for (name in source.colors3Arrays) {
  48149. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48150. if (i % 3 === 0) {
  48151. arr.push([num]);
  48152. }
  48153. else {
  48154. arr[arr.length - 1].push(num);
  48155. }
  48156. return arr;
  48157. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48158. material.setColor3Array(name, colors);
  48159. }
  48160. // Color4
  48161. for (name in source.colors4) {
  48162. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48163. }
  48164. // Vector2
  48165. for (name in source.vectors2) {
  48166. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48167. }
  48168. // Vector3
  48169. for (name in source.vectors3) {
  48170. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48171. }
  48172. // Vector4
  48173. for (name in source.vectors4) {
  48174. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48175. }
  48176. // Matrix
  48177. for (name in source.matrices) {
  48178. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48179. }
  48180. // Matrix 3x3
  48181. for (name in source.matrices3x3) {
  48182. material.setMatrix3x3(name, source.matrices3x3[name]);
  48183. }
  48184. // Matrix 2x2
  48185. for (name in source.matrices2x2) {
  48186. material.setMatrix2x2(name, source.matrices2x2[name]);
  48187. }
  48188. // Vector2Array
  48189. for (name in source.vectors2Arrays) {
  48190. material.setArray2(name, source.vectors2Arrays[name]);
  48191. }
  48192. // Vector3Array
  48193. for (name in source.vectors3Arrays) {
  48194. material.setArray3(name, source.vectors3Arrays[name]);
  48195. }
  48196. return material;
  48197. };
  48198. return ShaderMaterial;
  48199. }(BABYLON.Material));
  48200. BABYLON.ShaderMaterial = ShaderMaterial;
  48201. })(BABYLON || (BABYLON = {}));
  48202. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48203. var BABYLON;
  48204. (function (BABYLON) {
  48205. var MeshBuilder = /** @class */ (function () {
  48206. function MeshBuilder() {
  48207. }
  48208. MeshBuilder.updateSideOrientation = function (orientation) {
  48209. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  48210. return BABYLON.Mesh.DOUBLESIDE;
  48211. }
  48212. if (orientation === undefined || orientation === null) {
  48213. return BABYLON.Mesh.FRONTSIDE;
  48214. }
  48215. return orientation;
  48216. };
  48217. /**
  48218. * Creates a box mesh.
  48219. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  48220. * The parameter `size` sets the size (float) of each box side (default 1).
  48221. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  48222. * 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).
  48223. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48225. * 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).
  48226. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48228. */
  48229. MeshBuilder.CreateBox = function (name, options, scene) {
  48230. if (scene === void 0) { scene = null; }
  48231. var box = new BABYLON.Mesh(name, scene);
  48232. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48233. box._originalBuilderSideOrientation = options.sideOrientation;
  48234. var vertexData = BABYLON.VertexData.CreateBox(options);
  48235. vertexData.applyToMesh(box, options.updatable);
  48236. return box;
  48237. };
  48238. /**
  48239. * Creates a sphere mesh.
  48240. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  48241. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  48242. * 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`).
  48243. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  48244. * 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
  48245. * 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).
  48246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48247. * 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).
  48248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48250. */
  48251. MeshBuilder.CreateSphere = function (name, options, scene) {
  48252. var sphere = new BABYLON.Mesh(name, scene);
  48253. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48254. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48255. var vertexData = BABYLON.VertexData.CreateSphere(options);
  48256. vertexData.applyToMesh(sphere, options.updatable);
  48257. return sphere;
  48258. };
  48259. /**
  48260. * Creates a plane polygonal mesh. By default, this is a disc.
  48261. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  48262. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  48263. * 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.
  48264. * 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
  48265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48266. * 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).
  48267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48269. */
  48270. MeshBuilder.CreateDisc = function (name, options, scene) {
  48271. if (scene === void 0) { scene = null; }
  48272. var disc = new BABYLON.Mesh(name, scene);
  48273. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48274. disc._originalBuilderSideOrientation = options.sideOrientation;
  48275. var vertexData = BABYLON.VertexData.CreateDisc(options);
  48276. vertexData.applyToMesh(disc, options.updatable);
  48277. return disc;
  48278. };
  48279. /**
  48280. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  48281. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  48282. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  48283. * 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`).
  48284. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  48285. * 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.
  48286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48287. * 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).
  48288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48290. */
  48291. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  48292. var sphere = new BABYLON.Mesh(name, scene);
  48293. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48294. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48295. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  48296. vertexData.applyToMesh(sphere, options.updatable);
  48297. return sphere;
  48298. };
  48299. ;
  48300. /**
  48301. * Creates a ribbon mesh.
  48302. * 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.
  48303. *
  48304. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  48305. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  48306. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  48307. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  48308. * 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.
  48309. * 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.
  48310. * 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
  48311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48312. * 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).
  48313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48314. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48315. * 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.
  48316. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  48317. * 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
  48318. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  48319. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  48320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48321. */
  48322. MeshBuilder.CreateRibbon = function (name, options, scene) {
  48323. if (scene === void 0) { scene = null; }
  48324. var pathArray = options.pathArray;
  48325. var closeArray = options.closeArray;
  48326. var closePath = options.closePath;
  48327. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48328. var instance = options.instance;
  48329. var updatable = options.updatable;
  48330. if (instance) {
  48331. // positionFunction : ribbon case
  48332. // only pathArray and sideOrientation parameters are taken into account for positions update
  48333. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  48334. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  48335. var positionFunction = function (positions) {
  48336. var minlg = pathArray[0].length;
  48337. var i = 0;
  48338. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  48339. for (var si = 1; si <= ns; si++) {
  48340. for (var p = 0; p < pathArray.length; p++) {
  48341. var path = pathArray[p];
  48342. var l = path.length;
  48343. minlg = (minlg < l) ? minlg : l;
  48344. var j = 0;
  48345. while (j < minlg) {
  48346. positions[i] = path[j].x;
  48347. positions[i + 1] = path[j].y;
  48348. positions[i + 2] = path[j].z;
  48349. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  48350. BABYLON.Tmp.Vector3[0].x = path[j].x;
  48351. }
  48352. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  48353. BABYLON.Tmp.Vector3[1].x = path[j].x;
  48354. }
  48355. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  48356. BABYLON.Tmp.Vector3[0].y = path[j].y;
  48357. }
  48358. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  48359. BABYLON.Tmp.Vector3[1].y = path[j].y;
  48360. }
  48361. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  48362. BABYLON.Tmp.Vector3[0].z = path[j].z;
  48363. }
  48364. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  48365. BABYLON.Tmp.Vector3[1].z = path[j].z;
  48366. }
  48367. j++;
  48368. i += 3;
  48369. }
  48370. if (instance._closePath) {
  48371. positions[i] = path[0].x;
  48372. positions[i + 1] = path[0].y;
  48373. positions[i + 2] = path[0].z;
  48374. i += 3;
  48375. }
  48376. }
  48377. }
  48378. };
  48379. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48380. positionFunction(positions);
  48381. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48382. instance._boundingInfo.update(instance._worldMatrix);
  48383. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48384. if (options.colors) {
  48385. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48386. for (var c = 0; c < options.colors.length; c++) {
  48387. colors[c * 4] = options.colors[c].r;
  48388. colors[c * 4 + 1] = options.colors[c].g;
  48389. colors[c * 4 + 2] = options.colors[c].b;
  48390. colors[c * 4 + 3] = options.colors[c].a;
  48391. }
  48392. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48393. }
  48394. if (options.uvs) {
  48395. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48396. for (var i = 0; i < options.uvs.length; i++) {
  48397. uvs[i * 2] = options.uvs[i].x;
  48398. uvs[i * 2 + 1] = options.uvs[i].y;
  48399. }
  48400. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48401. }
  48402. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48403. var indices = instance.getIndices();
  48404. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48405. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48406. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48407. if (instance._closePath) {
  48408. var indexFirst = 0;
  48409. var indexLast = 0;
  48410. for (var p = 0; p < pathArray.length; p++) {
  48411. indexFirst = instance._idx[p] * 3;
  48412. if (p + 1 < pathArray.length) {
  48413. indexLast = (instance._idx[p + 1] - 1) * 3;
  48414. }
  48415. else {
  48416. indexLast = normals.length - 3;
  48417. }
  48418. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  48419. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  48420. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  48421. normals[indexLast] = normals[indexFirst];
  48422. normals[indexLast + 1] = normals[indexFirst + 1];
  48423. normals[indexLast + 2] = normals[indexFirst + 2];
  48424. }
  48425. }
  48426. if (!(instance.areNormalsFrozen)) {
  48427. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  48428. }
  48429. }
  48430. return instance;
  48431. }
  48432. else {
  48433. var ribbon = new BABYLON.Mesh(name, scene);
  48434. ribbon._originalBuilderSideOrientation = sideOrientation;
  48435. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  48436. if (closePath) {
  48437. ribbon._idx = vertexData._idx;
  48438. }
  48439. ribbon._closePath = closePath;
  48440. ribbon._closeArray = closeArray;
  48441. vertexData.applyToMesh(ribbon, updatable);
  48442. return ribbon;
  48443. }
  48444. };
  48445. /**
  48446. * Creates a cylinder or a cone mesh.
  48447. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48448. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48449. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48450. * 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.
  48451. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48452. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48453. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48454. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48455. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48456. * 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).
  48457. * 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
  48458. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48459. * 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
  48460. * 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.
  48461. * If `enclose` is false, a ring surface is one element.
  48462. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48463. * 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
  48464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48465. * 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).
  48466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48468. */
  48469. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48470. var cylinder = new BABYLON.Mesh(name, scene);
  48471. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48472. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48473. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48474. vertexData.applyToMesh(cylinder, options.updatable);
  48475. return cylinder;
  48476. };
  48477. /**
  48478. * Creates a torus mesh.
  48479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48480. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48481. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48482. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48484. * 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).
  48485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48487. */
  48488. MeshBuilder.CreateTorus = function (name, options, scene) {
  48489. var torus = new BABYLON.Mesh(name, scene);
  48490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48491. torus._originalBuilderSideOrientation = options.sideOrientation;
  48492. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48493. vertexData.applyToMesh(torus, options.updatable);
  48494. return torus;
  48495. };
  48496. /**
  48497. * Creates a torus knot mesh.
  48498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48499. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48500. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48501. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48502. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48504. * 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).
  48505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48507. */
  48508. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48509. var torusKnot = new BABYLON.Mesh(name, scene);
  48510. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48511. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48512. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48513. vertexData.applyToMesh(torusKnot, options.updatable);
  48514. return torusKnot;
  48515. };
  48516. /**
  48517. * Creates a line system mesh.
  48518. * A line system is a pool of many lines gathered in a single mesh.
  48519. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48520. * 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.
  48521. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48522. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48523. * 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
  48524. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48525. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48526. * 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
  48527. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48529. */
  48530. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48531. var instance = options.instance;
  48532. var lines = options.lines;
  48533. var colors = options.colors;
  48534. if (instance) {
  48535. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48536. var vertexColor;
  48537. var lineColors;
  48538. if (colors) {
  48539. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48540. }
  48541. var i = 0;
  48542. var c = 0;
  48543. for (var l = 0; l < lines.length; l++) {
  48544. var points = lines[l];
  48545. for (var p = 0; p < points.length; p++) {
  48546. positions[i] = points[p].x;
  48547. positions[i + 1] = points[p].y;
  48548. positions[i + 2] = points[p].z;
  48549. if (colors && vertexColor) {
  48550. lineColors = colors[l];
  48551. vertexColor[c] = lineColors[p].r;
  48552. vertexColor[c + 1] = lineColors[p].g;
  48553. vertexColor[c + 2] = lineColors[p].b;
  48554. vertexColor[c + 3] = lineColors[p].a;
  48555. c += 4;
  48556. }
  48557. i += 3;
  48558. }
  48559. }
  48560. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48561. if (colors && vertexColor) {
  48562. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48563. }
  48564. return instance;
  48565. }
  48566. // line system creation
  48567. var useVertexColor = (colors) ? true : false;
  48568. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48569. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48570. vertexData.applyToMesh(lineSystem, options.updatable);
  48571. return lineSystem;
  48572. };
  48573. /**
  48574. * Creates a line mesh.
  48575. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48576. * 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.
  48577. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48578. * The parameter `points` is an array successive Vector3.
  48579. * 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
  48580. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48581. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48582. * When updating an instance, remember that only point positions can change, not the number of points.
  48583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48584. */
  48585. MeshBuilder.CreateLines = function (name, options, scene) {
  48586. if (scene === void 0) { scene = null; }
  48587. var colors = (options.colors) ? [options.colors] : null;
  48588. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48589. return lines;
  48590. };
  48591. /**
  48592. * Creates a dashed line mesh.
  48593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48594. * 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.
  48595. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48596. * The parameter `points` is an array successive Vector3.
  48597. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48598. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48599. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48600. * 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
  48601. * When updating an instance, remember that only point positions can change, not the number of points.
  48602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48603. */
  48604. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48605. if (scene === void 0) { scene = null; }
  48606. var points = options.points;
  48607. var instance = options.instance;
  48608. var gapSize = options.gapSize || 1;
  48609. var dashSize = options.dashSize || 3;
  48610. if (instance) {
  48611. var positionFunction = function (positions) {
  48612. var curvect = BABYLON.Vector3.Zero();
  48613. var nbSeg = positions.length / 6;
  48614. var lg = 0;
  48615. var nb = 0;
  48616. var shft = 0;
  48617. var dashshft = 0;
  48618. var curshft = 0;
  48619. var p = 0;
  48620. var i = 0;
  48621. var j = 0;
  48622. for (i = 0; i < points.length - 1; i++) {
  48623. points[i + 1].subtractToRef(points[i], curvect);
  48624. lg += curvect.length();
  48625. }
  48626. shft = lg / nbSeg;
  48627. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48628. for (i = 0; i < points.length - 1; i++) {
  48629. points[i + 1].subtractToRef(points[i], curvect);
  48630. nb = Math.floor(curvect.length() / shft);
  48631. curvect.normalize();
  48632. j = 0;
  48633. while (j < nb && p < positions.length) {
  48634. curshft = shft * j;
  48635. positions[p] = points[i].x + curshft * curvect.x;
  48636. positions[p + 1] = points[i].y + curshft * curvect.y;
  48637. positions[p + 2] = points[i].z + curshft * curvect.z;
  48638. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48639. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48640. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48641. p += 6;
  48642. j++;
  48643. }
  48644. }
  48645. while (p < positions.length) {
  48646. positions[p] = points[i].x;
  48647. positions[p + 1] = points[i].y;
  48648. positions[p + 2] = points[i].z;
  48649. p += 3;
  48650. }
  48651. };
  48652. instance.updateMeshPositions(positionFunction, false);
  48653. return instance;
  48654. }
  48655. // dashed lines creation
  48656. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48657. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48658. vertexData.applyToMesh(dashedLines, options.updatable);
  48659. dashedLines.dashSize = dashSize;
  48660. dashedLines.gapSize = gapSize;
  48661. return dashedLines;
  48662. };
  48663. /**
  48664. * Creates an extruded shape mesh.
  48665. * 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.
  48666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48667. *
  48668. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48669. * 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
  48670. * extruded along the Z axis.
  48671. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48672. * 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.
  48673. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48674. * 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
  48675. * 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
  48676. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48678. * 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).
  48679. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48680. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48682. */
  48683. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48684. if (scene === void 0) { scene = null; }
  48685. var path = options.path;
  48686. var shape = options.shape;
  48687. var scale = options.scale || 1;
  48688. var rotation = options.rotation || 0;
  48689. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48690. var updatable = options.updatable;
  48691. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48692. var instance = options.instance || null;
  48693. var invertUV = options.invertUV || false;
  48694. 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);
  48695. };
  48696. /**
  48697. * Creates an custom extruded shape mesh.
  48698. * 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.
  48699. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48700. *
  48701. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48702. * 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
  48703. * extruded along the Z axis.
  48704. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48705. * 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
  48706. * and the distance of this point from the begining of the path :
  48707. * ```javascript
  48708. * var rotationFunction = function(i, distance) {
  48709. * // do things
  48710. * return rotationValue; }
  48711. * ```
  48712. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48713. * 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
  48714. * and the distance of this point from the begining of the path :
  48715. * ```javascript
  48716. * var scaleFunction = function(i, distance) {
  48717. * // do things
  48718. * return scaleValue;}
  48719. * ```
  48720. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48721. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48722. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48723. * 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
  48724. * 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
  48725. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48727. * 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).
  48728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48729. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48731. */
  48732. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48733. var path = options.path;
  48734. var shape = options.shape;
  48735. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48736. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48737. var ribbonCloseArray = options.ribbonCloseArray || false;
  48738. var ribbonClosePath = options.ribbonClosePath || false;
  48739. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48740. var updatable = options.updatable;
  48741. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48742. var instance = options.instance;
  48743. var invertUV = options.invertUV || false;
  48744. 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);
  48745. };
  48746. /**
  48747. * Creates lathe mesh.
  48748. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48750. *
  48751. * 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
  48752. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48753. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48754. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48755. * 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.
  48756. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48757. * 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
  48758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48759. * 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).
  48760. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48761. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48763. */
  48764. MeshBuilder.CreateLathe = function (name, options, scene) {
  48765. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48766. var closed = (options.closed === undefined) ? true : options.closed;
  48767. var shape = options.shape;
  48768. var radius = options.radius || 1;
  48769. var tessellation = options.tessellation || 64;
  48770. var updatable = options.updatable;
  48771. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48772. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48773. var pi2 = Math.PI * 2;
  48774. var paths = new Array();
  48775. var invertUV = options.invertUV || false;
  48776. var i = 0;
  48777. var p = 0;
  48778. var step = pi2 / tessellation * arc;
  48779. var rotated;
  48780. var path = new Array();
  48781. ;
  48782. for (i = 0; i <= tessellation; i++) {
  48783. var path = [];
  48784. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48785. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48786. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48787. }
  48788. for (p = 0; p < shape.length; p++) {
  48789. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48790. path.push(rotated);
  48791. }
  48792. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48793. 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));
  48794. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48795. }
  48796. paths.push(path);
  48797. }
  48798. // lathe ribbon
  48799. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48800. return lathe;
  48801. };
  48802. /**
  48803. * Creates a plane mesh.
  48804. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48805. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48806. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48807. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48808. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48809. * 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).
  48810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48812. */
  48813. MeshBuilder.CreatePlane = function (name, options, scene) {
  48814. var plane = new BABYLON.Mesh(name, scene);
  48815. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48816. plane._originalBuilderSideOrientation = options.sideOrientation;
  48817. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48818. vertexData.applyToMesh(plane, options.updatable);
  48819. if (options.sourcePlane) {
  48820. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48821. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48822. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48823. plane.rotate(vectorProduct, product);
  48824. }
  48825. return plane;
  48826. };
  48827. /**
  48828. * Creates a ground mesh.
  48829. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48830. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48831. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48833. */
  48834. MeshBuilder.CreateGround = function (name, options, scene) {
  48835. var ground = new BABYLON.GroundMesh(name, scene);
  48836. ground._setReady(false);
  48837. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48838. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48839. ground._width = options.width || 1;
  48840. ground._height = options.height || 1;
  48841. ground._maxX = ground._width / 2;
  48842. ground._maxZ = ground._height / 2;
  48843. ground._minX = -ground._maxX;
  48844. ground._minZ = -ground._maxZ;
  48845. var vertexData = BABYLON.VertexData.CreateGround(options);
  48846. vertexData.applyToMesh(ground, options.updatable);
  48847. ground._setReady(true);
  48848. return ground;
  48849. };
  48850. /**
  48851. * Creates a tiled ground mesh.
  48852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48853. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48854. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48855. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48856. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48857. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48858. * numbers of subdivisions on the ground width and height of each tile.
  48859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48860. */
  48861. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48862. var tiledGround = new BABYLON.Mesh(name, scene);
  48863. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48864. vertexData.applyToMesh(tiledGround, options.updatable);
  48865. return tiledGround;
  48866. };
  48867. /**
  48868. * Creates a ground mesh from a height map.
  48869. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48871. * The parameter `url` sets the URL of the height map image resource.
  48872. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48873. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48874. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48875. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48876. * 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.
  48877. * 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).
  48878. * This function is passed the newly built mesh :
  48879. * ```javascript
  48880. * function(mesh) { // do things
  48881. * return; }
  48882. * ```
  48883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48884. */
  48885. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48886. var width = options.width || 10.0;
  48887. var height = options.height || 10.0;
  48888. var subdivisions = options.subdivisions || 1 | 0;
  48889. var minHeight = options.minHeight || 0.0;
  48890. var maxHeight = options.maxHeight || 1.0;
  48891. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48892. var updatable = options.updatable;
  48893. var onReady = options.onReady;
  48894. var ground = new BABYLON.GroundMesh(name, scene);
  48895. ground._subdivisionsX = subdivisions;
  48896. ground._subdivisionsY = subdivisions;
  48897. ground._width = width;
  48898. ground._height = height;
  48899. ground._maxX = ground._width / 2.0;
  48900. ground._maxZ = ground._height / 2.0;
  48901. ground._minX = -ground._maxX;
  48902. ground._minZ = -ground._maxZ;
  48903. ground._setReady(false);
  48904. var onload = function (img) {
  48905. // Getting height map data
  48906. var canvas = document.createElement("canvas");
  48907. var context = canvas.getContext("2d");
  48908. if (!context) {
  48909. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48910. }
  48911. var bufferWidth = img.width;
  48912. var bufferHeight = img.height;
  48913. canvas.width = bufferWidth;
  48914. canvas.height = bufferHeight;
  48915. context.drawImage(img, 0, 0);
  48916. // Create VertexData from map data
  48917. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48918. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48919. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48920. width: width, height: height,
  48921. subdivisions: subdivisions,
  48922. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48923. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48924. });
  48925. vertexData.applyToMesh(ground, updatable);
  48926. ground._setReady(true);
  48927. //execute ready callback, if set
  48928. if (onReady) {
  48929. onReady(ground);
  48930. }
  48931. };
  48932. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48933. return ground;
  48934. };
  48935. /**
  48936. * Creates a polygon mesh.
  48937. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48938. * 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.
  48939. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48941. * 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).
  48942. * Remember you can only change the shape positions, not their number when updating a polygon.
  48943. */
  48944. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48945. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48946. var shape = options.shape;
  48947. var holes = options.holes || [];
  48948. var depth = options.depth || 0;
  48949. var contours = [];
  48950. var hole = [];
  48951. for (var i = 0; i < shape.length; i++) {
  48952. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48953. }
  48954. var epsilon = 0.00000001;
  48955. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48956. contours.pop();
  48957. }
  48958. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48959. for (var hNb = 0; hNb < holes.length; hNb++) {
  48960. hole = [];
  48961. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48962. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48963. }
  48964. polygonTriangulation.addHole(hole);
  48965. }
  48966. var polygon = polygonTriangulation.build(options.updatable, depth);
  48967. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48968. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48969. vertexData.applyToMesh(polygon, options.updatable);
  48970. return polygon;
  48971. };
  48972. ;
  48973. /**
  48974. * Creates an extruded polygon mesh, with depth in the Y direction.
  48975. * 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).
  48976. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48977. */
  48978. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48979. return MeshBuilder.CreatePolygon(name, options, scene);
  48980. };
  48981. ;
  48982. /**
  48983. * Creates a tube mesh.
  48984. * 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.
  48985. *
  48986. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48987. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48988. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48989. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48990. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48991. * 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.
  48992. * It must return a radius value (positive float) :
  48993. * ```javascript
  48994. * var radiusFunction = function(i, distance) {
  48995. * // do things
  48996. * return radius; }
  48997. * ```
  48998. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48999. * 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
  49000. * 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
  49001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49002. * 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).
  49003. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49004. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49006. */
  49007. MeshBuilder.CreateTube = function (name, options, scene) {
  49008. var path = options.path;
  49009. var instance = options.instance;
  49010. var radius = 1.0;
  49011. if (instance) {
  49012. radius = instance.radius;
  49013. }
  49014. if (options.radius !== undefined) {
  49015. radius = options.radius;
  49016. }
  49017. ;
  49018. var tessellation = options.tessellation || 64 | 0;
  49019. var radiusFunction = options.radiusFunction || null;
  49020. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49021. var invertUV = options.invertUV || false;
  49022. var updatable = options.updatable;
  49023. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49024. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49025. // tube geometry
  49026. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49027. var tangents = path3D.getTangents();
  49028. var normals = path3D.getNormals();
  49029. var distances = path3D.getDistances();
  49030. var pi2 = Math.PI * 2;
  49031. var step = pi2 / tessellation * arc;
  49032. var returnRadius = function () { return radius; };
  49033. var radiusFunctionFinal = radiusFunction || returnRadius;
  49034. var circlePath;
  49035. var rad;
  49036. var normal;
  49037. var rotated;
  49038. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49039. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49040. for (var i = 0; i < path.length; i++) {
  49041. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49042. circlePath = Array(); // current circle array
  49043. normal = normals[i]; // current normal
  49044. for (var t = 0; t < tessellation; t++) {
  49045. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49046. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49047. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49048. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49049. circlePath[t] = rotated;
  49050. }
  49051. circlePaths[index] = circlePath;
  49052. index++;
  49053. }
  49054. // cap
  49055. var capPath = function (nbPoints, pathIndex) {
  49056. var pointCap = Array();
  49057. for (var i = 0; i < nbPoints; i++) {
  49058. pointCap.push(path[pathIndex]);
  49059. }
  49060. return pointCap;
  49061. };
  49062. switch (cap) {
  49063. case BABYLON.Mesh.NO_CAP:
  49064. break;
  49065. case BABYLON.Mesh.CAP_START:
  49066. circlePaths[0] = capPath(tessellation, 0);
  49067. circlePaths[1] = circlePaths[2].slice(0);
  49068. break;
  49069. case BABYLON.Mesh.CAP_END:
  49070. circlePaths[index] = circlePaths[index - 1].slice(0);
  49071. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49072. break;
  49073. case BABYLON.Mesh.CAP_ALL:
  49074. circlePaths[0] = capPath(tessellation, 0);
  49075. circlePaths[1] = circlePaths[2].slice(0);
  49076. circlePaths[index] = circlePaths[index - 1].slice(0);
  49077. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49078. break;
  49079. default:
  49080. break;
  49081. }
  49082. return circlePaths;
  49083. };
  49084. var path3D;
  49085. var pathArray;
  49086. if (instance) {
  49087. var arc = options.arc || instance.arc;
  49088. path3D = (instance.path3D).update(path);
  49089. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  49090. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  49091. instance.path3D = path3D;
  49092. instance.pathArray = pathArray;
  49093. instance.arc = arc;
  49094. instance.radius = radius;
  49095. return instance;
  49096. }
  49097. // tube creation
  49098. path3D = new BABYLON.Path3D(path);
  49099. var newPathArray = new Array();
  49100. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49101. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  49102. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49103. tube.pathArray = pathArray;
  49104. tube.path3D = path3D;
  49105. tube.tessellation = tessellation;
  49106. tube.cap = cap;
  49107. tube.arc = options.arc;
  49108. tube.radius = radius;
  49109. return tube;
  49110. };
  49111. /**
  49112. * Creates a polyhedron mesh.
  49113. *
  49114. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  49115. * 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
  49116. * to choose the wanted type.
  49117. * The parameter `size` (positive float, default 1) sets the polygon size.
  49118. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  49119. * 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`.
  49120. * 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
  49121. * 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)`).
  49122. * 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
  49123. * 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.
  49124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49125. * 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).
  49126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49128. */
  49129. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  49130. var polyhedron = new BABYLON.Mesh(name, scene);
  49131. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49132. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  49133. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  49134. vertexData.applyToMesh(polyhedron, options.updatable);
  49135. return polyhedron;
  49136. };
  49137. /**
  49138. * Creates a decal mesh.
  49139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  49140. * 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.
  49141. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  49142. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  49143. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  49144. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  49145. */
  49146. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  49147. var indices = sourceMesh.getIndices();
  49148. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49149. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49150. var position = options.position || BABYLON.Vector3.Zero();
  49151. var normal = options.normal || BABYLON.Vector3.Up();
  49152. var size = options.size || BABYLON.Vector3.One();
  49153. var angle = options.angle || 0;
  49154. // Getting correct rotation
  49155. if (!normal) {
  49156. var target = new BABYLON.Vector3(0, 0, 1);
  49157. var camera = sourceMesh.getScene().activeCamera;
  49158. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  49159. normal = camera.globalPosition.subtract(cameraWorldTarget);
  49160. }
  49161. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  49162. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  49163. var pitch = Math.atan2(normal.y, len);
  49164. // Matrix
  49165. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  49166. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  49167. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  49168. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  49169. var vertexData = new BABYLON.VertexData();
  49170. vertexData.indices = [];
  49171. vertexData.positions = [];
  49172. vertexData.normals = [];
  49173. vertexData.uvs = [];
  49174. var currentVertexDataIndex = 0;
  49175. var extractDecalVector3 = function (indexId) {
  49176. var result = new BABYLON.PositionNormalVertex();
  49177. if (!indices || !positions || !normals) {
  49178. return result;
  49179. }
  49180. var vertexId = indices[indexId];
  49181. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  49182. // Send vector to decal local world
  49183. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  49184. // Get normal
  49185. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  49186. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  49187. return result;
  49188. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  49189. var clip = function (vertices, axis) {
  49190. if (vertices.length === 0) {
  49191. return vertices;
  49192. }
  49193. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  49194. var clipVertices = function (v0, v1) {
  49195. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  49196. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  49197. };
  49198. var result = new Array();
  49199. for (var index = 0; index < vertices.length; index += 3) {
  49200. var v1Out;
  49201. var v2Out;
  49202. var v3Out;
  49203. var total = 0;
  49204. var nV1 = null;
  49205. var nV2 = null;
  49206. var nV3 = null;
  49207. var nV4 = null;
  49208. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  49209. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  49210. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  49211. v1Out = d1 > 0;
  49212. v2Out = d2 > 0;
  49213. v3Out = d3 > 0;
  49214. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  49215. switch (total) {
  49216. case 0:
  49217. result.push(vertices[index]);
  49218. result.push(vertices[index + 1]);
  49219. result.push(vertices[index + 2]);
  49220. break;
  49221. case 1:
  49222. if (v1Out) {
  49223. nV1 = vertices[index + 1];
  49224. nV2 = vertices[index + 2];
  49225. nV3 = clipVertices(vertices[index], nV1);
  49226. nV4 = clipVertices(vertices[index], nV2);
  49227. }
  49228. if (v2Out) {
  49229. nV1 = vertices[index];
  49230. nV2 = vertices[index + 2];
  49231. nV3 = clipVertices(vertices[index + 1], nV1);
  49232. nV4 = clipVertices(vertices[index + 1], nV2);
  49233. result.push(nV3);
  49234. result.push(nV2.clone());
  49235. result.push(nV1.clone());
  49236. result.push(nV2.clone());
  49237. result.push(nV3.clone());
  49238. result.push(nV4);
  49239. break;
  49240. }
  49241. if (v3Out) {
  49242. nV1 = vertices[index];
  49243. nV2 = vertices[index + 1];
  49244. nV3 = clipVertices(vertices[index + 2], nV1);
  49245. nV4 = clipVertices(vertices[index + 2], nV2);
  49246. }
  49247. if (nV1 && nV2 && nV3 && nV4) {
  49248. result.push(nV1.clone());
  49249. result.push(nV2.clone());
  49250. result.push(nV3);
  49251. result.push(nV4);
  49252. result.push(nV3.clone());
  49253. result.push(nV2.clone());
  49254. }
  49255. break;
  49256. case 2:
  49257. if (!v1Out) {
  49258. nV1 = vertices[index].clone();
  49259. nV2 = clipVertices(nV1, vertices[index + 1]);
  49260. nV3 = clipVertices(nV1, vertices[index + 2]);
  49261. result.push(nV1);
  49262. result.push(nV2);
  49263. result.push(nV3);
  49264. }
  49265. if (!v2Out) {
  49266. nV1 = vertices[index + 1].clone();
  49267. nV2 = clipVertices(nV1, vertices[index + 2]);
  49268. nV3 = clipVertices(nV1, vertices[index]);
  49269. result.push(nV1);
  49270. result.push(nV2);
  49271. result.push(nV3);
  49272. }
  49273. if (!v3Out) {
  49274. nV1 = vertices[index + 2].clone();
  49275. nV2 = clipVertices(nV1, vertices[index]);
  49276. nV3 = clipVertices(nV1, vertices[index + 1]);
  49277. result.push(nV1);
  49278. result.push(nV2);
  49279. result.push(nV3);
  49280. }
  49281. break;
  49282. case 3:
  49283. break;
  49284. }
  49285. }
  49286. return result;
  49287. };
  49288. for (var index = 0; index < indices.length; index += 3) {
  49289. var faceVertices = new Array();
  49290. faceVertices.push(extractDecalVector3(index));
  49291. faceVertices.push(extractDecalVector3(index + 1));
  49292. faceVertices.push(extractDecalVector3(index + 2));
  49293. // Clip
  49294. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  49295. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  49296. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  49297. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  49298. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  49299. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  49300. if (faceVertices.length === 0) {
  49301. continue;
  49302. }
  49303. // Add UVs and get back to world
  49304. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  49305. var vertex = faceVertices[vIndex];
  49306. //TODO check for Int32Array | Uint32Array | Uint16Array
  49307. vertexData.indices.push(currentVertexDataIndex);
  49308. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  49309. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  49310. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  49311. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  49312. currentVertexDataIndex++;
  49313. }
  49314. }
  49315. // Return mesh
  49316. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  49317. vertexData.applyToMesh(decal);
  49318. decal.position = position.clone();
  49319. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  49320. return decal;
  49321. };
  49322. // Privates
  49323. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  49324. // extrusion geometry
  49325. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  49326. var tangents = path3D.getTangents();
  49327. var normals = path3D.getNormals();
  49328. var binormals = path3D.getBinormals();
  49329. var distances = path3D.getDistances();
  49330. var angle = 0;
  49331. var returnScale = function () { return scale !== null ? scale : 1; };
  49332. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  49333. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  49334. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  49335. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49336. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49337. for (var i = 0; i < curve.length; i++) {
  49338. var shapePath = new Array();
  49339. var angleStep = rotate(i, distances[i]);
  49340. var scaleRatio = scl(i, distances[i]);
  49341. for (var p = 0; p < shape.length; p++) {
  49342. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  49343. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  49344. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  49345. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  49346. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  49347. shapePath[p] = rotated;
  49348. }
  49349. shapePaths[index] = shapePath;
  49350. angle += angleStep;
  49351. index++;
  49352. }
  49353. // cap
  49354. var capPath = function (shapePath) {
  49355. var pointCap = Array();
  49356. var barycenter = BABYLON.Vector3.Zero();
  49357. var i;
  49358. for (i = 0; i < shapePath.length; i++) {
  49359. barycenter.addInPlace(shapePath[i]);
  49360. }
  49361. barycenter.scaleInPlace(1.0 / shapePath.length);
  49362. for (i = 0; i < shapePath.length; i++) {
  49363. pointCap.push(barycenter);
  49364. }
  49365. return pointCap;
  49366. };
  49367. switch (cap) {
  49368. case BABYLON.Mesh.NO_CAP:
  49369. break;
  49370. case BABYLON.Mesh.CAP_START:
  49371. shapePaths[0] = capPath(shapePaths[2]);
  49372. shapePaths[1] = shapePaths[2];
  49373. break;
  49374. case BABYLON.Mesh.CAP_END:
  49375. shapePaths[index] = shapePaths[index - 1];
  49376. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49377. break;
  49378. case BABYLON.Mesh.CAP_ALL:
  49379. shapePaths[0] = capPath(shapePaths[2]);
  49380. shapePaths[1] = shapePaths[2];
  49381. shapePaths[index] = shapePaths[index - 1];
  49382. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49383. break;
  49384. default:
  49385. break;
  49386. }
  49387. return shapePaths;
  49388. };
  49389. var path3D;
  49390. var pathArray;
  49391. if (instance) {
  49392. path3D = (instance.path3D).update(curve);
  49393. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49394. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49395. return instance;
  49396. }
  49397. // extruded shape creation
  49398. path3D = new BABYLON.Path3D(curve);
  49399. var newShapePaths = new Array();
  49400. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49401. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49402. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49403. extrudedGeneric.pathArray = pathArray;
  49404. extrudedGeneric.path3D = path3D;
  49405. extrudedGeneric.cap = cap;
  49406. return extrudedGeneric;
  49407. };
  49408. return MeshBuilder;
  49409. }());
  49410. BABYLON.MeshBuilder = MeshBuilder;
  49411. })(BABYLON || (BABYLON = {}));
  49412. //# sourceMappingURL=babylon.meshBuilder.js.map
  49413. var BABYLON;
  49414. (function (BABYLON) {
  49415. var AudioEngine = /** @class */ (function () {
  49416. function AudioEngine() {
  49417. this._audioContext = null;
  49418. this._audioContextInitialized = false;
  49419. this.canUseWebAudio = false;
  49420. this.WarnedWebAudioUnsupported = false;
  49421. this.unlocked = false;
  49422. this.isMP3supported = false;
  49423. this.isOGGsupported = false;
  49424. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  49425. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  49426. this.canUseWebAudio = true;
  49427. }
  49428. var audioElem = document.createElement('audio');
  49429. try {
  49430. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  49431. this.isMP3supported = true;
  49432. }
  49433. }
  49434. catch (e) {
  49435. // protect error during capability check.
  49436. }
  49437. try {
  49438. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  49439. this.isOGGsupported = true;
  49440. }
  49441. }
  49442. catch (e) {
  49443. // protect error during capability check.
  49444. }
  49445. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49446. this._unlockiOSaudio();
  49447. }
  49448. else {
  49449. this.unlocked = true;
  49450. }
  49451. }
  49452. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49453. get: function () {
  49454. if (!this._audioContextInitialized) {
  49455. this._initializeAudioContext();
  49456. }
  49457. return this._audioContext;
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. AudioEngine.prototype._unlockiOSaudio = function () {
  49463. var _this = this;
  49464. var unlockaudio = function () {
  49465. if (!_this.audioContext) {
  49466. return;
  49467. }
  49468. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49469. var source = _this.audioContext.createBufferSource();
  49470. source.buffer = buffer;
  49471. source.connect(_this.audioContext.destination);
  49472. source.start(0);
  49473. setTimeout(function () {
  49474. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49475. _this.unlocked = true;
  49476. window.removeEventListener('touchend', unlockaudio, false);
  49477. if (_this.onAudioUnlocked) {
  49478. _this.onAudioUnlocked();
  49479. }
  49480. }
  49481. }, 0);
  49482. };
  49483. window.addEventListener('touchend', unlockaudio, false);
  49484. };
  49485. AudioEngine.prototype._initializeAudioContext = function () {
  49486. try {
  49487. if (this.canUseWebAudio) {
  49488. this._audioContext = new AudioContext();
  49489. // create a global volume gain node
  49490. this.masterGain = this._audioContext.createGain();
  49491. this.masterGain.gain.value = 1;
  49492. this.masterGain.connect(this._audioContext.destination);
  49493. this._audioContextInitialized = true;
  49494. }
  49495. }
  49496. catch (e) {
  49497. this.canUseWebAudio = false;
  49498. BABYLON.Tools.Error("Web Audio: " + e.message);
  49499. }
  49500. };
  49501. AudioEngine.prototype.dispose = function () {
  49502. if (this.canUseWebAudio && this._audioContextInitialized) {
  49503. if (this._connectedAnalyser && this._audioContext) {
  49504. this._connectedAnalyser.stopDebugCanvas();
  49505. this._connectedAnalyser.dispose();
  49506. this.masterGain.disconnect();
  49507. this.masterGain.connect(this._audioContext.destination);
  49508. this._connectedAnalyser = null;
  49509. }
  49510. this.masterGain.gain.value = 1;
  49511. }
  49512. this.WarnedWebAudioUnsupported = false;
  49513. };
  49514. AudioEngine.prototype.getGlobalVolume = function () {
  49515. if (this.canUseWebAudio && this._audioContextInitialized) {
  49516. return this.masterGain.gain.value;
  49517. }
  49518. else {
  49519. return -1;
  49520. }
  49521. };
  49522. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49523. if (this.canUseWebAudio && this._audioContextInitialized) {
  49524. this.masterGain.gain.value = newVolume;
  49525. }
  49526. };
  49527. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49528. if (this._connectedAnalyser) {
  49529. this._connectedAnalyser.stopDebugCanvas();
  49530. }
  49531. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49532. this._connectedAnalyser = analyser;
  49533. this.masterGain.disconnect();
  49534. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49535. }
  49536. };
  49537. return AudioEngine;
  49538. }());
  49539. BABYLON.AudioEngine = AudioEngine;
  49540. })(BABYLON || (BABYLON = {}));
  49541. //# sourceMappingURL=babylon.audioEngine.js.map
  49542. var BABYLON;
  49543. (function (BABYLON) {
  49544. var Sound = /** @class */ (function () {
  49545. /**
  49546. * Create a sound and attach it to a scene
  49547. * @param name Name of your sound
  49548. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49549. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49550. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49551. */
  49552. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49553. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49554. var _this = this;
  49555. this.autoplay = false;
  49556. this.loop = false;
  49557. this.useCustomAttenuation = false;
  49558. this.spatialSound = false;
  49559. this.refDistance = 1;
  49560. this.rolloffFactor = 1;
  49561. this.maxDistance = 100;
  49562. this.distanceModel = "linear";
  49563. this._panningModel = "equalpower";
  49564. this._playbackRate = 1;
  49565. this._streaming = false;
  49566. this._startTime = 0;
  49567. this._startOffset = 0;
  49568. this._position = BABYLON.Vector3.Zero();
  49569. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49570. this._volume = 1;
  49571. this._isReadyToPlay = false;
  49572. this.isPlaying = false;
  49573. this.isPaused = false;
  49574. this._isDirectional = false;
  49575. // Used if you'd like to create a directional sound.
  49576. // If not set, the sound will be omnidirectional
  49577. this._coneInnerAngle = 360;
  49578. this._coneOuterAngle = 360;
  49579. this._coneOuterGain = 0;
  49580. this._isOutputConnected = false;
  49581. this._urlType = "Unknown";
  49582. this.name = name;
  49583. this._scene = scene;
  49584. this._readyToPlayCallback = readyToPlayCallback;
  49585. // Default custom attenuation function is a linear attenuation
  49586. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49587. if (currentDistance < maxDistance) {
  49588. return currentVolume * (1 - currentDistance / maxDistance);
  49589. }
  49590. else {
  49591. return 0;
  49592. }
  49593. };
  49594. if (options) {
  49595. this.autoplay = options.autoplay || false;
  49596. this.loop = options.loop || false;
  49597. // if volume === 0, we need another way to check this option
  49598. if (options.volume !== undefined) {
  49599. this._volume = options.volume;
  49600. }
  49601. this.spatialSound = options.spatialSound || false;
  49602. this.maxDistance = options.maxDistance || 100;
  49603. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49604. this.rolloffFactor = options.rolloffFactor || 1;
  49605. this.refDistance = options.refDistance || 1;
  49606. this.distanceModel = options.distanceModel || "linear";
  49607. this._playbackRate = options.playbackRate || 1;
  49608. this._streaming = options.streaming || false;
  49609. }
  49610. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49611. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49612. this._soundGain.gain.value = this._volume;
  49613. this._inputAudioNode = this._soundGain;
  49614. this._ouputAudioNode = this._soundGain;
  49615. if (this.spatialSound) {
  49616. this._createSpatialParameters();
  49617. }
  49618. this._scene.mainSoundTrack.AddSound(this);
  49619. var validParameter = true;
  49620. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49621. if (urlOrArrayBuffer) {
  49622. if (typeof (urlOrArrayBuffer) === "string")
  49623. this._urlType = "String";
  49624. if (Array.isArray(urlOrArrayBuffer))
  49625. this._urlType = "Array";
  49626. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49627. this._urlType = "ArrayBuffer";
  49628. var urls = [];
  49629. var codecSupportedFound = false;
  49630. switch (this._urlType) {
  49631. case "ArrayBuffer":
  49632. if (urlOrArrayBuffer.byteLength > 0) {
  49633. codecSupportedFound = true;
  49634. this._soundLoaded(urlOrArrayBuffer);
  49635. }
  49636. break;
  49637. case "String":
  49638. urls.push(urlOrArrayBuffer);
  49639. case "Array":
  49640. if (urls.length === 0)
  49641. urls = urlOrArrayBuffer;
  49642. // If we found a supported format, we load it immediately and stop the loop
  49643. for (var i = 0; i < urls.length; i++) {
  49644. var url = urls[i];
  49645. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49646. codecSupportedFound = true;
  49647. }
  49648. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49649. codecSupportedFound = true;
  49650. }
  49651. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49652. codecSupportedFound = true;
  49653. }
  49654. if (url.indexOf("blob:") !== -1) {
  49655. codecSupportedFound = true;
  49656. }
  49657. if (codecSupportedFound) {
  49658. // Loading sound using XHR2
  49659. if (!this._streaming) {
  49660. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49661. }
  49662. else {
  49663. this._htmlAudioElement = new Audio(url);
  49664. this._htmlAudioElement.controls = false;
  49665. this._htmlAudioElement.loop = this.loop;
  49666. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  49667. this._htmlAudioElement.preload = "auto";
  49668. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49669. _this._isReadyToPlay = true;
  49670. if (_this.autoplay) {
  49671. _this.play();
  49672. }
  49673. if (_this._readyToPlayCallback) {
  49674. _this._readyToPlayCallback();
  49675. }
  49676. });
  49677. document.body.appendChild(this._htmlAudioElement);
  49678. }
  49679. break;
  49680. }
  49681. }
  49682. break;
  49683. default:
  49684. validParameter = false;
  49685. break;
  49686. }
  49687. if (!validParameter) {
  49688. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49689. }
  49690. else {
  49691. if (!codecSupportedFound) {
  49692. this._isReadyToPlay = true;
  49693. // Simulating a ready to play event to avoid breaking code path
  49694. if (this._readyToPlayCallback) {
  49695. window.setTimeout(function () {
  49696. if (_this._readyToPlayCallback) {
  49697. _this._readyToPlayCallback();
  49698. }
  49699. }, 1000);
  49700. }
  49701. }
  49702. }
  49703. }
  49704. }
  49705. else {
  49706. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49707. this._scene.mainSoundTrack.AddSound(this);
  49708. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49709. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49710. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49711. }
  49712. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49713. if (this._readyToPlayCallback) {
  49714. window.setTimeout(function () {
  49715. if (_this._readyToPlayCallback) {
  49716. _this._readyToPlayCallback();
  49717. }
  49718. }, 1000);
  49719. }
  49720. }
  49721. }
  49722. Sound.prototype.dispose = function () {
  49723. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49724. if (this.isPlaying) {
  49725. this.stop();
  49726. }
  49727. this._isReadyToPlay = false;
  49728. if (this.soundTrackId === -1) {
  49729. this._scene.mainSoundTrack.RemoveSound(this);
  49730. }
  49731. else {
  49732. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49733. }
  49734. if (this._soundGain) {
  49735. this._soundGain.disconnect();
  49736. this._soundGain = null;
  49737. }
  49738. if (this._soundPanner) {
  49739. this._soundPanner.disconnect();
  49740. this._soundPanner = null;
  49741. }
  49742. if (this._soundSource) {
  49743. this._soundSource.disconnect();
  49744. this._soundSource = null;
  49745. }
  49746. this._audioBuffer = null;
  49747. if (this._htmlAudioElement) {
  49748. this._htmlAudioElement.pause();
  49749. this._htmlAudioElement.src = "";
  49750. document.body.removeChild(this._htmlAudioElement);
  49751. }
  49752. if (this._connectedMesh && this._registerFunc) {
  49753. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49754. this._connectedMesh = null;
  49755. }
  49756. }
  49757. };
  49758. Sound.prototype.isReady = function () {
  49759. return this._isReadyToPlay;
  49760. };
  49761. Sound.prototype._soundLoaded = function (audioData) {
  49762. var _this = this;
  49763. if (!BABYLON.Engine.audioEngine.audioContext) {
  49764. return;
  49765. }
  49766. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49767. _this._audioBuffer = buffer;
  49768. _this._isReadyToPlay = true;
  49769. if (_this.autoplay) {
  49770. _this.play();
  49771. }
  49772. if (_this._readyToPlayCallback) {
  49773. _this._readyToPlayCallback();
  49774. }
  49775. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49776. };
  49777. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49779. this._audioBuffer = audioBuffer;
  49780. this._isReadyToPlay = true;
  49781. }
  49782. };
  49783. Sound.prototype.updateOptions = function (options) {
  49784. if (options) {
  49785. this.loop = options.loop || this.loop;
  49786. this.maxDistance = options.maxDistance || this.maxDistance;
  49787. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49788. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49789. this.refDistance = options.refDistance || this.refDistance;
  49790. this.distanceModel = options.distanceModel || this.distanceModel;
  49791. this._playbackRate = options.playbackRate || this._playbackRate;
  49792. this._updateSpatialParameters();
  49793. if (this.isPlaying) {
  49794. if (this._streaming) {
  49795. this._htmlAudioElement.playbackRate = this._playbackRate;
  49796. }
  49797. else {
  49798. if (this._soundSource) {
  49799. this._soundSource.playbackRate.value = this._playbackRate;
  49800. }
  49801. }
  49802. }
  49803. }
  49804. };
  49805. Sound.prototype._createSpatialParameters = function () {
  49806. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49807. if (this._scene.headphone) {
  49808. this._panningModel = "HRTF";
  49809. }
  49810. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49811. this._updateSpatialParameters();
  49812. this._soundPanner.connect(this._ouputAudioNode);
  49813. this._inputAudioNode = this._soundPanner;
  49814. }
  49815. };
  49816. Sound.prototype._updateSpatialParameters = function () {
  49817. if (this.spatialSound && this._soundPanner) {
  49818. if (this.useCustomAttenuation) {
  49819. // Tricks to disable in a way embedded Web Audio attenuation
  49820. this._soundPanner.distanceModel = "linear";
  49821. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49822. this._soundPanner.refDistance = 1;
  49823. this._soundPanner.rolloffFactor = 1;
  49824. this._soundPanner.panningModel = this._panningModel;
  49825. }
  49826. else {
  49827. this._soundPanner.distanceModel = this.distanceModel;
  49828. this._soundPanner.maxDistance = this.maxDistance;
  49829. this._soundPanner.refDistance = this.refDistance;
  49830. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49831. this._soundPanner.panningModel = this._panningModel;
  49832. }
  49833. }
  49834. };
  49835. Sound.prototype.switchPanningModelToHRTF = function () {
  49836. this._panningModel = "HRTF";
  49837. this._switchPanningModel();
  49838. };
  49839. Sound.prototype.switchPanningModelToEqualPower = function () {
  49840. this._panningModel = "equalpower";
  49841. this._switchPanningModel();
  49842. };
  49843. Sound.prototype._switchPanningModel = function () {
  49844. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49845. this._soundPanner.panningModel = this._panningModel;
  49846. }
  49847. };
  49848. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49850. if (this._isOutputConnected) {
  49851. this._ouputAudioNode.disconnect();
  49852. }
  49853. this._ouputAudioNode.connect(soundTrackAudioNode);
  49854. this._isOutputConnected = true;
  49855. }
  49856. };
  49857. /**
  49858. * Transform this sound into a directional source
  49859. * @param coneInnerAngle Size of the inner cone in degree
  49860. * @param coneOuterAngle Size of the outer cone in degree
  49861. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49862. */
  49863. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49864. if (coneOuterAngle < coneInnerAngle) {
  49865. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49866. return;
  49867. }
  49868. this._coneInnerAngle = coneInnerAngle;
  49869. this._coneOuterAngle = coneOuterAngle;
  49870. this._coneOuterGain = coneOuterGain;
  49871. this._isDirectional = true;
  49872. if (this.isPlaying && this.loop) {
  49873. this.stop();
  49874. this.play();
  49875. }
  49876. };
  49877. Sound.prototype.setPosition = function (newPosition) {
  49878. this._position = newPosition;
  49879. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49880. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49881. }
  49882. };
  49883. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49884. this._localDirection = newLocalDirection;
  49885. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49886. this._updateDirection();
  49887. }
  49888. };
  49889. Sound.prototype._updateDirection = function () {
  49890. if (!this._connectedMesh || !this._soundPanner) {
  49891. return;
  49892. }
  49893. var mat = this._connectedMesh.getWorldMatrix();
  49894. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49895. direction.normalize();
  49896. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49897. };
  49898. Sound.prototype.updateDistanceFromListener = function () {
  49899. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49900. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49901. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49902. }
  49903. };
  49904. Sound.prototype.setAttenuationFunction = function (callback) {
  49905. this._customAttenuationFunction = callback;
  49906. };
  49907. /**
  49908. * Play the sound
  49909. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49910. * @param offset (optional) Start the sound setting it at a specific time
  49911. */
  49912. Sound.prototype.play = function (time, offset) {
  49913. var _this = this;
  49914. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49915. try {
  49916. if (this._startOffset < 0) {
  49917. time = -this._startOffset;
  49918. this._startOffset = 0;
  49919. }
  49920. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49921. if (!this._soundSource || !this._streamingSource) {
  49922. if (this.spatialSound && this._soundPanner) {
  49923. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49924. if (this._isDirectional) {
  49925. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49926. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49927. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49928. if (this._connectedMesh) {
  49929. this._updateDirection();
  49930. }
  49931. else {
  49932. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49933. }
  49934. }
  49935. }
  49936. }
  49937. if (this._streaming) {
  49938. if (!this._streamingSource) {
  49939. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49940. this._htmlAudioElement.onended = function () { _this._onended(); };
  49941. this._htmlAudioElement.playbackRate = this._playbackRate;
  49942. }
  49943. this._streamingSource.disconnect();
  49944. this._streamingSource.connect(this._inputAudioNode);
  49945. this._htmlAudioElement.play();
  49946. }
  49947. else {
  49948. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49949. this._soundSource.buffer = this._audioBuffer;
  49950. this._soundSource.connect(this._inputAudioNode);
  49951. this._soundSource.loop = this.loop;
  49952. this._soundSource.playbackRate.value = this._playbackRate;
  49953. this._soundSource.onended = function () { _this._onended(); };
  49954. if (this._soundSource.buffer) {
  49955. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49956. }
  49957. }
  49958. this._startTime = startTime;
  49959. this.isPlaying = true;
  49960. this.isPaused = false;
  49961. }
  49962. catch (ex) {
  49963. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49964. }
  49965. }
  49966. };
  49967. Sound.prototype._onended = function () {
  49968. this.isPlaying = false;
  49969. if (this.onended) {
  49970. this.onended();
  49971. }
  49972. };
  49973. /**
  49974. * Stop the sound
  49975. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49976. */
  49977. Sound.prototype.stop = function (time) {
  49978. if (this.isPlaying) {
  49979. if (this._streaming) {
  49980. this._htmlAudioElement.pause();
  49981. // Test needed for Firefox or it will generate an Invalid State Error
  49982. if (this._htmlAudioElement.currentTime > 0) {
  49983. this._htmlAudioElement.currentTime = 0;
  49984. }
  49985. }
  49986. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49987. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49988. this._soundSource.stop(stopTime);
  49989. this._soundSource.onended = function () { };
  49990. if (!this.isPaused) {
  49991. this._startOffset = 0;
  49992. }
  49993. }
  49994. this.isPlaying = false;
  49995. }
  49996. };
  49997. Sound.prototype.pause = function () {
  49998. if (this.isPlaying) {
  49999. this.isPaused = true;
  50000. if (this._streaming) {
  50001. this._htmlAudioElement.pause();
  50002. }
  50003. else if (BABYLON.Engine.audioEngine.audioContext) {
  50004. this.stop(0);
  50005. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50006. }
  50007. }
  50008. };
  50009. Sound.prototype.setVolume = function (newVolume, time) {
  50010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50011. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50012. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50013. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50014. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50015. }
  50016. else {
  50017. this._soundGain.gain.value = newVolume;
  50018. }
  50019. }
  50020. this._volume = newVolume;
  50021. };
  50022. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50023. this._playbackRate = newPlaybackRate;
  50024. if (this.isPlaying) {
  50025. if (this._streaming) {
  50026. this._htmlAudioElement.playbackRate = this._playbackRate;
  50027. }
  50028. else if (this._soundSource) {
  50029. this._soundSource.playbackRate.value = this._playbackRate;
  50030. }
  50031. }
  50032. };
  50033. Sound.prototype.getVolume = function () {
  50034. return this._volume;
  50035. };
  50036. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50037. var _this = this;
  50038. if (this._connectedMesh && this._registerFunc) {
  50039. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50040. this._registerFunc = null;
  50041. }
  50042. this._connectedMesh = meshToConnectTo;
  50043. if (!this.spatialSound) {
  50044. this.spatialSound = true;
  50045. this._createSpatialParameters();
  50046. if (this.isPlaying && this.loop) {
  50047. this.stop();
  50048. this.play();
  50049. }
  50050. }
  50051. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50052. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  50053. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  50054. };
  50055. Sound.prototype.detachFromMesh = function () {
  50056. if (this._connectedMesh && this._registerFunc) {
  50057. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50058. this._registerFunc = null;
  50059. this._connectedMesh = null;
  50060. }
  50061. };
  50062. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  50063. if (!node.getBoundingInfo) {
  50064. return;
  50065. }
  50066. var mesh = node;
  50067. var boundingInfo = mesh.getBoundingInfo();
  50068. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  50069. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  50070. this._updateDirection();
  50071. }
  50072. };
  50073. Sound.prototype.clone = function () {
  50074. var _this = this;
  50075. if (!this._streaming) {
  50076. var setBufferAndRun = function () {
  50077. if (_this._isReadyToPlay) {
  50078. clonedSound._audioBuffer = _this.getAudioBuffer();
  50079. clonedSound._isReadyToPlay = true;
  50080. if (clonedSound.autoplay) {
  50081. clonedSound.play();
  50082. }
  50083. }
  50084. else {
  50085. window.setTimeout(setBufferAndRun, 300);
  50086. }
  50087. };
  50088. var currentOptions = {
  50089. autoplay: this.autoplay, loop: this.loop,
  50090. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  50091. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  50092. refDistance: this.refDistance, distanceModel: this.distanceModel
  50093. };
  50094. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  50095. if (this.useCustomAttenuation) {
  50096. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  50097. }
  50098. clonedSound.setPosition(this._position);
  50099. clonedSound.setPlaybackRate(this._playbackRate);
  50100. setBufferAndRun();
  50101. return clonedSound;
  50102. }
  50103. else {
  50104. return null;
  50105. }
  50106. };
  50107. Sound.prototype.getAudioBuffer = function () {
  50108. return this._audioBuffer;
  50109. };
  50110. Sound.prototype.serialize = function () {
  50111. var serializationObject = {
  50112. name: this.name,
  50113. url: this.name,
  50114. autoplay: this.autoplay,
  50115. loop: this.loop,
  50116. volume: this._volume,
  50117. spatialSound: this.spatialSound,
  50118. maxDistance: this.maxDistance,
  50119. rolloffFactor: this.rolloffFactor,
  50120. refDistance: this.refDistance,
  50121. distanceModel: this.distanceModel,
  50122. playbackRate: this._playbackRate,
  50123. panningModel: this._panningModel,
  50124. soundTrackId: this.soundTrackId
  50125. };
  50126. if (this.spatialSound) {
  50127. if (this._connectedMesh)
  50128. serializationObject.connectedMeshId = this._connectedMesh.id;
  50129. serializationObject.position = this._position.asArray();
  50130. serializationObject.refDistance = this.refDistance;
  50131. serializationObject.distanceModel = this.distanceModel;
  50132. serializationObject.isDirectional = this._isDirectional;
  50133. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  50134. serializationObject.coneInnerAngle = this._coneInnerAngle;
  50135. serializationObject.coneOuterAngle = this._coneOuterAngle;
  50136. serializationObject.coneOuterGain = this._coneOuterGain;
  50137. }
  50138. return serializationObject;
  50139. };
  50140. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  50141. var soundName = parsedSound.name;
  50142. var soundUrl;
  50143. if (parsedSound.url) {
  50144. soundUrl = rootUrl + parsedSound.url;
  50145. }
  50146. else {
  50147. soundUrl = rootUrl + soundName;
  50148. }
  50149. var options = {
  50150. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  50151. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  50152. rolloffFactor: parsedSound.rolloffFactor,
  50153. refDistance: parsedSound.refDistance,
  50154. distanceModel: parsedSound.distanceModel,
  50155. playbackRate: parsedSound.playbackRate
  50156. };
  50157. var newSound;
  50158. if (!sourceSound) {
  50159. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  50160. scene._addPendingData(newSound);
  50161. }
  50162. else {
  50163. var setBufferAndRun = function () {
  50164. if (sourceSound._isReadyToPlay) {
  50165. newSound._audioBuffer = sourceSound.getAudioBuffer();
  50166. newSound._isReadyToPlay = true;
  50167. if (newSound.autoplay) {
  50168. newSound.play();
  50169. }
  50170. }
  50171. else {
  50172. window.setTimeout(setBufferAndRun, 300);
  50173. }
  50174. };
  50175. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  50176. setBufferAndRun();
  50177. }
  50178. if (parsedSound.position) {
  50179. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  50180. newSound.setPosition(soundPosition);
  50181. }
  50182. if (parsedSound.isDirectional) {
  50183. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  50184. if (parsedSound.localDirectionToMesh) {
  50185. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  50186. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  50187. }
  50188. }
  50189. if (parsedSound.connectedMeshId) {
  50190. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  50191. if (connectedMesh) {
  50192. newSound.attachToMesh(connectedMesh);
  50193. }
  50194. }
  50195. return newSound;
  50196. };
  50197. return Sound;
  50198. }());
  50199. BABYLON.Sound = Sound;
  50200. })(BABYLON || (BABYLON = {}));
  50201. //# sourceMappingURL=babylon.sound.js.map
  50202. var BABYLON;
  50203. (function (BABYLON) {
  50204. var SoundTrack = /** @class */ (function () {
  50205. function SoundTrack(scene, options) {
  50206. this.id = -1;
  50207. this._isMainTrack = false;
  50208. this._isInitialized = false;
  50209. this._scene = scene;
  50210. this.soundCollection = new Array();
  50211. this._options = options;
  50212. if (!this._isMainTrack) {
  50213. this._scene.soundTracks.push(this);
  50214. this.id = this._scene.soundTracks.length - 1;
  50215. }
  50216. }
  50217. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  50218. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50219. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  50220. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  50221. if (this._options) {
  50222. if (this._options.volume) {
  50223. this._outputAudioNode.gain.value = this._options.volume;
  50224. }
  50225. if (this._options.mainTrack) {
  50226. this._isMainTrack = this._options.mainTrack;
  50227. }
  50228. }
  50229. this._isInitialized = true;
  50230. }
  50231. };
  50232. SoundTrack.prototype.dispose = function () {
  50233. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50234. if (this._connectedAnalyser) {
  50235. this._connectedAnalyser.stopDebugCanvas();
  50236. }
  50237. while (this.soundCollection.length) {
  50238. this.soundCollection[0].dispose();
  50239. }
  50240. if (this._outputAudioNode) {
  50241. this._outputAudioNode.disconnect();
  50242. }
  50243. this._outputAudioNode = null;
  50244. }
  50245. };
  50246. SoundTrack.prototype.AddSound = function (sound) {
  50247. if (!this._isInitialized) {
  50248. this._initializeSoundTrackAudioGraph();
  50249. }
  50250. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50251. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  50252. }
  50253. if (sound.soundTrackId) {
  50254. if (sound.soundTrackId === -1) {
  50255. this._scene.mainSoundTrack.RemoveSound(sound);
  50256. }
  50257. else {
  50258. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  50259. }
  50260. }
  50261. this.soundCollection.push(sound);
  50262. sound.soundTrackId = this.id;
  50263. };
  50264. SoundTrack.prototype.RemoveSound = function (sound) {
  50265. var index = this.soundCollection.indexOf(sound);
  50266. if (index !== -1) {
  50267. this.soundCollection.splice(index, 1);
  50268. }
  50269. };
  50270. SoundTrack.prototype.setVolume = function (newVolume) {
  50271. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50272. this._outputAudioNode.gain.value = newVolume;
  50273. }
  50274. };
  50275. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  50276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50277. for (var i = 0; i < this.soundCollection.length; i++) {
  50278. this.soundCollection[i].switchPanningModelToHRTF();
  50279. }
  50280. }
  50281. };
  50282. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  50283. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50284. for (var i = 0; i < this.soundCollection.length; i++) {
  50285. this.soundCollection[i].switchPanningModelToEqualPower();
  50286. }
  50287. }
  50288. };
  50289. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  50290. if (this._connectedAnalyser) {
  50291. this._connectedAnalyser.stopDebugCanvas();
  50292. }
  50293. this._connectedAnalyser = analyser;
  50294. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50295. this._outputAudioNode.disconnect();
  50296. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  50297. }
  50298. };
  50299. return SoundTrack;
  50300. }());
  50301. BABYLON.SoundTrack = SoundTrack;
  50302. })(BABYLON || (BABYLON = {}));
  50303. //# sourceMappingURL=babylon.soundtrack.js.map
  50304. var BABYLON;
  50305. (function (BABYLON) {
  50306. var Analyser = /** @class */ (function () {
  50307. function Analyser(scene) {
  50308. this.SMOOTHING = 0.75;
  50309. this.FFT_SIZE = 512;
  50310. this.BARGRAPHAMPLITUDE = 256;
  50311. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50312. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50313. this._scene = scene;
  50314. this._audioEngine = BABYLON.Engine.audioEngine;
  50315. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  50316. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50317. this._webAudioAnalyser.minDecibels = -140;
  50318. this._webAudioAnalyser.maxDecibels = 0;
  50319. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50320. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50321. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50322. }
  50323. }
  50324. Analyser.prototype.getFrequencyBinCount = function () {
  50325. if (this._audioEngine.canUseWebAudio) {
  50326. return this._webAudioAnalyser.frequencyBinCount;
  50327. }
  50328. else {
  50329. return 0;
  50330. }
  50331. };
  50332. Analyser.prototype.getByteFrequencyData = function () {
  50333. if (this._audioEngine.canUseWebAudio) {
  50334. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50335. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50336. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50337. }
  50338. return this._byteFreqs;
  50339. };
  50340. Analyser.prototype.getByteTimeDomainData = function () {
  50341. if (this._audioEngine.canUseWebAudio) {
  50342. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50343. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50344. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50345. }
  50346. return this._byteTime;
  50347. };
  50348. Analyser.prototype.getFloatFrequencyData = function () {
  50349. if (this._audioEngine.canUseWebAudio) {
  50350. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50351. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50352. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50353. }
  50354. return this._floatFreqs;
  50355. };
  50356. Analyser.prototype.drawDebugCanvas = function () {
  50357. var _this = this;
  50358. if (this._audioEngine.canUseWebAudio) {
  50359. if (!this._debugCanvas) {
  50360. this._debugCanvas = document.createElement("canvas");
  50361. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50362. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50363. this._debugCanvas.style.position = "absolute";
  50364. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50365. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50366. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50367. document.body.appendChild(this._debugCanvas);
  50368. this._registerFunc = function () {
  50369. _this.drawDebugCanvas();
  50370. };
  50371. this._scene.registerBeforeRender(this._registerFunc);
  50372. }
  50373. if (this._registerFunc && this._debugCanvasContext) {
  50374. var workingArray = this.getByteFrequencyData();
  50375. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50376. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50377. // Draw the frequency domain chart.
  50378. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50379. var value = workingArray[i];
  50380. var percent = value / this.BARGRAPHAMPLITUDE;
  50381. var height = this.DEBUGCANVASSIZE.height * percent;
  50382. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50383. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50384. var hue = i / this.getFrequencyBinCount() * 360;
  50385. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50386. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50387. }
  50388. }
  50389. }
  50390. };
  50391. Analyser.prototype.stopDebugCanvas = function () {
  50392. if (this._debugCanvas) {
  50393. if (this._registerFunc) {
  50394. this._scene.unregisterBeforeRender(this._registerFunc);
  50395. this._registerFunc = null;
  50396. }
  50397. document.body.removeChild(this._debugCanvas);
  50398. this._debugCanvas = null;
  50399. this._debugCanvasContext = null;
  50400. }
  50401. };
  50402. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50403. if (this._audioEngine.canUseWebAudio) {
  50404. inputAudioNode.connect(this._webAudioAnalyser);
  50405. this._webAudioAnalyser.connect(outputAudioNode);
  50406. }
  50407. };
  50408. Analyser.prototype.dispose = function () {
  50409. if (this._audioEngine.canUseWebAudio) {
  50410. this._webAudioAnalyser.disconnect();
  50411. }
  50412. };
  50413. return Analyser;
  50414. }());
  50415. BABYLON.Analyser = Analyser;
  50416. })(BABYLON || (BABYLON = {}));
  50417. //# sourceMappingURL=babylon.analyser.js.map
  50418. var BABYLON;
  50419. (function (BABYLON) {
  50420. var CubeTexture = /** @class */ (function (_super) {
  50421. __extends(CubeTexture, _super);
  50422. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  50423. if (extensions === void 0) { extensions = null; }
  50424. if (noMipmap === void 0) { noMipmap = false; }
  50425. if (files === void 0) { files = null; }
  50426. if (onLoad === void 0) { onLoad = null; }
  50427. if (onError === void 0) { onError = null; }
  50428. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50429. if (prefiltered === void 0) { prefiltered = false; }
  50430. if (forcedExtension === void 0) { forcedExtension = null; }
  50431. var _this = _super.call(this, scene) || this;
  50432. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50433. _this.name = rootUrl;
  50434. _this.url = rootUrl;
  50435. _this._noMipmap = noMipmap;
  50436. _this.hasAlpha = false;
  50437. _this._format = format;
  50438. _this._prefiltered = prefiltered;
  50439. _this.isCube = true;
  50440. _this._textureMatrix = BABYLON.Matrix.Identity();
  50441. if (prefiltered) {
  50442. _this.gammaSpace = false;
  50443. }
  50444. if (!rootUrl && !files) {
  50445. return _this;
  50446. }
  50447. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50448. var lastDot = rootUrl.lastIndexOf(".");
  50449. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50450. var isDDS = (extension === ".dds");
  50451. if (!files) {
  50452. if (!isDDS && !extensions) {
  50453. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50454. }
  50455. files = [];
  50456. if (extensions) {
  50457. for (var index = 0; index < extensions.length; index++) {
  50458. files.push(rootUrl + extensions[index]);
  50459. }
  50460. }
  50461. }
  50462. _this._files = files;
  50463. if (!_this._texture) {
  50464. if (!scene.useDelayedTextureLoading) {
  50465. if (prefiltered) {
  50466. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50467. }
  50468. else {
  50469. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50470. }
  50471. }
  50472. else {
  50473. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50474. }
  50475. }
  50476. else if (onLoad) {
  50477. if (_this._texture.isReady) {
  50478. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50479. }
  50480. else {
  50481. _this._texture.onLoadedObservable.add(onLoad);
  50482. }
  50483. }
  50484. return _this;
  50485. }
  50486. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50487. return new CubeTexture("", scene, null, noMipmap, files);
  50488. };
  50489. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50490. if (forcedExtension === void 0) { forcedExtension = null; }
  50491. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50492. };
  50493. // Methods
  50494. CubeTexture.prototype.delayLoad = function () {
  50495. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50496. return;
  50497. }
  50498. var scene = this.getScene();
  50499. if (!scene) {
  50500. return;
  50501. }
  50502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50503. this._texture = this._getFromCache(this.url, this._noMipmap);
  50504. if (!this._texture) {
  50505. if (this._prefiltered) {
  50506. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50507. }
  50508. else {
  50509. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50510. }
  50511. }
  50512. };
  50513. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50514. return this._textureMatrix;
  50515. };
  50516. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50517. this._textureMatrix = value;
  50518. };
  50519. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50520. var texture = BABYLON.SerializationHelper.Parse(function () {
  50521. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50522. }, parsedTexture, scene);
  50523. // Animations
  50524. if (parsedTexture.animations) {
  50525. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50526. var parsedAnimation = parsedTexture.animations[animationIndex];
  50527. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50528. }
  50529. }
  50530. return texture;
  50531. };
  50532. CubeTexture.prototype.clone = function () {
  50533. var _this = this;
  50534. return BABYLON.SerializationHelper.Clone(function () {
  50535. var scene = _this.getScene();
  50536. if (!scene) {
  50537. return _this;
  50538. }
  50539. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50540. }, this);
  50541. };
  50542. return CubeTexture;
  50543. }(BABYLON.BaseTexture));
  50544. BABYLON.CubeTexture = CubeTexture;
  50545. })(BABYLON || (BABYLON = {}));
  50546. //# sourceMappingURL=babylon.cubeTexture.js.map
  50547. var BABYLON;
  50548. (function (BABYLON) {
  50549. var RenderTargetTexture = /** @class */ (function (_super) {
  50550. __extends(RenderTargetTexture, _super);
  50551. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50552. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50553. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50554. if (isCube === void 0) { isCube = false; }
  50555. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50556. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50557. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50558. if (isMulti === void 0) { isMulti = false; }
  50559. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50560. _this.isCube = isCube;
  50561. /**
  50562. * Use this list to define the list of mesh you want to render.
  50563. */
  50564. _this.renderList = new Array();
  50565. _this.renderParticles = true;
  50566. _this.renderSprites = false;
  50567. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50568. _this.ignoreCameraViewport = false;
  50569. // Events
  50570. /**
  50571. * An event triggered when the texture is unbind.
  50572. * @type {BABYLON.Observable}
  50573. */
  50574. _this.onBeforeBindObservable = new BABYLON.Observable();
  50575. /**
  50576. * An event triggered when the texture is unbind.
  50577. * @type {BABYLON.Observable}
  50578. */
  50579. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50580. /**
  50581. * An event triggered before rendering the texture
  50582. * @type {BABYLON.Observable}
  50583. */
  50584. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50585. /**
  50586. * An event triggered after rendering the texture
  50587. * @type {BABYLON.Observable}
  50588. */
  50589. _this.onAfterRenderObservable = new BABYLON.Observable();
  50590. /**
  50591. * An event triggered after the texture clear
  50592. * @type {BABYLON.Observable}
  50593. */
  50594. _this.onClearObservable = new BABYLON.Observable();
  50595. _this._currentRefreshId = -1;
  50596. _this._refreshRate = 1;
  50597. _this._samples = 1;
  50598. scene = _this.getScene();
  50599. if (!scene) {
  50600. return _this;
  50601. }
  50602. _this._engine = scene.getEngine();
  50603. _this.name = name;
  50604. _this.isRenderTarget = true;
  50605. _this._initialSizeParameter = size;
  50606. _this._processSizeParameter(size);
  50607. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50608. });
  50609. _this._generateMipMaps = generateMipMaps ? true : false;
  50610. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50611. // Rendering groups
  50612. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50613. if (isMulti) {
  50614. return _this;
  50615. }
  50616. _this._renderTargetOptions = {
  50617. generateMipMaps: generateMipMaps,
  50618. type: type,
  50619. samplingMode: samplingMode,
  50620. generateDepthBuffer: generateDepthBuffer,
  50621. generateStencilBuffer: generateStencilBuffer
  50622. };
  50623. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50624. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50625. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50626. }
  50627. if (isCube) {
  50628. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50629. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50630. _this._textureMatrix = BABYLON.Matrix.Identity();
  50631. }
  50632. else {
  50633. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50634. }
  50635. return _this;
  50636. }
  50637. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50638. get: function () {
  50639. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50640. },
  50641. enumerable: true,
  50642. configurable: true
  50643. });
  50644. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50645. get: function () {
  50646. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50647. },
  50648. enumerable: true,
  50649. configurable: true
  50650. });
  50651. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50652. get: function () {
  50653. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50654. },
  50655. enumerable: true,
  50656. configurable: true
  50657. });
  50658. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50659. set: function (callback) {
  50660. if (this._onAfterUnbindObserver) {
  50661. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50662. }
  50663. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50664. },
  50665. enumerable: true,
  50666. configurable: true
  50667. });
  50668. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50669. set: function (callback) {
  50670. if (this._onBeforeRenderObserver) {
  50671. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50672. }
  50673. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50679. set: function (callback) {
  50680. if (this._onAfterRenderObserver) {
  50681. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50682. }
  50683. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50689. set: function (callback) {
  50690. if (this._onClearObserver) {
  50691. this.onClearObservable.remove(this._onClearObserver);
  50692. }
  50693. this._onClearObserver = this.onClearObservable.add(callback);
  50694. },
  50695. enumerable: true,
  50696. configurable: true
  50697. });
  50698. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50699. get: function () {
  50700. return this._renderTargetOptions;
  50701. },
  50702. enumerable: true,
  50703. configurable: true
  50704. });
  50705. RenderTargetTexture.prototype._onRatioRescale = function () {
  50706. if (this._sizeRatio) {
  50707. this.resize(this._initialSizeParameter);
  50708. }
  50709. };
  50710. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50711. if (size.ratio) {
  50712. this._sizeRatio = size.ratio;
  50713. this._size = {
  50714. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50715. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50716. };
  50717. }
  50718. else {
  50719. this._size = size;
  50720. }
  50721. };
  50722. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50723. get: function () {
  50724. return this._samples;
  50725. },
  50726. set: function (value) {
  50727. if (this._samples === value) {
  50728. return;
  50729. }
  50730. var scene = this.getScene();
  50731. if (!scene) {
  50732. return;
  50733. }
  50734. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50735. },
  50736. enumerable: true,
  50737. configurable: true
  50738. });
  50739. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50740. this._currentRefreshId = -1;
  50741. };
  50742. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50743. get: function () {
  50744. return this._refreshRate;
  50745. },
  50746. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50747. set: function (value) {
  50748. this._refreshRate = value;
  50749. this.resetRefreshCounter();
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50755. if (!this._postProcessManager) {
  50756. var scene = this.getScene();
  50757. if (!scene) {
  50758. return;
  50759. }
  50760. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50761. this._postProcesses = new Array();
  50762. }
  50763. this._postProcesses.push(postProcess);
  50764. this._postProcesses[0].autoClear = false;
  50765. };
  50766. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50767. if (!this._postProcesses) {
  50768. return;
  50769. }
  50770. if (dispose) {
  50771. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50772. var postProcess = _a[_i];
  50773. postProcess.dispose();
  50774. }
  50775. }
  50776. this._postProcesses = [];
  50777. };
  50778. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50779. if (!this._postProcesses) {
  50780. return;
  50781. }
  50782. var index = this._postProcesses.indexOf(postProcess);
  50783. if (index === -1) {
  50784. return;
  50785. }
  50786. this._postProcesses.splice(index, 1);
  50787. if (this._postProcesses.length > 0) {
  50788. this._postProcesses[0].autoClear = false;
  50789. }
  50790. };
  50791. RenderTargetTexture.prototype._shouldRender = function () {
  50792. if (this._currentRefreshId === -1) {
  50793. this._currentRefreshId = 1;
  50794. return true;
  50795. }
  50796. if (this.refreshRate === this._currentRefreshId) {
  50797. this._currentRefreshId = 1;
  50798. return true;
  50799. }
  50800. this._currentRefreshId++;
  50801. return false;
  50802. };
  50803. RenderTargetTexture.prototype.getRenderSize = function () {
  50804. if (this._size.width) {
  50805. return this._size.width;
  50806. }
  50807. return this._size;
  50808. };
  50809. RenderTargetTexture.prototype.getRenderWidth = function () {
  50810. if (this._size.width) {
  50811. return this._size.width;
  50812. }
  50813. return this._size;
  50814. };
  50815. RenderTargetTexture.prototype.getRenderHeight = function () {
  50816. if (this._size.width) {
  50817. return this._size.height;
  50818. }
  50819. return this._size;
  50820. };
  50821. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50822. get: function () {
  50823. return true;
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. RenderTargetTexture.prototype.scale = function (ratio) {
  50829. var newSize = this.getRenderSize() * ratio;
  50830. this.resize(newSize);
  50831. };
  50832. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50833. if (this.isCube) {
  50834. return this._textureMatrix;
  50835. }
  50836. return _super.prototype.getReflectionTextureMatrix.call(this);
  50837. };
  50838. RenderTargetTexture.prototype.resize = function (size) {
  50839. this.releaseInternalTexture();
  50840. var scene = this.getScene();
  50841. if (!scene) {
  50842. return;
  50843. }
  50844. this._processSizeParameter(size);
  50845. if (this.isCube) {
  50846. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50847. }
  50848. else {
  50849. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50850. }
  50851. };
  50852. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50853. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50854. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50855. var scene = this.getScene();
  50856. if (!scene) {
  50857. return;
  50858. }
  50859. var engine = scene.getEngine();
  50860. if (this.useCameraPostProcesses !== undefined) {
  50861. useCameraPostProcess = this.useCameraPostProcesses;
  50862. }
  50863. if (this._waitingRenderList) {
  50864. this.renderList = [];
  50865. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50866. var id = this._waitingRenderList[index];
  50867. var mesh_1 = scene.getMeshByID(id);
  50868. if (mesh_1) {
  50869. this.renderList.push(mesh_1);
  50870. }
  50871. }
  50872. delete this._waitingRenderList;
  50873. }
  50874. // Is predicate defined?
  50875. if (this.renderListPredicate) {
  50876. if (this.renderList) {
  50877. this.renderList.splice(0); // Clear previous renderList
  50878. }
  50879. else {
  50880. this.renderList = [];
  50881. }
  50882. var scene = this.getScene();
  50883. if (!scene) {
  50884. return;
  50885. }
  50886. var sceneMeshes = scene.meshes;
  50887. for (var index = 0; index < sceneMeshes.length; index++) {
  50888. var mesh = sceneMeshes[index];
  50889. if (this.renderListPredicate(mesh)) {
  50890. this.renderList.push(mesh);
  50891. }
  50892. }
  50893. }
  50894. this.onBeforeBindObservable.notifyObservers(this);
  50895. // Set custom projection.
  50896. // Needs to be before binding to prevent changing the aspect ratio.
  50897. var camera;
  50898. if (this.activeCamera) {
  50899. camera = this.activeCamera;
  50900. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50901. if (this.activeCamera !== scene.activeCamera) {
  50902. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50903. }
  50904. }
  50905. else {
  50906. camera = scene.activeCamera;
  50907. if (camera) {
  50908. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50909. }
  50910. }
  50911. // Prepare renderingManager
  50912. this._renderingManager.reset();
  50913. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50914. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50915. var sceneRenderId = scene.getRenderId();
  50916. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50917. var mesh = currentRenderList[meshIndex];
  50918. if (mesh) {
  50919. if (!mesh.isReady()) {
  50920. // Reset _currentRefreshId
  50921. this.resetRefreshCounter();
  50922. continue;
  50923. }
  50924. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50925. var isMasked = void 0;
  50926. if (!this.renderList && camera) {
  50927. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50928. }
  50929. else {
  50930. isMasked = false;
  50931. }
  50932. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50933. mesh._activate(sceneRenderId);
  50934. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50935. var subMesh = mesh.subMeshes[subIndex];
  50936. scene._activeIndices.addCount(subMesh.indexCount, false);
  50937. this._renderingManager.dispatch(subMesh);
  50938. }
  50939. }
  50940. }
  50941. }
  50942. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50943. var particleSystem = scene.particleSystems[particleIndex];
  50944. var emitter = particleSystem.emitter;
  50945. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50946. continue;
  50947. }
  50948. if (currentRenderList.indexOf(emitter) >= 0) {
  50949. this._renderingManager.dispatchParticles(particleSystem);
  50950. }
  50951. }
  50952. if (this.isCube) {
  50953. for (var face = 0; face < 6; face++) {
  50954. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50955. scene.incrementRenderId();
  50956. scene.resetCachedMaterial();
  50957. }
  50958. }
  50959. else {
  50960. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50961. }
  50962. this.onAfterUnbindObservable.notifyObservers(this);
  50963. if (scene.activeCamera) {
  50964. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50965. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50966. }
  50967. engine.setViewport(scene.activeCamera.viewport);
  50968. }
  50969. scene.resetCachedMaterial();
  50970. };
  50971. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50972. var minimum = 128;
  50973. var x = renderDimension * scale;
  50974. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50975. // Ensure we don't exceed the render dimension (while staying POT)
  50976. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50977. };
  50978. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50979. var _this = this;
  50980. var scene = this.getScene();
  50981. if (!scene) {
  50982. return;
  50983. }
  50984. var engine = scene.getEngine();
  50985. if (!this._texture) {
  50986. return;
  50987. }
  50988. // Bind
  50989. if (this._postProcessManager) {
  50990. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50991. }
  50992. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50993. if (this._texture) {
  50994. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50995. }
  50996. }
  50997. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50998. // Clear
  50999. if (this.onClearObservable.hasObservers()) {
  51000. this.onClearObservable.notifyObservers(engine);
  51001. }
  51002. else {
  51003. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51004. }
  51005. if (!this._doNotChangeAspectRatio) {
  51006. scene.updateTransformMatrix(true);
  51007. }
  51008. // Render
  51009. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51010. if (this._postProcessManager) {
  51011. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51012. }
  51013. else if (useCameraPostProcess) {
  51014. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51015. }
  51016. if (!this._doNotChangeAspectRatio) {
  51017. scene.updateTransformMatrix(true);
  51018. }
  51019. // Dump ?
  51020. if (dumpForDebug) {
  51021. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51022. }
  51023. // Unbind
  51024. if (!this.isCube || faceIndex === 5) {
  51025. if (this.isCube) {
  51026. if (faceIndex === 5) {
  51027. engine.generateMipMapsForCubemap(this._texture);
  51028. }
  51029. }
  51030. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51031. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51032. });
  51033. }
  51034. else {
  51035. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51036. }
  51037. };
  51038. /**
  51039. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51040. * This allowed control for front to back rendering or reversly depending of the special needs.
  51041. *
  51042. * @param renderingGroupId The rendering group id corresponding to its index
  51043. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51044. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51045. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51046. */
  51047. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  51048. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  51049. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  51050. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  51051. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  51052. };
  51053. /**
  51054. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  51055. *
  51056. * @param renderingGroupId The rendering group id corresponding to its index
  51057. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  51058. */
  51059. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  51060. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  51061. };
  51062. RenderTargetTexture.prototype.clone = function () {
  51063. var textureSize = this.getSize();
  51064. 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);
  51065. // Base texture
  51066. newTexture.hasAlpha = this.hasAlpha;
  51067. newTexture.level = this.level;
  51068. // RenderTarget Texture
  51069. newTexture.coordinatesMode = this.coordinatesMode;
  51070. if (this.renderList) {
  51071. newTexture.renderList = this.renderList.slice(0);
  51072. }
  51073. return newTexture;
  51074. };
  51075. RenderTargetTexture.prototype.serialize = function () {
  51076. if (!this.name) {
  51077. return null;
  51078. }
  51079. var serializationObject = _super.prototype.serialize.call(this);
  51080. serializationObject.renderTargetSize = this.getRenderSize();
  51081. serializationObject.renderList = [];
  51082. if (this.renderList) {
  51083. for (var index = 0; index < this.renderList.length; index++) {
  51084. serializationObject.renderList.push(this.renderList[index].id);
  51085. }
  51086. }
  51087. return serializationObject;
  51088. };
  51089. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  51090. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  51091. var objBuffer = this.getInternalTexture();
  51092. var scene = this.getScene();
  51093. if (objBuffer && scene) {
  51094. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  51095. }
  51096. };
  51097. RenderTargetTexture.prototype.dispose = function () {
  51098. if (this._postProcessManager) {
  51099. this._postProcessManager.dispose();
  51100. this._postProcessManager = null;
  51101. }
  51102. this.clearPostProcesses(true);
  51103. if (this._resizeObserver) {
  51104. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  51105. this._resizeObserver = null;
  51106. }
  51107. this.renderList = null;
  51108. // Remove from custom render targets
  51109. var scene = this.getScene();
  51110. if (!scene) {
  51111. return;
  51112. }
  51113. var index = scene.customRenderTargets.indexOf(this);
  51114. if (index >= 0) {
  51115. scene.customRenderTargets.splice(index, 1);
  51116. }
  51117. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  51118. var camera = _a[_i];
  51119. index = camera.customRenderTargets.indexOf(this);
  51120. if (index >= 0) {
  51121. camera.customRenderTargets.splice(index, 1);
  51122. }
  51123. }
  51124. _super.prototype.dispose.call(this);
  51125. };
  51126. RenderTargetTexture.prototype._rebuild = function () {
  51127. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51128. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51129. }
  51130. if (this._postProcessManager) {
  51131. this._postProcessManager._rebuild();
  51132. }
  51133. };
  51134. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  51135. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  51136. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  51137. return RenderTargetTexture;
  51138. }(BABYLON.Texture));
  51139. BABYLON.RenderTargetTexture = RenderTargetTexture;
  51140. })(BABYLON || (BABYLON = {}));
  51141. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  51142. var BABYLON;
  51143. (function (BABYLON) {
  51144. ;
  51145. var MultiRenderTarget = /** @class */ (function (_super) {
  51146. __extends(MultiRenderTarget, _super);
  51147. function MultiRenderTarget(name, size, count, scene, options) {
  51148. var _this = this;
  51149. options = options || {};
  51150. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  51151. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  51152. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  51153. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  51154. _this._engine = scene.getEngine();
  51155. if (!_this.isSupported) {
  51156. _this.dispose();
  51157. return;
  51158. }
  51159. var types = [];
  51160. var samplingModes = [];
  51161. for (var i = 0; i < count; i++) {
  51162. if (options.types && options.types[i]) {
  51163. types.push(options.types[i]);
  51164. }
  51165. else {
  51166. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  51167. }
  51168. if (options.samplingModes && options.samplingModes[i]) {
  51169. samplingModes.push(options.samplingModes[i]);
  51170. }
  51171. else {
  51172. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51173. }
  51174. }
  51175. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  51176. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  51177. _this._size = size;
  51178. _this._multiRenderTargetOptions = {
  51179. samplingModes: samplingModes,
  51180. generateMipMaps: generateMipMaps,
  51181. generateDepthBuffer: generateDepthBuffer,
  51182. generateStencilBuffer: generateStencilBuffer,
  51183. generateDepthTexture: generateDepthTexture,
  51184. types: types,
  51185. textureCount: count
  51186. };
  51187. _this._createInternalTextures();
  51188. _this._createTextures();
  51189. return _this;
  51190. }
  51191. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  51192. get: function () {
  51193. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  51199. get: function () {
  51200. return this._textures;
  51201. },
  51202. enumerable: true,
  51203. configurable: true
  51204. });
  51205. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  51206. get: function () {
  51207. return this._textures[this._textures.length - 1];
  51208. },
  51209. enumerable: true,
  51210. configurable: true
  51211. });
  51212. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  51213. set: function (wrap) {
  51214. if (this._textures) {
  51215. for (var i = 0; i < this._textures.length; i++) {
  51216. this._textures[i].wrapU = wrap;
  51217. }
  51218. }
  51219. },
  51220. enumerable: true,
  51221. configurable: true
  51222. });
  51223. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  51224. set: function (wrap) {
  51225. if (this._textures) {
  51226. for (var i = 0; i < this._textures.length; i++) {
  51227. this._textures[i].wrapV = wrap;
  51228. }
  51229. }
  51230. },
  51231. enumerable: true,
  51232. configurable: true
  51233. });
  51234. MultiRenderTarget.prototype._rebuild = function () {
  51235. this.releaseInternalTextures();
  51236. this._createInternalTextures();
  51237. for (var i = 0; i < this._internalTextures.length; i++) {
  51238. var texture = this._textures[i];
  51239. texture._texture = this._internalTextures[i];
  51240. }
  51241. // Keeps references to frame buffer and stencil/depth buffer
  51242. this._texture = this._internalTextures[0];
  51243. };
  51244. MultiRenderTarget.prototype._createInternalTextures = function () {
  51245. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  51246. };
  51247. MultiRenderTarget.prototype._createTextures = function () {
  51248. this._textures = [];
  51249. for (var i = 0; i < this._internalTextures.length; i++) {
  51250. var texture = new BABYLON.Texture(null, this.getScene());
  51251. texture._texture = this._internalTextures[i];
  51252. this._textures.push(texture);
  51253. }
  51254. // Keeps references to frame buffer and stencil/depth buffer
  51255. this._texture = this._internalTextures[0];
  51256. };
  51257. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  51258. get: function () {
  51259. return this._samples;
  51260. },
  51261. set: function (value) {
  51262. if (this._samples === value) {
  51263. return;
  51264. }
  51265. for (var i = 0; i < this._internalTextures.length; i++) {
  51266. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  51267. }
  51268. },
  51269. enumerable: true,
  51270. configurable: true
  51271. });
  51272. MultiRenderTarget.prototype.resize = function (size) {
  51273. this.releaseInternalTextures();
  51274. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  51275. this._createInternalTextures();
  51276. };
  51277. MultiRenderTarget.prototype.dispose = function () {
  51278. this.releaseInternalTextures();
  51279. _super.prototype.dispose.call(this);
  51280. };
  51281. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  51282. if (!this._internalTextures) {
  51283. return;
  51284. }
  51285. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  51286. if (this._internalTextures[i] !== undefined) {
  51287. this._internalTextures[i].dispose();
  51288. this._internalTextures.splice(i, 1);
  51289. }
  51290. }
  51291. };
  51292. return MultiRenderTarget;
  51293. }(BABYLON.RenderTargetTexture));
  51294. BABYLON.MultiRenderTarget = MultiRenderTarget;
  51295. })(BABYLON || (BABYLON = {}));
  51296. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  51297. var BABYLON;
  51298. (function (BABYLON) {
  51299. var MirrorTexture = /** @class */ (function (_super) {
  51300. __extends(MirrorTexture, _super);
  51301. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  51302. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51304. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51305. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  51306. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  51307. _this._transformMatrix = BABYLON.Matrix.Zero();
  51308. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  51309. _this._adaptiveBlurKernel = 0;
  51310. _this._blurKernelX = 0;
  51311. _this._blurKernelY = 0;
  51312. _this._blurRatio = 1.0;
  51313. _this.ignoreCameraViewport = true;
  51314. _this.onBeforeRenderObservable.add(function () {
  51315. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  51316. _this._savedViewMatrix = scene.getViewMatrix();
  51317. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  51318. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  51319. scene.clipPlane = _this.mirrorPlane;
  51320. scene.getEngine().cullBackFaces = false;
  51321. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  51322. });
  51323. _this.onAfterRenderObservable.add(function () {
  51324. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  51325. scene.getEngine().cullBackFaces = true;
  51326. scene._mirroredCameraPosition = null;
  51327. delete scene.clipPlane;
  51328. });
  51329. return _this;
  51330. }
  51331. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  51332. get: function () {
  51333. return this._blurRatio;
  51334. },
  51335. set: function (value) {
  51336. if (this._blurRatio === value) {
  51337. return;
  51338. }
  51339. this._blurRatio = value;
  51340. this._preparePostProcesses();
  51341. },
  51342. enumerable: true,
  51343. configurable: true
  51344. });
  51345. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  51346. set: function (value) {
  51347. this._adaptiveBlurKernel = value;
  51348. this._autoComputeBlurKernel();
  51349. },
  51350. enumerable: true,
  51351. configurable: true
  51352. });
  51353. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  51354. set: function (value) {
  51355. this.blurKernelX = value;
  51356. this.blurKernelY = value;
  51357. },
  51358. enumerable: true,
  51359. configurable: true
  51360. });
  51361. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  51362. get: function () {
  51363. return this._blurKernelX;
  51364. },
  51365. set: function (value) {
  51366. if (this._blurKernelX === value) {
  51367. return;
  51368. }
  51369. this._blurKernelX = value;
  51370. this._preparePostProcesses();
  51371. },
  51372. enumerable: true,
  51373. configurable: true
  51374. });
  51375. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51376. get: function () {
  51377. return this._blurKernelY;
  51378. },
  51379. set: function (value) {
  51380. if (this._blurKernelY === value) {
  51381. return;
  51382. }
  51383. this._blurKernelY = value;
  51384. this._preparePostProcesses();
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51390. var engine = this.getScene().getEngine();
  51391. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51392. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51393. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51394. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51395. };
  51396. MirrorTexture.prototype._onRatioRescale = function () {
  51397. if (this._sizeRatio) {
  51398. this.resize(this._initialSizeParameter);
  51399. if (!this._adaptiveBlurKernel) {
  51400. this._preparePostProcesses();
  51401. }
  51402. }
  51403. if (this._adaptiveBlurKernel) {
  51404. this._autoComputeBlurKernel();
  51405. }
  51406. };
  51407. MirrorTexture.prototype._preparePostProcesses = function () {
  51408. this.clearPostProcesses(true);
  51409. if (this._blurKernelX && this._blurKernelY) {
  51410. var engine = this.getScene().getEngine();
  51411. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51412. 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);
  51413. this._blurX.autoClear = false;
  51414. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  51415. this._blurX.outputTexture = this._texture;
  51416. }
  51417. else {
  51418. this._blurX.alwaysForcePOT = true;
  51419. }
  51420. 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);
  51421. this._blurY.autoClear = false;
  51422. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  51423. this.addPostProcess(this._blurX);
  51424. this.addPostProcess(this._blurY);
  51425. }
  51426. else {
  51427. if (this._blurY) {
  51428. this.removePostProcess(this._blurY);
  51429. this._blurY.dispose();
  51430. this._blurY = null;
  51431. }
  51432. if (this._blurX) {
  51433. this.removePostProcess(this._blurX);
  51434. this._blurX.dispose();
  51435. this._blurX = null;
  51436. }
  51437. }
  51438. };
  51439. MirrorTexture.prototype.clone = function () {
  51440. var scene = this.getScene();
  51441. if (!scene) {
  51442. return this;
  51443. }
  51444. var textureSize = this.getSize();
  51445. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51446. // Base texture
  51447. newTexture.hasAlpha = this.hasAlpha;
  51448. newTexture.level = this.level;
  51449. // Mirror Texture
  51450. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51451. if (this.renderList) {
  51452. newTexture.renderList = this.renderList.slice(0);
  51453. }
  51454. return newTexture;
  51455. };
  51456. MirrorTexture.prototype.serialize = function () {
  51457. if (!this.name) {
  51458. return null;
  51459. }
  51460. var serializationObject = _super.prototype.serialize.call(this);
  51461. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51462. return serializationObject;
  51463. };
  51464. return MirrorTexture;
  51465. }(BABYLON.RenderTargetTexture));
  51466. BABYLON.MirrorTexture = MirrorTexture;
  51467. })(BABYLON || (BABYLON = {}));
  51468. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51469. var BABYLON;
  51470. (function (BABYLON) {
  51471. /**
  51472. * Creates a refraction texture used by refraction channel of the standard material.
  51473. * @param name the texture name
  51474. * @param size size of the underlying texture
  51475. * @param scene root scene
  51476. */
  51477. var RefractionTexture = /** @class */ (function (_super) {
  51478. __extends(RefractionTexture, _super);
  51479. function RefractionTexture(name, size, scene, generateMipMaps) {
  51480. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51481. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51482. _this.depth = 2.0;
  51483. _this.onBeforeRenderObservable.add(function () {
  51484. scene.clipPlane = _this.refractionPlane;
  51485. });
  51486. _this.onAfterRenderObservable.add(function () {
  51487. delete scene.clipPlane;
  51488. });
  51489. return _this;
  51490. }
  51491. RefractionTexture.prototype.clone = function () {
  51492. var scene = this.getScene();
  51493. if (!scene) {
  51494. return this;
  51495. }
  51496. var textureSize = this.getSize();
  51497. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51498. // Base texture
  51499. newTexture.hasAlpha = this.hasAlpha;
  51500. newTexture.level = this.level;
  51501. // Refraction Texture
  51502. newTexture.refractionPlane = this.refractionPlane.clone();
  51503. if (this.renderList) {
  51504. newTexture.renderList = this.renderList.slice(0);
  51505. }
  51506. newTexture.depth = this.depth;
  51507. return newTexture;
  51508. };
  51509. RefractionTexture.prototype.serialize = function () {
  51510. if (!this.name) {
  51511. return null;
  51512. }
  51513. var serializationObject = _super.prototype.serialize.call(this);
  51514. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51515. serializationObject.depth = this.depth;
  51516. return serializationObject;
  51517. };
  51518. return RefractionTexture;
  51519. }(BABYLON.RenderTargetTexture));
  51520. BABYLON.RefractionTexture = RefractionTexture;
  51521. })(BABYLON || (BABYLON = {}));
  51522. //# sourceMappingURL=babylon.refractionTexture.js.map
  51523. var BABYLON;
  51524. (function (BABYLON) {
  51525. var DynamicTexture = /** @class */ (function (_super) {
  51526. __extends(DynamicTexture, _super);
  51527. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51528. if (scene === void 0) { scene = null; }
  51529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51530. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51531. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51532. _this.name = name;
  51533. _this._engine = _this.getScene().getEngine();
  51534. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51535. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51536. _this._generateMipMaps = generateMipMaps;
  51537. if (options.getContext) {
  51538. _this._canvas = options;
  51539. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51540. }
  51541. else {
  51542. _this._canvas = document.createElement("canvas");
  51543. if (options.width) {
  51544. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51545. }
  51546. else {
  51547. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51548. }
  51549. }
  51550. var textureSize = _this.getSize();
  51551. _this._canvas.width = textureSize.width;
  51552. _this._canvas.height = textureSize.height;
  51553. _this._context = _this._canvas.getContext("2d");
  51554. return _this;
  51555. }
  51556. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51557. get: function () {
  51558. return true;
  51559. },
  51560. enumerable: true,
  51561. configurable: true
  51562. });
  51563. DynamicTexture.prototype._recreate = function (textureSize) {
  51564. this._canvas.width = textureSize.width;
  51565. this._canvas.height = textureSize.height;
  51566. this.releaseInternalTexture();
  51567. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51568. };
  51569. DynamicTexture.prototype.scale = function (ratio) {
  51570. var textureSize = this.getSize();
  51571. textureSize.width *= ratio;
  51572. textureSize.height *= ratio;
  51573. this._recreate(textureSize);
  51574. };
  51575. DynamicTexture.prototype.scaleTo = function (width, height) {
  51576. var textureSize = this.getSize();
  51577. textureSize.width = width;
  51578. textureSize.height = height;
  51579. this._recreate(textureSize);
  51580. };
  51581. DynamicTexture.prototype.getContext = function () {
  51582. return this._context;
  51583. };
  51584. DynamicTexture.prototype.clear = function () {
  51585. var size = this.getSize();
  51586. this._context.fillRect(0, 0, size.width, size.height);
  51587. };
  51588. DynamicTexture.prototype.update = function (invertY) {
  51589. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51590. };
  51591. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51592. if (update === void 0) { update = true; }
  51593. var size = this.getSize();
  51594. if (clearColor) {
  51595. this._context.fillStyle = clearColor;
  51596. this._context.fillRect(0, 0, size.width, size.height);
  51597. }
  51598. this._context.font = font;
  51599. if (x === null || x === undefined) {
  51600. var textSize = this._context.measureText(text);
  51601. x = (size.width - textSize.width) / 2;
  51602. }
  51603. if (y === null || y === undefined) {
  51604. var fontSize = parseInt((font.replace(/\D/g, '')));
  51605. ;
  51606. y = (size.height / 2) + (fontSize / 3.65);
  51607. }
  51608. this._context.fillStyle = color;
  51609. this._context.fillText(text, x, y);
  51610. if (update) {
  51611. this.update(invertY);
  51612. }
  51613. };
  51614. DynamicTexture.prototype.clone = function () {
  51615. var scene = this.getScene();
  51616. if (!scene) {
  51617. return this;
  51618. }
  51619. var textureSize = this.getSize();
  51620. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51621. // Base texture
  51622. newTexture.hasAlpha = this.hasAlpha;
  51623. newTexture.level = this.level;
  51624. // Dynamic Texture
  51625. newTexture.wrapU = this.wrapU;
  51626. newTexture.wrapV = this.wrapV;
  51627. return newTexture;
  51628. };
  51629. DynamicTexture.prototype._rebuild = function () {
  51630. this.update();
  51631. };
  51632. return DynamicTexture;
  51633. }(BABYLON.Texture));
  51634. BABYLON.DynamicTexture = DynamicTexture;
  51635. })(BABYLON || (BABYLON = {}));
  51636. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51637. var BABYLON;
  51638. (function (BABYLON) {
  51639. var VideoTexture = /** @class */ (function (_super) {
  51640. __extends(VideoTexture, _super);
  51641. /**
  51642. * Creates a video texture.
  51643. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51644. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51645. * @param {BABYLON.Scene} scene is obviously the current scene.
  51646. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51647. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51648. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51649. */
  51650. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51651. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51652. if (invertY === void 0) { invertY = false; }
  51653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51654. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51655. _this._autoLaunch = true;
  51656. var urls = null;
  51657. _this.name = name;
  51658. if (urlsOrVideo instanceof HTMLVideoElement) {
  51659. _this.video = urlsOrVideo;
  51660. }
  51661. else {
  51662. urls = urlsOrVideo;
  51663. _this.video = document.createElement("video");
  51664. _this.video.autoplay = false;
  51665. _this.video.loop = true;
  51666. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  51667. }
  51668. _this._engine = _this.getScene().getEngine();
  51669. _this._generateMipMaps = generateMipMaps;
  51670. _this._samplingMode = samplingMode;
  51671. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51672. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51673. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51674. }
  51675. else {
  51676. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51677. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51678. _this._generateMipMaps = false;
  51679. }
  51680. if (urls) {
  51681. _this.video.addEventListener("canplay", function () {
  51682. _this._createTexture();
  51683. });
  51684. urls.forEach(function (url) {
  51685. var source = document.createElement("source");
  51686. source.src = url;
  51687. _this.video.appendChild(source);
  51688. });
  51689. }
  51690. else {
  51691. _this._createTexture();
  51692. }
  51693. _this._lastUpdate = BABYLON.Tools.Now;
  51694. return _this;
  51695. }
  51696. VideoTexture.prototype.__setTextureReady = function () {
  51697. if (this._texture) {
  51698. this._texture.isReady = true;
  51699. }
  51700. };
  51701. VideoTexture.prototype._createTexture = function () {
  51702. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51703. if (this._autoLaunch) {
  51704. this._autoLaunch = false;
  51705. this.video.play();
  51706. }
  51707. this._setTextureReady = this.__setTextureReady.bind(this);
  51708. this.video.addEventListener("playing", this._setTextureReady);
  51709. };
  51710. VideoTexture.prototype._rebuild = function () {
  51711. this.update();
  51712. };
  51713. VideoTexture.prototype.update = function () {
  51714. var now = BABYLON.Tools.Now;
  51715. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51716. return false;
  51717. }
  51718. this._lastUpdate = now;
  51719. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51720. return true;
  51721. };
  51722. VideoTexture.prototype.dispose = function () {
  51723. _super.prototype.dispose.call(this);
  51724. this.video.removeEventListener("playing", this._setTextureReady);
  51725. };
  51726. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51727. var video = document.createElement("video");
  51728. var constraintsDeviceId;
  51729. if (constraints && constraints.deviceId) {
  51730. constraintsDeviceId = {
  51731. exact: constraints.deviceId
  51732. };
  51733. }
  51734. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51735. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51736. if (navigator.getUserMedia) {
  51737. navigator.getUserMedia({
  51738. video: {
  51739. deviceId: constraintsDeviceId,
  51740. width: {
  51741. min: (constraints && constraints.minWidth) || 256,
  51742. max: (constraints && constraints.maxWidth) || 640
  51743. },
  51744. height: {
  51745. min: (constraints && constraints.minHeight) || 256,
  51746. max: (constraints && constraints.maxHeight) || 480
  51747. }
  51748. }
  51749. }, function (stream) {
  51750. if (video.mozSrcObject !== undefined) {
  51751. video.mozSrcObject = stream;
  51752. }
  51753. else {
  51754. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51755. }
  51756. video.play();
  51757. if (onReady) {
  51758. onReady(new VideoTexture("video", video, scene, true, true));
  51759. }
  51760. }, function (e) {
  51761. BABYLON.Tools.Error(e.name);
  51762. });
  51763. }
  51764. };
  51765. return VideoTexture;
  51766. }(BABYLON.Texture));
  51767. BABYLON.VideoTexture = VideoTexture;
  51768. })(BABYLON || (BABYLON = {}));
  51769. //# sourceMappingURL=babylon.videoTexture.js.map
  51770. var BABYLON;
  51771. (function (BABYLON) {
  51772. var RawTexture = /** @class */ (function (_super) {
  51773. __extends(RawTexture, _super);
  51774. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51776. if (invertY === void 0) { invertY = false; }
  51777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51778. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51779. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51780. _this.format = format;
  51781. _this._engine = scene.getEngine();
  51782. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51783. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51784. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51785. return _this;
  51786. }
  51787. RawTexture.prototype.update = function (data) {
  51788. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  51789. };
  51790. // Statics
  51791. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51792. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51793. if (invertY === void 0) { invertY = false; }
  51794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51795. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51796. };
  51797. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51798. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51799. if (invertY === void 0) { invertY = false; }
  51800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51801. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51802. };
  51803. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51804. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51805. if (invertY === void 0) { invertY = false; }
  51806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51807. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51808. };
  51809. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51811. if (invertY === void 0) { invertY = false; }
  51812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51813. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51814. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51815. };
  51816. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51817. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51818. if (invertY === void 0) { invertY = false; }
  51819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51820. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51821. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  51822. };
  51823. return RawTexture;
  51824. }(BABYLON.Texture));
  51825. BABYLON.RawTexture = RawTexture;
  51826. })(BABYLON || (BABYLON = {}));
  51827. //# sourceMappingURL=babylon.rawTexture.js.map
  51828. var BABYLON;
  51829. (function (BABYLON) {
  51830. var PostProcess = /** @class */ (function () {
  51831. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51833. if (defines === void 0) { defines = null; }
  51834. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51835. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51836. if (blockCompilation === void 0) { blockCompilation = false; }
  51837. this.name = name;
  51838. this.width = -1;
  51839. this.height = -1;
  51840. this.autoClear = true;
  51841. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51842. this.animations = new Array();
  51843. /*
  51844. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51845. Can only be used on a single postprocess or on the last one of a chain.
  51846. */
  51847. this.enablePixelPerfectMode = false;
  51848. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51849. this.alwaysForcePOT = false;
  51850. this.samples = 1;
  51851. this.adaptScaleToCurrentViewport = false;
  51852. this._reusable = false;
  51853. this._textures = new BABYLON.SmartArray(2);
  51854. this._currentRenderTextureInd = 0;
  51855. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51856. this._texelSize = BABYLON.Vector2.Zero();
  51857. // Events
  51858. /**
  51859. * An event triggered when the postprocess is activated.
  51860. * @type {BABYLON.Observable}
  51861. */
  51862. this.onActivateObservable = new BABYLON.Observable();
  51863. /**
  51864. * An event triggered when the postprocess changes its size.
  51865. * @type {BABYLON.Observable}
  51866. */
  51867. this.onSizeChangedObservable = new BABYLON.Observable();
  51868. /**
  51869. * An event triggered when the postprocess applies its effect.
  51870. * @type {BABYLON.Observable}
  51871. */
  51872. this.onApplyObservable = new BABYLON.Observable();
  51873. /**
  51874. * An event triggered before rendering the postprocess
  51875. * @type {BABYLON.Observable}
  51876. */
  51877. this.onBeforeRenderObservable = new BABYLON.Observable();
  51878. /**
  51879. * An event triggered after rendering the postprocess
  51880. * @type {BABYLON.Observable}
  51881. */
  51882. this.onAfterRenderObservable = new BABYLON.Observable();
  51883. if (camera != null) {
  51884. this._camera = camera;
  51885. this._scene = camera.getScene();
  51886. camera.attachPostProcess(this);
  51887. this._engine = this._scene.getEngine();
  51888. this._scene.postProcesses.push(this);
  51889. }
  51890. else if (engine) {
  51891. this._engine = engine;
  51892. this._engine.postProcesses.push(this);
  51893. }
  51894. this._options = options;
  51895. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51896. this._reusable = reusable || false;
  51897. this._textureType = textureType;
  51898. this._samplers = samplers || [];
  51899. this._samplers.push("textureSampler");
  51900. this._fragmentUrl = fragmentUrl;
  51901. this._vertexUrl = vertexUrl;
  51902. this._parameters = parameters || [];
  51903. this._parameters.push("scale");
  51904. this._indexParameters = indexParameters;
  51905. if (!blockCompilation) {
  51906. this.updateEffect(defines);
  51907. }
  51908. }
  51909. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51910. set: function (callback) {
  51911. if (this._onActivateObserver) {
  51912. this.onActivateObservable.remove(this._onActivateObserver);
  51913. }
  51914. if (callback) {
  51915. this._onActivateObserver = this.onActivateObservable.add(callback);
  51916. }
  51917. },
  51918. enumerable: true,
  51919. configurable: true
  51920. });
  51921. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51922. set: function (callback) {
  51923. if (this._onSizeChangedObserver) {
  51924. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51925. }
  51926. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51927. },
  51928. enumerable: true,
  51929. configurable: true
  51930. });
  51931. Object.defineProperty(PostProcess.prototype, "onApply", {
  51932. set: function (callback) {
  51933. if (this._onApplyObserver) {
  51934. this.onApplyObservable.remove(this._onApplyObserver);
  51935. }
  51936. this._onApplyObserver = this.onApplyObservable.add(callback);
  51937. },
  51938. enumerable: true,
  51939. configurable: true
  51940. });
  51941. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51942. set: function (callback) {
  51943. if (this._onBeforeRenderObserver) {
  51944. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51945. }
  51946. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51947. },
  51948. enumerable: true,
  51949. configurable: true
  51950. });
  51951. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51952. set: function (callback) {
  51953. if (this._onAfterRenderObserver) {
  51954. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51955. }
  51956. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51957. },
  51958. enumerable: true,
  51959. configurable: true
  51960. });
  51961. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51962. get: function () {
  51963. return this._textures.data[this._currentRenderTextureInd];
  51964. },
  51965. set: function (value) {
  51966. this._forcedOutputTexture = value;
  51967. },
  51968. enumerable: true,
  51969. configurable: true
  51970. });
  51971. PostProcess.prototype.getCamera = function () {
  51972. return this._camera;
  51973. };
  51974. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51975. get: function () {
  51976. if (this._shareOutputWithPostProcess) {
  51977. return this._shareOutputWithPostProcess.texelSize;
  51978. }
  51979. if (this._forcedOutputTexture) {
  51980. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51981. }
  51982. return this._texelSize;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. PostProcess.prototype.getEngine = function () {
  51988. return this._engine;
  51989. };
  51990. PostProcess.prototype.getEffect = function () {
  51991. return this._effect;
  51992. };
  51993. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51994. this._disposeTextures();
  51995. this._shareOutputWithPostProcess = postProcess;
  51996. return this;
  51997. };
  51998. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51999. if (defines === void 0) { defines = null; }
  52000. if (uniforms === void 0) { uniforms = null; }
  52001. if (samplers === void 0) { samplers = null; }
  52002. 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);
  52003. };
  52004. PostProcess.prototype.isReusable = function () {
  52005. return this._reusable;
  52006. };
  52007. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52008. PostProcess.prototype.markTextureDirty = function () {
  52009. this.width = -1;
  52010. };
  52011. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52012. var _this = this;
  52013. if (sourceTexture === void 0) { sourceTexture = null; }
  52014. camera = camera || this._camera;
  52015. var scene = camera.getScene();
  52016. var engine = scene.getEngine();
  52017. var maxSize = engine.getCaps().maxTextureSize;
  52018. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52019. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52020. var desiredWidth = (this._options.width || requiredWidth);
  52021. var desiredHeight = this._options.height || requiredHeight;
  52022. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52023. if (this.adaptScaleToCurrentViewport) {
  52024. var currentViewport = engine.currentViewport;
  52025. if (currentViewport) {
  52026. desiredWidth *= currentViewport.width;
  52027. desiredHeight *= currentViewport.height;
  52028. }
  52029. }
  52030. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52031. if (!this._options.width) {
  52032. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52033. }
  52034. if (!this._options.height) {
  52035. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52036. }
  52037. }
  52038. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52039. if (this._textures.length > 0) {
  52040. for (var i = 0; i < this._textures.length; i++) {
  52041. this._engine._releaseTexture(this._textures.data[i]);
  52042. }
  52043. this._textures.reset();
  52044. }
  52045. this.width = desiredWidth;
  52046. this.height = desiredHeight;
  52047. var textureSize = { width: this.width, height: this.height };
  52048. var textureOptions = {
  52049. generateMipMaps: false,
  52050. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  52051. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  52052. samplingMode: this.renderTargetSamplingMode,
  52053. type: this._textureType
  52054. };
  52055. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52056. if (this._reusable) {
  52057. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52058. }
  52059. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  52060. this.onSizeChangedObservable.notifyObservers(this);
  52061. }
  52062. this._textures.forEach(function (texture) {
  52063. if (texture.samples !== _this.samples) {
  52064. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  52065. }
  52066. });
  52067. }
  52068. var target;
  52069. if (this._shareOutputWithPostProcess) {
  52070. target = this._shareOutputWithPostProcess.outputTexture;
  52071. }
  52072. else if (this._forcedOutputTexture) {
  52073. target = this._forcedOutputTexture;
  52074. this.width = this._forcedOutputTexture.width;
  52075. this.height = this._forcedOutputTexture.height;
  52076. }
  52077. else {
  52078. target = this.outputTexture;
  52079. }
  52080. if (this.enablePixelPerfectMode) {
  52081. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  52082. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  52083. }
  52084. else {
  52085. this._scaleRatio.copyFromFloats(1, 1);
  52086. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  52087. }
  52088. this.onActivateObservable.notifyObservers(camera);
  52089. // Clear
  52090. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  52091. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  52092. }
  52093. if (this._reusable) {
  52094. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  52095. }
  52096. };
  52097. Object.defineProperty(PostProcess.prototype, "isSupported", {
  52098. get: function () {
  52099. return this._effect.isSupported;
  52100. },
  52101. enumerable: true,
  52102. configurable: true
  52103. });
  52104. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  52105. get: function () {
  52106. if (this._shareOutputWithPostProcess) {
  52107. return this._shareOutputWithPostProcess.aspectRatio;
  52108. }
  52109. if (this._forcedOutputTexture) {
  52110. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  52111. }
  52112. return this.width / this.height;
  52113. },
  52114. enumerable: true,
  52115. configurable: true
  52116. });
  52117. PostProcess.prototype.apply = function () {
  52118. // Check
  52119. if (!this._effect || !this._effect.isReady())
  52120. return null;
  52121. // States
  52122. this._engine.enableEffect(this._effect);
  52123. this._engine.setState(false);
  52124. this._engine.setDepthBuffer(false);
  52125. this._engine.setDepthWrite(false);
  52126. // Alpha
  52127. this._engine.setAlphaMode(this.alphaMode);
  52128. if (this.alphaConstants) {
  52129. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  52130. }
  52131. // Texture
  52132. var source;
  52133. if (this._shareOutputWithPostProcess) {
  52134. source = this._shareOutputWithPostProcess.outputTexture;
  52135. }
  52136. else if (this._forcedOutputTexture) {
  52137. source = this._forcedOutputTexture;
  52138. }
  52139. else {
  52140. source = this.outputTexture;
  52141. }
  52142. this._effect._bindTexture("textureSampler", source);
  52143. // Parameters
  52144. this._effect.setVector2("scale", this._scaleRatio);
  52145. this.onApplyObservable.notifyObservers(this._effect);
  52146. return this._effect;
  52147. };
  52148. PostProcess.prototype._disposeTextures = function () {
  52149. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  52150. return;
  52151. }
  52152. if (this._textures.length > 0) {
  52153. for (var i = 0; i < this._textures.length; i++) {
  52154. this._engine._releaseTexture(this._textures.data[i]);
  52155. }
  52156. }
  52157. this._textures.dispose();
  52158. };
  52159. PostProcess.prototype.dispose = function (camera) {
  52160. camera = camera || this._camera;
  52161. this._disposeTextures();
  52162. if (this._scene) {
  52163. var index_1 = this._scene.postProcesses.indexOf(this);
  52164. if (index_1 !== -1) {
  52165. this._scene.postProcesses.splice(index_1, 1);
  52166. }
  52167. }
  52168. else {
  52169. var index_2 = this._engine.postProcesses.indexOf(this);
  52170. if (index_2 !== -1) {
  52171. this._engine.postProcesses.splice(index_2, 1);
  52172. }
  52173. }
  52174. if (!camera) {
  52175. return;
  52176. }
  52177. camera.detachPostProcess(this);
  52178. var index = camera._postProcesses.indexOf(this);
  52179. if (index === 0 && camera._postProcesses.length > 0) {
  52180. this._camera._postProcesses[0].markTextureDirty();
  52181. }
  52182. this.onActivateObservable.clear();
  52183. this.onAfterRenderObservable.clear();
  52184. this.onApplyObservable.clear();
  52185. this.onBeforeRenderObservable.clear();
  52186. this.onSizeChangedObservable.clear();
  52187. };
  52188. return PostProcess;
  52189. }());
  52190. BABYLON.PostProcess = PostProcess;
  52191. })(BABYLON || (BABYLON = {}));
  52192. //# sourceMappingURL=babylon.postProcess.js.map
  52193. var BABYLON;
  52194. (function (BABYLON) {
  52195. var PassPostProcess = /** @class */ (function (_super) {
  52196. __extends(PassPostProcess, _super);
  52197. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52198. if (camera === void 0) { camera = null; }
  52199. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52200. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  52201. }
  52202. return PassPostProcess;
  52203. }(BABYLON.PostProcess));
  52204. BABYLON.PassPostProcess = PassPostProcess;
  52205. })(BABYLON || (BABYLON = {}));
  52206. //# sourceMappingURL=babylon.passPostProcess.js.map
  52207. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52208. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52209. s = arguments[i];
  52210. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52211. t[p] = s[p];
  52212. }
  52213. return t;
  52214. };
  52215. var BABYLON;
  52216. (function (BABYLON) {
  52217. var ShadowGenerator = /** @class */ (function () {
  52218. /**
  52219. * Creates a ShadowGenerator object.
  52220. * A ShadowGenerator is the required tool to use the shadows.
  52221. * Each light casting shadows needs to use its own ShadowGenerator.
  52222. * Required parameters :
  52223. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  52224. * - `light`: the light object generating the shadows.
  52225. * - `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.
  52226. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  52227. */
  52228. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  52229. // Members
  52230. this._bias = 0.00005;
  52231. this._blurBoxOffset = 1;
  52232. this._blurScale = 2;
  52233. this._blurKernel = 1;
  52234. this._useKernelBlur = false;
  52235. this._filter = ShadowGenerator.FILTER_NONE;
  52236. this._darkness = 0;
  52237. this._transparencyShadow = false;
  52238. /**
  52239. * Controls the extent to which the shadows fade out at the edge of the frustum
  52240. * Used only by directionals and spots
  52241. */
  52242. this.frustumEdgeFalloff = 0;
  52243. this.forceBackFacesOnly = false;
  52244. this._lightDirection = BABYLON.Vector3.Zero();
  52245. this._viewMatrix = BABYLON.Matrix.Zero();
  52246. this._projectionMatrix = BABYLON.Matrix.Zero();
  52247. this._transformMatrix = BABYLON.Matrix.Zero();
  52248. this._currentFaceIndex = 0;
  52249. this._currentFaceIndexCache = 0;
  52250. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  52251. this._mapSize = mapSize;
  52252. this._light = light;
  52253. this._scene = light.getScene();
  52254. light._shadowGenerator = this;
  52255. // Texture type fallback from float to int if not supported.
  52256. var caps = this._scene.getEngine().getCaps();
  52257. if (!useFullFloatFirst) {
  52258. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52259. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52260. }
  52261. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52262. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52263. }
  52264. else {
  52265. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52266. }
  52267. }
  52268. else {
  52269. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52270. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52271. }
  52272. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52273. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52274. }
  52275. else {
  52276. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52277. }
  52278. }
  52279. this._initializeGenerator();
  52280. }
  52281. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  52282. // Static
  52283. get: function () {
  52284. return ShadowGenerator._FILTER_NONE;
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  52290. get: function () {
  52291. return ShadowGenerator._FILTER_POISSONSAMPLING;
  52292. },
  52293. enumerable: true,
  52294. configurable: true
  52295. });
  52296. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  52297. get: function () {
  52298. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  52299. },
  52300. enumerable: true,
  52301. configurable: true
  52302. });
  52303. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  52304. get: function () {
  52305. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  52306. },
  52307. enumerable: true,
  52308. configurable: true
  52309. });
  52310. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  52311. get: function () {
  52312. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52313. },
  52314. enumerable: true,
  52315. configurable: true
  52316. });
  52317. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  52318. get: function () {
  52319. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52320. },
  52321. enumerable: true,
  52322. configurable: true
  52323. });
  52324. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  52325. get: function () {
  52326. return this._bias;
  52327. },
  52328. set: function (bias) {
  52329. this._bias = bias;
  52330. },
  52331. enumerable: true,
  52332. configurable: true
  52333. });
  52334. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  52335. get: function () {
  52336. return this._blurBoxOffset;
  52337. },
  52338. set: function (value) {
  52339. if (this._blurBoxOffset === value) {
  52340. return;
  52341. }
  52342. this._blurBoxOffset = value;
  52343. this._disposeBlurPostProcesses();
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  52349. get: function () {
  52350. return this._blurScale;
  52351. },
  52352. set: function (value) {
  52353. if (this._blurScale === value) {
  52354. return;
  52355. }
  52356. this._blurScale = value;
  52357. this._disposeBlurPostProcesses();
  52358. },
  52359. enumerable: true,
  52360. configurable: true
  52361. });
  52362. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  52363. get: function () {
  52364. return this._blurKernel;
  52365. },
  52366. set: function (value) {
  52367. if (this._blurKernel === value) {
  52368. return;
  52369. }
  52370. this._blurKernel = value;
  52371. this._disposeBlurPostProcesses();
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52377. get: function () {
  52378. return this._useKernelBlur;
  52379. },
  52380. set: function (value) {
  52381. if (this._useKernelBlur === value) {
  52382. return;
  52383. }
  52384. this._useKernelBlur = value;
  52385. this._disposeBlurPostProcesses();
  52386. },
  52387. enumerable: true,
  52388. configurable: true
  52389. });
  52390. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52391. get: function () {
  52392. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52393. },
  52394. set: function (value) {
  52395. this._depthScale = value;
  52396. },
  52397. enumerable: true,
  52398. configurable: true
  52399. });
  52400. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52401. get: function () {
  52402. return this._filter;
  52403. },
  52404. set: function (value) {
  52405. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  52406. if (this._light.needCube()) {
  52407. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52408. this.useExponentialShadowMap = true;
  52409. return;
  52410. }
  52411. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52412. this.useCloseExponentialShadowMap = true;
  52413. return;
  52414. }
  52415. }
  52416. if (this._filter === value) {
  52417. return;
  52418. }
  52419. this._filter = value;
  52420. this._disposeBlurPostProcesses();
  52421. this._applyFilterValues();
  52422. this._light._markMeshesAsLightDirty();
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  52428. get: function () {
  52429. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  52430. },
  52431. set: function (value) {
  52432. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  52433. return;
  52434. }
  52435. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52441. get: function () {
  52442. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52443. return this.useExponentialShadowMap;
  52444. },
  52445. set: function (value) {
  52446. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52447. this.useExponentialShadowMap = value;
  52448. },
  52449. enumerable: true,
  52450. configurable: true
  52451. });
  52452. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52453. get: function () {
  52454. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52455. return this.useBlurExponentialShadowMap;
  52456. },
  52457. set: function (value) {
  52458. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52459. this.useBlurExponentialShadowMap = value;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52465. get: function () {
  52466. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52467. },
  52468. set: function (value) {
  52469. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52470. return;
  52471. }
  52472. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52478. get: function () {
  52479. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52480. },
  52481. set: function (value) {
  52482. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52483. return;
  52484. }
  52485. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52491. get: function () {
  52492. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52493. },
  52494. set: function (value) {
  52495. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52496. return;
  52497. }
  52498. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52499. },
  52500. enumerable: true,
  52501. configurable: true
  52502. });
  52503. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52504. get: function () {
  52505. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52506. },
  52507. set: function (value) {
  52508. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52509. return;
  52510. }
  52511. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. /**
  52517. * Returns the darkness value (float).
  52518. */
  52519. ShadowGenerator.prototype.getDarkness = function () {
  52520. return this._darkness;
  52521. };
  52522. /**
  52523. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52524. * Returns the ShadowGenerator.
  52525. */
  52526. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52527. if (darkness >= 1.0)
  52528. this._darkness = 1.0;
  52529. else if (darkness <= 0.0)
  52530. this._darkness = 0.0;
  52531. else
  52532. this._darkness = darkness;
  52533. return this;
  52534. };
  52535. /**
  52536. * Sets the ability to have transparent shadow (boolean).
  52537. * Returns the ShadowGenerator.
  52538. */
  52539. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52540. this._transparencyShadow = hasShadow;
  52541. return this;
  52542. };
  52543. /**
  52544. * Returns a RenderTargetTexture object : the shadow map texture.
  52545. */
  52546. ShadowGenerator.prototype.getShadowMap = function () {
  52547. return this._shadowMap;
  52548. };
  52549. /**
  52550. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52551. */
  52552. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52553. if (this._shadowMap2) {
  52554. return this._shadowMap2;
  52555. }
  52556. return this._shadowMap;
  52557. };
  52558. /**
  52559. * Helper function to add a mesh and its descendants to the list of shadow casters
  52560. * @param mesh Mesh to add
  52561. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52562. */
  52563. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52564. if (includeDescendants === void 0) { includeDescendants = true; }
  52565. if (!this._shadowMap) {
  52566. return this;
  52567. }
  52568. if (!this._shadowMap.renderList) {
  52569. this._shadowMap.renderList = [];
  52570. }
  52571. this._shadowMap.renderList.push(mesh);
  52572. if (includeDescendants) {
  52573. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52574. }
  52575. return this;
  52576. var _a;
  52577. };
  52578. /**
  52579. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52580. * @param mesh Mesh to remove
  52581. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52582. */
  52583. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52584. if (includeDescendants === void 0) { includeDescendants = true; }
  52585. if (!this._shadowMap || !this._shadowMap.renderList) {
  52586. return this;
  52587. }
  52588. var index = this._shadowMap.renderList.indexOf(mesh);
  52589. if (index !== -1) {
  52590. this._shadowMap.renderList.splice(index, 1);
  52591. }
  52592. if (includeDescendants) {
  52593. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52594. var child = _a[_i];
  52595. this.removeShadowCaster(child);
  52596. }
  52597. }
  52598. return this;
  52599. };
  52600. /**
  52601. * Returns the associated light object.
  52602. */
  52603. ShadowGenerator.prototype.getLight = function () {
  52604. return this._light;
  52605. };
  52606. ShadowGenerator.prototype._initializeGenerator = function () {
  52607. this._light._markMeshesAsLightDirty();
  52608. this._initializeShadowMap();
  52609. };
  52610. ShadowGenerator.prototype._initializeShadowMap = function () {
  52611. var _this = this;
  52612. // Render target
  52613. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52614. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52615. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52616. this._shadowMap.anisotropicFilteringLevel = 1;
  52617. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52618. this._shadowMap.renderParticles = false;
  52619. this._shadowMap.ignoreCameraViewport = true;
  52620. // Record Face Index before render.
  52621. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52622. _this._currentFaceIndex = faceIndex;
  52623. });
  52624. // Custom render function.
  52625. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52626. // Blur if required afer render.
  52627. this._shadowMap.onAfterUnbindObservable.add(function () {
  52628. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52629. return;
  52630. }
  52631. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52632. _this._initializeBlurRTTAndPostProcesses();
  52633. }
  52634. var shadowMap = _this.getShadowMapForRendering();
  52635. if (shadowMap) {
  52636. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52637. }
  52638. });
  52639. // Clear according to the chosen filter.
  52640. this._shadowMap.onClearObservable.add(function (engine) {
  52641. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52642. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52643. }
  52644. else {
  52645. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52646. }
  52647. });
  52648. };
  52649. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52650. var _this = this;
  52651. var engine = this._scene.getEngine();
  52652. var targetSize = this._mapSize / this.blurScale;
  52653. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52654. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52655. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52656. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52657. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52658. }
  52659. if (this.useKernelBlur) {
  52660. 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);
  52661. this._kernelBlurXPostprocess.width = targetSize;
  52662. this._kernelBlurXPostprocess.height = targetSize;
  52663. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52664. effect.setTexture("textureSampler", _this._shadowMap);
  52665. });
  52666. 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);
  52667. this._kernelBlurXPostprocess.autoClear = false;
  52668. this._kernelBlurYPostprocess.autoClear = false;
  52669. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52670. this._kernelBlurXPostprocess.packedFloat = true;
  52671. this._kernelBlurYPostprocess.packedFloat = true;
  52672. }
  52673. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52674. }
  52675. else {
  52676. 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);
  52677. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52678. effect.setFloat2("screenSize", targetSize, targetSize);
  52679. effect.setTexture("textureSampler", _this._shadowMap);
  52680. });
  52681. this._boxBlurPostprocess.autoClear = false;
  52682. this._blurPostProcesses = [this._boxBlurPostprocess];
  52683. }
  52684. };
  52685. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52686. var index;
  52687. var engine = this._scene.getEngine();
  52688. if (depthOnlySubMeshes.length) {
  52689. engine.setColorWrite(false);
  52690. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52691. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52692. }
  52693. engine.setColorWrite(true);
  52694. }
  52695. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52696. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52697. }
  52698. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52699. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52700. }
  52701. if (this._transparencyShadow) {
  52702. for (index = 0; index < transparentSubMeshes.length; index++) {
  52703. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52704. }
  52705. }
  52706. };
  52707. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52708. var _this = this;
  52709. var mesh = subMesh.getRenderingMesh();
  52710. var scene = this._scene;
  52711. var engine = scene.getEngine();
  52712. var material = subMesh.getMaterial();
  52713. if (!material) {
  52714. return;
  52715. }
  52716. // Culling
  52717. engine.setState(material.backFaceCulling);
  52718. // Managing instances
  52719. var batch = mesh._getInstancesRenderList(subMesh._id);
  52720. if (batch.mustReturn) {
  52721. return;
  52722. }
  52723. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52724. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52725. engine.enableEffect(this._effect);
  52726. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52727. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52728. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52729. this._effect.setVector3("lightPosition", this.getLight().position);
  52730. if (scene.activeCamera) {
  52731. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52732. }
  52733. // Alpha test
  52734. if (material && material.needAlphaTesting()) {
  52735. var alphaTexture = material.getAlphaTestTexture();
  52736. if (alphaTexture) {
  52737. this._effect.setTexture("diffuseSampler", alphaTexture);
  52738. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52739. }
  52740. }
  52741. // Bones
  52742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52743. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52744. }
  52745. if (this.forceBackFacesOnly) {
  52746. engine.setState(true, 0, false, true);
  52747. }
  52748. // Draw
  52749. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52750. if (this.forceBackFacesOnly) {
  52751. engine.setState(true, 0, false, false);
  52752. }
  52753. }
  52754. else {
  52755. // Need to reset refresh rate of the shadowMap
  52756. if (this._shadowMap) {
  52757. this._shadowMap.resetRefreshCounter();
  52758. }
  52759. }
  52760. };
  52761. ShadowGenerator.prototype._applyFilterValues = function () {
  52762. if (!this._shadowMap) {
  52763. return;
  52764. }
  52765. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52766. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52767. }
  52768. else {
  52769. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52770. }
  52771. };
  52772. /**
  52773. * Force shader compilation including textures ready check
  52774. */
  52775. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52776. var _this = this;
  52777. var localOptions = __assign({ useInstances: false }, options);
  52778. var shadowMap = this.getShadowMap();
  52779. if (!shadowMap) {
  52780. if (onCompiled) {
  52781. onCompiled(this);
  52782. }
  52783. return;
  52784. }
  52785. var renderList = shadowMap.renderList;
  52786. if (!renderList) {
  52787. if (onCompiled) {
  52788. onCompiled(this);
  52789. }
  52790. return;
  52791. }
  52792. var subMeshes = new Array();
  52793. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52794. var mesh = renderList_1[_i];
  52795. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52796. }
  52797. if (subMeshes.length === 0) {
  52798. if (onCompiled) {
  52799. onCompiled(this);
  52800. }
  52801. return;
  52802. }
  52803. var currentIndex = 0;
  52804. var checkReady = function () {
  52805. if (!_this._scene || !_this._scene.getEngine()) {
  52806. return;
  52807. }
  52808. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52809. currentIndex++;
  52810. if (currentIndex >= subMeshes.length) {
  52811. if (onCompiled) {
  52812. onCompiled(_this);
  52813. }
  52814. return;
  52815. }
  52816. }
  52817. setTimeout(checkReady, 16);
  52818. };
  52819. checkReady();
  52820. };
  52821. /**
  52822. * Boolean : true when the ShadowGenerator is finally computed.
  52823. */
  52824. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52825. var defines = [];
  52826. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52827. defines.push("#define FLOAT");
  52828. }
  52829. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52830. defines.push("#define ESM");
  52831. }
  52832. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52833. var mesh = subMesh.getMesh();
  52834. var material = subMesh.getMaterial();
  52835. // Alpha test
  52836. if (material && material.needAlphaTesting()) {
  52837. var alphaTexture = material.getAlphaTestTexture();
  52838. if (alphaTexture) {
  52839. defines.push("#define ALPHATEST");
  52840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52841. attribs.push(BABYLON.VertexBuffer.UVKind);
  52842. defines.push("#define UV1");
  52843. }
  52844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52845. if (alphaTexture.coordinatesIndex === 1) {
  52846. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52847. defines.push("#define UV2");
  52848. }
  52849. }
  52850. }
  52851. }
  52852. // Bones
  52853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52856. if (mesh.numBoneInfluencers > 4) {
  52857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52859. }
  52860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52861. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52862. }
  52863. else {
  52864. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52865. }
  52866. // Instances
  52867. if (useInstances) {
  52868. defines.push("#define INSTANCES");
  52869. attribs.push("world0");
  52870. attribs.push("world1");
  52871. attribs.push("world2");
  52872. attribs.push("world3");
  52873. }
  52874. // Get correct effect
  52875. var join = defines.join("\n");
  52876. if (this._cachedDefines !== join) {
  52877. this._cachedDefines = join;
  52878. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52879. }
  52880. return this._effect.isReady();
  52881. };
  52882. /**
  52883. * This creates the defines related to the standard BJS materials.
  52884. */
  52885. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52886. var scene = this._scene;
  52887. var light = this._light;
  52888. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52889. return;
  52890. }
  52891. defines["SHADOW" + lightIndex] = true;
  52892. if (this.usePoissonSampling) {
  52893. defines["SHADOWPCF" + lightIndex] = true;
  52894. }
  52895. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52896. defines["SHADOWESM" + lightIndex] = true;
  52897. }
  52898. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52899. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52900. }
  52901. if (light.needCube()) {
  52902. defines["SHADOWCUBE" + lightIndex] = true;
  52903. }
  52904. };
  52905. /**
  52906. * This binds shadow lights related to the standard BJS materials.
  52907. * It implies the unifroms available on the materials are the standard BJS ones.
  52908. */
  52909. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52910. var light = this._light;
  52911. var scene = this._scene;
  52912. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52913. return;
  52914. }
  52915. var camera = scene.activeCamera;
  52916. if (!camera) {
  52917. return;
  52918. }
  52919. var shadowMap = this.getShadowMap();
  52920. if (!shadowMap) {
  52921. return;
  52922. }
  52923. if (!light.needCube()) {
  52924. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52925. }
  52926. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52927. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52928. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52929. };
  52930. // Methods
  52931. /**
  52932. * Returns a Matrix object : the updated transformation matrix.
  52933. */
  52934. ShadowGenerator.prototype.getTransformMatrix = function () {
  52935. var scene = this._scene;
  52936. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52937. return this._transformMatrix;
  52938. }
  52939. this._currentRenderID = scene.getRenderId();
  52940. this._currentFaceIndexCache = this._currentFaceIndex;
  52941. var lightPosition = this._light.position;
  52942. if (this._light.computeTransformedInformation()) {
  52943. lightPosition = this._light.transformedPosition;
  52944. }
  52945. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52946. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52947. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52948. }
  52949. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52950. this._cachedPosition = lightPosition.clone();
  52951. this._cachedDirection = this._lightDirection.clone();
  52952. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52953. var shadowMap = this.getShadowMap();
  52954. if (shadowMap) {
  52955. var renderList = shadowMap.renderList;
  52956. if (renderList) {
  52957. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52958. }
  52959. }
  52960. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52961. }
  52962. return this._transformMatrix;
  52963. };
  52964. ShadowGenerator.prototype.recreateShadowMap = function () {
  52965. var shadowMap = this._shadowMap;
  52966. if (!shadowMap) {
  52967. return;
  52968. }
  52969. // Track render list.
  52970. var renderList = shadowMap.renderList;
  52971. // Clean up existing data.
  52972. this._disposeRTTandPostProcesses();
  52973. // Reinitializes.
  52974. this._initializeGenerator();
  52975. // Reaffect the filter to ensure a correct fallback if necessary.
  52976. this.filter = this.filter;
  52977. // Reaffect the filter.
  52978. this._applyFilterValues();
  52979. // Reaffect Render List.
  52980. this._shadowMap.renderList = renderList;
  52981. };
  52982. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52983. if (this._shadowMap2) {
  52984. this._shadowMap2.dispose();
  52985. this._shadowMap2 = null;
  52986. }
  52987. if (this._downSamplePostprocess) {
  52988. this._downSamplePostprocess.dispose();
  52989. this._downSamplePostprocess = null;
  52990. }
  52991. if (this._boxBlurPostprocess) {
  52992. this._boxBlurPostprocess.dispose();
  52993. this._boxBlurPostprocess = null;
  52994. }
  52995. if (this._kernelBlurXPostprocess) {
  52996. this._kernelBlurXPostprocess.dispose();
  52997. this._kernelBlurXPostprocess = null;
  52998. }
  52999. if (this._kernelBlurYPostprocess) {
  53000. this._kernelBlurYPostprocess.dispose();
  53001. this._kernelBlurYPostprocess = null;
  53002. }
  53003. this._blurPostProcesses = [];
  53004. };
  53005. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53006. if (this._shadowMap) {
  53007. this._shadowMap.dispose();
  53008. this._shadowMap = null;
  53009. }
  53010. this._disposeBlurPostProcesses();
  53011. };
  53012. /**
  53013. * Disposes the ShadowGenerator.
  53014. * Returns nothing.
  53015. */
  53016. ShadowGenerator.prototype.dispose = function () {
  53017. this._disposeRTTandPostProcesses();
  53018. if (this._light) {
  53019. this._light._shadowGenerator = null;
  53020. this._light._markMeshesAsLightDirty();
  53021. }
  53022. };
  53023. /**
  53024. * Serializes the ShadowGenerator and returns a serializationObject.
  53025. */
  53026. ShadowGenerator.prototype.serialize = function () {
  53027. var serializationObject = {};
  53028. var shadowMap = this.getShadowMap();
  53029. if (!shadowMap) {
  53030. return serializationObject;
  53031. }
  53032. serializationObject.lightId = this._light.id;
  53033. serializationObject.mapSize = shadowMap.getRenderSize();
  53034. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53035. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53036. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53037. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53038. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53039. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53040. serializationObject.depthScale = this.depthScale;
  53041. serializationObject.darkness = this.getDarkness();
  53042. serializationObject.blurBoxOffset = this.blurBoxOffset;
  53043. serializationObject.blurKernel = this.blurKernel;
  53044. serializationObject.blurScale = this.blurScale;
  53045. serializationObject.useKernelBlur = this.useKernelBlur;
  53046. serializationObject.transparencyShadow = this._transparencyShadow;
  53047. serializationObject.renderList = [];
  53048. if (shadowMap.renderList) {
  53049. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  53050. var mesh = shadowMap.renderList[meshIndex];
  53051. serializationObject.renderList.push(mesh.id);
  53052. }
  53053. }
  53054. return serializationObject;
  53055. };
  53056. /**
  53057. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  53058. */
  53059. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  53060. //casting to point light, as light is missing the position attr and typescript complains.
  53061. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  53062. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  53063. var shadowMap = shadowGenerator.getShadowMap();
  53064. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  53065. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  53066. meshes.forEach(function (mesh) {
  53067. if (!shadowMap) {
  53068. return;
  53069. }
  53070. if (!shadowMap.renderList) {
  53071. shadowMap.renderList = [];
  53072. }
  53073. shadowMap.renderList.push(mesh);
  53074. });
  53075. }
  53076. if (parsedShadowGenerator.usePoissonSampling) {
  53077. shadowGenerator.usePoissonSampling = true;
  53078. }
  53079. else if (parsedShadowGenerator.useExponentialShadowMap) {
  53080. shadowGenerator.useExponentialShadowMap = true;
  53081. }
  53082. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  53083. shadowGenerator.useBlurExponentialShadowMap = true;
  53084. }
  53085. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  53086. shadowGenerator.useCloseExponentialShadowMap = true;
  53087. }
  53088. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  53089. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  53090. }
  53091. else if (parsedShadowGenerator.useVarianceShadowMap) {
  53092. shadowGenerator.useExponentialShadowMap = true;
  53093. }
  53094. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  53095. shadowGenerator.useBlurExponentialShadowMap = true;
  53096. }
  53097. if (parsedShadowGenerator.depthScale) {
  53098. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  53099. }
  53100. if (parsedShadowGenerator.blurScale) {
  53101. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  53102. }
  53103. if (parsedShadowGenerator.blurBoxOffset) {
  53104. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  53105. }
  53106. if (parsedShadowGenerator.useKernelBlur) {
  53107. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  53108. }
  53109. if (parsedShadowGenerator.blurKernel) {
  53110. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  53111. }
  53112. if (parsedShadowGenerator.bias !== undefined) {
  53113. shadowGenerator.bias = parsedShadowGenerator.bias;
  53114. }
  53115. if (parsedShadowGenerator.darkness) {
  53116. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  53117. }
  53118. if (parsedShadowGenerator.transparencyShadow) {
  53119. shadowGenerator.setTransparencyShadow(true);
  53120. }
  53121. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  53122. return shadowGenerator;
  53123. };
  53124. ShadowGenerator._FILTER_NONE = 0;
  53125. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  53126. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  53127. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  53128. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  53129. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  53130. return ShadowGenerator;
  53131. }());
  53132. BABYLON.ShadowGenerator = ShadowGenerator;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.shadowGenerator.js.map
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var DefaultLoadingScreen = /** @class */ (function () {
  53138. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  53139. if (_loadingText === void 0) { _loadingText = ""; }
  53140. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  53141. var _this = this;
  53142. this._renderingCanvas = _renderingCanvas;
  53143. this._loadingText = _loadingText;
  53144. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  53145. // Resize
  53146. this._resizeLoadingUI = function () {
  53147. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  53148. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  53149. if (!_this._loadingDiv) {
  53150. return;
  53151. }
  53152. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  53153. _this._loadingDiv.style.left = canvasRect.left + "px";
  53154. _this._loadingDiv.style.top = canvasRect.top + "px";
  53155. _this._loadingDiv.style.width = canvasRect.width + "px";
  53156. _this._loadingDiv.style.height = canvasRect.height + "px";
  53157. };
  53158. }
  53159. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  53160. if (this._loadingDiv) {
  53161. // Do not add a loading screen if there is already one
  53162. return;
  53163. }
  53164. this._loadingDiv = document.createElement("div");
  53165. this._loadingDiv.id = "babylonjsLoadingDiv";
  53166. this._loadingDiv.style.opacity = "0";
  53167. this._loadingDiv.style.transition = "opacity 1.5s ease";
  53168. this._loadingDiv.style.pointerEvents = "none";
  53169. // Loading text
  53170. this._loadingTextDiv = document.createElement("div");
  53171. this._loadingTextDiv.style.position = "absolute";
  53172. this._loadingTextDiv.style.left = "0";
  53173. this._loadingTextDiv.style.top = "50%";
  53174. this._loadingTextDiv.style.marginTop = "80px";
  53175. this._loadingTextDiv.style.width = "100%";
  53176. this._loadingTextDiv.style.height = "20px";
  53177. this._loadingTextDiv.style.fontFamily = "Arial";
  53178. this._loadingTextDiv.style.fontSize = "14px";
  53179. this._loadingTextDiv.style.color = "white";
  53180. this._loadingTextDiv.style.textAlign = "center";
  53181. this._loadingTextDiv.innerHTML = "Loading";
  53182. this._loadingDiv.appendChild(this._loadingTextDiv);
  53183. //set the predefined text
  53184. this._loadingTextDiv.innerHTML = this._loadingText;
  53185. // Generating keyframes
  53186. var style = document.createElement('style');
  53187. style.type = 'text/css';
  53188. 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 }";
  53189. style.innerHTML = keyFrames;
  53190. document.getElementsByTagName('head')[0].appendChild(style);
  53191. // Loading img
  53192. var imgBack = new Image();
  53193. 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";
  53194. imgBack.style.position = "absolute";
  53195. imgBack.style.left = "50%";
  53196. imgBack.style.top = "50%";
  53197. imgBack.style.marginLeft = "-60px";
  53198. imgBack.style.marginTop = "-60px";
  53199. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  53200. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  53201. imgBack.style.transformOrigin = "50% 50%";
  53202. imgBack.style.webkitTransformOrigin = "50% 50%";
  53203. this._loadingDiv.appendChild(imgBack);
  53204. this._resizeLoadingUI();
  53205. window.addEventListener("resize", this._resizeLoadingUI);
  53206. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53207. document.body.appendChild(this._loadingDiv);
  53208. this._loadingDiv.style.opacity = "1";
  53209. };
  53210. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  53211. var _this = this;
  53212. if (!this._loadingDiv) {
  53213. return;
  53214. }
  53215. var onTransitionEnd = function () {
  53216. if (!_this._loadingDiv) {
  53217. return;
  53218. }
  53219. document.body.removeChild(_this._loadingDiv);
  53220. window.removeEventListener("resize", _this._resizeLoadingUI);
  53221. _this._loadingDiv = null;
  53222. };
  53223. this._loadingDiv.style.opacity = "0";
  53224. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  53225. };
  53226. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  53227. set: function (text) {
  53228. this._loadingText = text;
  53229. if (this._loadingTextDiv) {
  53230. this._loadingTextDiv.innerHTML = this._loadingText;
  53231. }
  53232. },
  53233. enumerable: true,
  53234. configurable: true
  53235. });
  53236. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  53237. get: function () {
  53238. return this._loadingDivBackgroundColor;
  53239. },
  53240. set: function (color) {
  53241. this._loadingDivBackgroundColor = color;
  53242. if (!this._loadingDiv) {
  53243. return;
  53244. }
  53245. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53246. },
  53247. enumerable: true,
  53248. configurable: true
  53249. });
  53250. return DefaultLoadingScreen;
  53251. }());
  53252. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  53253. })(BABYLON || (BABYLON = {}));
  53254. //# sourceMappingURL=babylon.loadingScreen.js.map
  53255. var BABYLON;
  53256. (function (BABYLON) {
  53257. var SceneLoader = /** @class */ (function () {
  53258. function SceneLoader() {
  53259. }
  53260. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  53261. get: function () {
  53262. return 0;
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  53268. get: function () {
  53269. return 1;
  53270. },
  53271. enumerable: true,
  53272. configurable: true
  53273. });
  53274. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  53275. get: function () {
  53276. return 2;
  53277. },
  53278. enumerable: true,
  53279. configurable: true
  53280. });
  53281. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  53282. get: function () {
  53283. return 3;
  53284. },
  53285. enumerable: true,
  53286. configurable: true
  53287. });
  53288. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  53289. get: function () {
  53290. return SceneLoader._ForceFullSceneLoadingForIncremental;
  53291. },
  53292. set: function (value) {
  53293. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  53294. },
  53295. enumerable: true,
  53296. configurable: true
  53297. });
  53298. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  53299. get: function () {
  53300. return SceneLoader._ShowLoadingScreen;
  53301. },
  53302. set: function (value) {
  53303. SceneLoader._ShowLoadingScreen = value;
  53304. },
  53305. enumerable: true,
  53306. configurable: true
  53307. });
  53308. Object.defineProperty(SceneLoader, "loggingLevel", {
  53309. get: function () {
  53310. return SceneLoader._loggingLevel;
  53311. },
  53312. set: function (value) {
  53313. SceneLoader._loggingLevel = value;
  53314. },
  53315. enumerable: true,
  53316. configurable: true
  53317. });
  53318. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  53319. get: function () {
  53320. return SceneLoader._CleanBoneMatrixWeights;
  53321. },
  53322. set: function (value) {
  53323. SceneLoader._CleanBoneMatrixWeights = value;
  53324. },
  53325. enumerable: true,
  53326. configurable: true
  53327. });
  53328. SceneLoader._getDefaultPlugin = function () {
  53329. return SceneLoader._registeredPlugins[".babylon"];
  53330. };
  53331. SceneLoader._getPluginForExtension = function (extension) {
  53332. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  53333. if (registeredPlugin) {
  53334. return registeredPlugin;
  53335. }
  53336. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  53337. return SceneLoader._getDefaultPlugin();
  53338. };
  53339. SceneLoader._getPluginForDirectLoad = function (data) {
  53340. for (var extension in SceneLoader._registeredPlugins) {
  53341. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  53342. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  53343. return SceneLoader._registeredPlugins[extension];
  53344. }
  53345. }
  53346. return SceneLoader._getDefaultPlugin();
  53347. };
  53348. SceneLoader._getPluginForFilename = function (sceneFilename) {
  53349. if (sceneFilename.name) {
  53350. sceneFilename = sceneFilename.name;
  53351. }
  53352. var queryStringPosition = sceneFilename.indexOf("?");
  53353. if (queryStringPosition !== -1) {
  53354. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  53355. }
  53356. var dotPosition = sceneFilename.lastIndexOf(".");
  53357. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  53358. return SceneLoader._getPluginForExtension(extension);
  53359. };
  53360. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  53361. SceneLoader._getDirectLoad = function (sceneFilename) {
  53362. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  53363. return sceneFilename.substr(5);
  53364. }
  53365. return null;
  53366. };
  53367. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53368. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  53369. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  53370. var plugin;
  53371. if (registeredPlugin.plugin.createPlugin) {
  53372. plugin = registeredPlugin.plugin.createPlugin();
  53373. }
  53374. else {
  53375. plugin = registeredPlugin.plugin;
  53376. }
  53377. var useArrayBuffer = registeredPlugin.isBinary;
  53378. var database;
  53379. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53380. var dataCallback = function (data, responseURL) {
  53381. if (scene.isDisposed) {
  53382. onError("Scene has been disposed");
  53383. return;
  53384. }
  53385. scene.database = database;
  53386. onSuccess(plugin, data, responseURL);
  53387. };
  53388. var manifestChecked = function (success) {
  53389. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request, exception) {
  53390. if (request) {
  53391. onError(request.status + " " + request.statusText, exception);
  53392. }
  53393. });
  53394. };
  53395. if (directLoad) {
  53396. dataCallback(directLoad);
  53397. return plugin;
  53398. }
  53399. if (rootUrl.indexOf("file:") === -1) {
  53400. if (scene.getEngine().enableOfflineSupport) {
  53401. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  53402. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  53403. }
  53404. else {
  53405. manifestChecked(true);
  53406. }
  53407. }
  53408. else {
  53409. var fileOrString = sceneFilename;
  53410. if (fileOrString.name) {
  53411. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  53412. }
  53413. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  53414. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  53415. }
  53416. else {
  53417. onError("Unable to find file named " + sceneFilename);
  53418. }
  53419. }
  53420. return plugin;
  53421. };
  53422. // Public functions
  53423. SceneLoader.GetPluginForExtension = function (extension) {
  53424. return SceneLoader._getPluginForExtension(extension).plugin;
  53425. };
  53426. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  53427. return !!SceneLoader._registeredPlugins[extension];
  53428. };
  53429. SceneLoader.RegisterPlugin = function (plugin) {
  53430. if (typeof plugin.extensions === "string") {
  53431. var extension = plugin.extensions;
  53432. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53433. plugin: plugin,
  53434. isBinary: false
  53435. };
  53436. }
  53437. else {
  53438. var extensions = plugin.extensions;
  53439. Object.keys(extensions).forEach(function (extension) {
  53440. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53441. plugin: plugin,
  53442. isBinary: extensions[extension].isBinary
  53443. };
  53444. });
  53445. }
  53446. };
  53447. /**
  53448. * Import meshes into a scene
  53449. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53450. * @param rootUrl a string that defines the root url for scene and resources
  53451. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53452. * @param scene the instance of BABYLON.Scene to append to
  53453. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53454. * @param onProgress a callback with a progress event for each file being loaded
  53455. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53456. */
  53457. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53458. if (onSuccess === void 0) { onSuccess = null; }
  53459. if (onProgress === void 0) { onProgress = null; }
  53460. if (onError === void 0) { onError = null; }
  53461. if (pluginExtension === void 0) { pluginExtension = null; }
  53462. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53463. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53464. return null;
  53465. }
  53466. var loadingToken = {};
  53467. scene._addPendingData(loadingToken);
  53468. var errorHandler = function (message, exception) {
  53469. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  53470. if (onError) {
  53471. onError(scene, errorMessage, exception);
  53472. }
  53473. else {
  53474. BABYLON.Tools.Error(errorMessage);
  53475. // should the exception be thrown?
  53476. }
  53477. scene._removePendingData(loadingToken);
  53478. };
  53479. var progressHandler = onProgress ? function (event) {
  53480. try {
  53481. onProgress(event);
  53482. }
  53483. catch (e) {
  53484. errorHandler("Error in onProgress callback", e);
  53485. }
  53486. } : undefined;
  53487. var successHandler = function (meshes, particleSystems, skeletons) {
  53488. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53489. if (onSuccess) {
  53490. try {
  53491. onSuccess(meshes, particleSystems, skeletons);
  53492. }
  53493. catch (e) {
  53494. errorHandler("Error in onSuccess callback", e);
  53495. }
  53496. }
  53497. scene._removePendingData(loadingToken);
  53498. };
  53499. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53500. if (plugin.rewriteRootURL) {
  53501. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53502. }
  53503. if (plugin.importMesh) {
  53504. var syncedPlugin = plugin;
  53505. var meshes = new Array();
  53506. var particleSystems = new Array();
  53507. var skeletons = new Array();
  53508. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53509. return;
  53510. }
  53511. scene.loadingPluginName = plugin.name;
  53512. successHandler(meshes, particleSystems, skeletons);
  53513. }
  53514. else {
  53515. var asyncedPlugin = plugin;
  53516. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53517. scene.loadingPluginName = plugin.name;
  53518. successHandler(meshes, particleSystems, skeletons);
  53519. }, progressHandler, errorHandler);
  53520. }
  53521. }, progressHandler, errorHandler, pluginExtension);
  53522. };
  53523. /**
  53524. * Load a scene
  53525. * @param rootUrl a string that defines the root url for scene and resources
  53526. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53527. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53528. * @param onSuccess a callback with the scene when import succeeds
  53529. * @param onProgress a callback with a progress event for each file being loaded
  53530. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53531. */
  53532. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53533. if (onSuccess === void 0) { onSuccess = null; }
  53534. if (onProgress === void 0) { onProgress = null; }
  53535. if (onError === void 0) { onError = null; }
  53536. if (pluginExtension === void 0) { pluginExtension = null; }
  53537. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53538. };
  53539. /**
  53540. * Append a scene
  53541. * @param rootUrl a string that defines the root url for scene and resources
  53542. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53543. * @param scene is the instance of BABYLON.Scene to append to
  53544. * @param onSuccess a callback with the scene when import succeeds
  53545. * @param onProgress a callback with a progress event for each file being loaded
  53546. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53547. */
  53548. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53549. if (onSuccess === void 0) { onSuccess = null; }
  53550. if (onProgress === void 0) { onProgress = null; }
  53551. if (onError === void 0) { onError = null; }
  53552. if (pluginExtension === void 0) { pluginExtension = null; }
  53553. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53554. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53555. return null;
  53556. }
  53557. if (SceneLoader.ShowLoadingScreen) {
  53558. scene.getEngine().displayLoadingUI();
  53559. }
  53560. var loadingToken = {};
  53561. scene._addPendingData(loadingToken);
  53562. var errorHandler = function (message, exception) {
  53563. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53564. if (onError) {
  53565. onError(scene, errorMessage, exception);
  53566. }
  53567. else {
  53568. BABYLON.Tools.Error(errorMessage);
  53569. // should the exception be thrown?
  53570. }
  53571. scene._removePendingData(loadingToken);
  53572. scene.getEngine().hideLoadingUI();
  53573. };
  53574. var progressHandler = onProgress ? function (event) {
  53575. try {
  53576. onProgress(event);
  53577. }
  53578. catch (e) {
  53579. errorHandler("Error in onProgress callback", e);
  53580. }
  53581. } : undefined;
  53582. var successHandler = function () {
  53583. if (onSuccess) {
  53584. try {
  53585. onSuccess(scene);
  53586. }
  53587. catch (e) {
  53588. errorHandler("Error in onSuccess callback", e);
  53589. }
  53590. }
  53591. scene._removePendingData(loadingToken);
  53592. };
  53593. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53594. if (plugin.load) {
  53595. var syncedPlugin = plugin;
  53596. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53597. return;
  53598. }
  53599. scene.loadingPluginName = plugin.name;
  53600. successHandler();
  53601. }
  53602. else {
  53603. var asyncedPlugin = plugin;
  53604. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53605. scene.loadingPluginName = plugin.name;
  53606. successHandler();
  53607. }, progressHandler, errorHandler);
  53608. }
  53609. if (SceneLoader.ShowLoadingScreen) {
  53610. scene.executeWhenReady(function () {
  53611. scene.getEngine().hideLoadingUI();
  53612. });
  53613. }
  53614. }, progressHandler, errorHandler, pluginExtension);
  53615. };
  53616. // Flags
  53617. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53618. SceneLoader._ShowLoadingScreen = true;
  53619. SceneLoader._CleanBoneMatrixWeights = false;
  53620. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53621. // Members
  53622. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53623. SceneLoader._registeredPlugins = {};
  53624. return SceneLoader;
  53625. }());
  53626. BABYLON.SceneLoader = SceneLoader;
  53627. ;
  53628. })(BABYLON || (BABYLON = {}));
  53629. //# sourceMappingURL=babylon.sceneLoader.js.map
  53630. var BABYLON;
  53631. (function (BABYLON) {
  53632. var Internals;
  53633. (function (Internals) {
  53634. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53635. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53636. var parsedMaterial = parsedData.materials[index];
  53637. if (parsedMaterial.id === id) {
  53638. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53639. }
  53640. }
  53641. return null;
  53642. };
  53643. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53644. for (var i in names) {
  53645. if (mesh.name === names[i]) {
  53646. hierarchyIds.push(mesh.id);
  53647. return true;
  53648. }
  53649. }
  53650. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53651. hierarchyIds.push(mesh.id);
  53652. return true;
  53653. }
  53654. return false;
  53655. };
  53656. var logOperation = function (operation, producer) {
  53657. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53658. };
  53659. BABYLON.SceneLoader.RegisterPlugin({
  53660. name: "babylon.js",
  53661. extensions: ".babylon",
  53662. canDirectLoad: function (data) {
  53663. if (data.indexOf("babylon") !== -1) {
  53664. return true;
  53665. }
  53666. return false;
  53667. },
  53668. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53669. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53670. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53671. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53672. // and avoid problems with multiple concurrent .babylon loads.
  53673. var log = "importMesh has failed JSON parse";
  53674. try {
  53675. var parsedData = JSON.parse(data);
  53676. log = "";
  53677. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53678. if (!meshesNames) {
  53679. meshesNames = null;
  53680. }
  53681. else if (!Array.isArray(meshesNames)) {
  53682. meshesNames = [meshesNames];
  53683. }
  53684. var hierarchyIds = new Array();
  53685. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53686. var loadedSkeletonsIds = [];
  53687. var loadedMaterialsIds = [];
  53688. var index;
  53689. var cache;
  53690. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53691. var parsedMesh = parsedData.meshes[index];
  53692. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53693. if (meshesNames !== null) {
  53694. // Remove found mesh name from list.
  53695. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53696. }
  53697. //Geometry?
  53698. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53699. //does the file contain geometries?
  53700. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53701. //find the correct geometry and add it to the scene
  53702. var found = false;
  53703. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53704. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53705. return;
  53706. }
  53707. else {
  53708. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53709. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53710. switch (geometryType) {
  53711. case "boxes":
  53712. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53713. break;
  53714. case "spheres":
  53715. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53716. break;
  53717. case "cylinders":
  53718. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53719. break;
  53720. case "toruses":
  53721. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53722. break;
  53723. case "grounds":
  53724. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53725. break;
  53726. case "planes":
  53727. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53728. break;
  53729. case "torusKnots":
  53730. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53731. break;
  53732. case "vertexData":
  53733. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53734. break;
  53735. }
  53736. found = true;
  53737. }
  53738. });
  53739. }
  53740. });
  53741. if (found === false) {
  53742. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53743. }
  53744. }
  53745. }
  53746. // Material ?
  53747. if (parsedMesh.materialId) {
  53748. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53749. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53750. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53751. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53752. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53753. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53754. var subMatId = parsedMultiMaterial.materials[matIndex];
  53755. loadedMaterialsIds.push(subMatId);
  53756. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53757. log += "\n\tMaterial " + mat.toString(fullDetails);
  53758. }
  53759. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53760. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53761. materialFound = true;
  53762. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53763. break;
  53764. }
  53765. }
  53766. }
  53767. if (materialFound === false) {
  53768. loadedMaterialsIds.push(parsedMesh.materialId);
  53769. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53770. if (!mat) {
  53771. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53772. }
  53773. else {
  53774. log += "\n\tMaterial " + mat.toString(fullDetails);
  53775. }
  53776. }
  53777. }
  53778. // Skeleton ?
  53779. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53780. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53781. if (skeletonAlreadyLoaded === false) {
  53782. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53783. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53784. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53785. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53786. skeletons.push(skeleton);
  53787. loadedSkeletonsIds.push(parsedSkeleton.id);
  53788. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53789. }
  53790. }
  53791. }
  53792. }
  53793. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53794. meshes.push(mesh);
  53795. log += "\n\tMesh " + mesh.toString(fullDetails);
  53796. }
  53797. }
  53798. // Connecting parents
  53799. var currentMesh;
  53800. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53801. currentMesh = scene.meshes[index];
  53802. if (currentMesh._waitingParentId) {
  53803. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53804. currentMesh._waitingParentId = null;
  53805. }
  53806. }
  53807. // freeze and compute world matrix application
  53808. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53809. currentMesh = scene.meshes[index];
  53810. if (currentMesh._waitingFreezeWorldMatrix) {
  53811. currentMesh.freezeWorldMatrix();
  53812. currentMesh._waitingFreezeWorldMatrix = null;
  53813. }
  53814. else {
  53815. currentMesh.computeWorldMatrix(true);
  53816. }
  53817. }
  53818. }
  53819. // Particles
  53820. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53821. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53822. var parsedParticleSystem = parsedData.particleSystems[index];
  53823. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53824. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53825. }
  53826. }
  53827. }
  53828. return true;
  53829. }
  53830. catch (err) {
  53831. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53832. if (onError) {
  53833. onError(msg, err);
  53834. }
  53835. else {
  53836. BABYLON.Tools.Log(msg);
  53837. throw err;
  53838. }
  53839. }
  53840. finally {
  53841. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53842. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53843. }
  53844. }
  53845. return false;
  53846. },
  53847. load: function (scene, data, rootUrl, onError) {
  53848. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53849. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53850. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53851. // and avoid problems with multiple concurrent .babylon loads.
  53852. var log = "importScene has failed JSON parse";
  53853. try {
  53854. var parsedData = JSON.parse(data);
  53855. log = "";
  53856. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53857. // Scene
  53858. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53859. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53860. }
  53861. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53862. scene.autoClear = parsedData.autoClear;
  53863. }
  53864. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53865. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53866. }
  53867. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53868. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53869. }
  53870. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53871. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53872. }
  53873. // Fog
  53874. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53875. scene.fogMode = parsedData.fogMode;
  53876. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53877. scene.fogStart = parsedData.fogStart;
  53878. scene.fogEnd = parsedData.fogEnd;
  53879. scene.fogDensity = parsedData.fogDensity;
  53880. log += "\tFog mode for scene: ";
  53881. switch (scene.fogMode) {
  53882. // getters not compiling, so using hardcoded
  53883. case 1:
  53884. log += "exp\n";
  53885. break;
  53886. case 2:
  53887. log += "exp2\n";
  53888. break;
  53889. case 3:
  53890. log += "linear\n";
  53891. break;
  53892. }
  53893. }
  53894. //Physics
  53895. if (parsedData.physicsEnabled) {
  53896. var physicsPlugin;
  53897. if (parsedData.physicsEngine === "cannon") {
  53898. physicsPlugin = new BABYLON.CannonJSPlugin();
  53899. }
  53900. else if (parsedData.physicsEngine === "oimo") {
  53901. physicsPlugin = new BABYLON.OimoJSPlugin();
  53902. }
  53903. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53904. //else - default engine, which is currently oimo
  53905. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53906. scene.enablePhysics(physicsGravity, physicsPlugin);
  53907. }
  53908. // Metadata
  53909. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53910. scene.metadata = parsedData.metadata;
  53911. }
  53912. //collisions, if defined. otherwise, default is true
  53913. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53914. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53915. }
  53916. scene.workerCollisions = !!parsedData.workerCollisions;
  53917. var index;
  53918. var cache;
  53919. // Lights
  53920. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53921. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53922. var parsedLight = parsedData.lights[index];
  53923. var light = BABYLON.Light.Parse(parsedLight, scene);
  53924. if (light) {
  53925. log += (index === 0 ? "\n\tLights:" : "");
  53926. log += "\n\t\t" + light.toString(fullDetails);
  53927. }
  53928. }
  53929. }
  53930. // Animations
  53931. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53932. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53933. var parsedAnimation = parsedData.animations[index];
  53934. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53935. scene.animations.push(animation);
  53936. log += (index === 0 ? "\n\tAnimations:" : "");
  53937. log += "\n\t\t" + animation.toString(fullDetails);
  53938. }
  53939. }
  53940. if (parsedData.autoAnimate) {
  53941. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53942. }
  53943. // Materials
  53944. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53945. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53946. var parsedMaterial = parsedData.materials[index];
  53947. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53948. log += (index === 0 ? "\n\tMaterials:" : "");
  53949. log += "\n\t\t" + mat.toString(fullDetails);
  53950. }
  53951. }
  53952. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53953. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53954. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53955. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53956. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53957. log += "\n\t\t" + mmat.toString(fullDetails);
  53958. }
  53959. }
  53960. // Morph targets
  53961. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53962. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53963. var managerData = _a[_i];
  53964. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53965. }
  53966. }
  53967. // Skeletons
  53968. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53969. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53970. var parsedSkeleton = parsedData.skeletons[index];
  53971. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53972. log += (index === 0 ? "\n\tSkeletons:" : "");
  53973. log += "\n\t\t" + skeleton.toString(fullDetails);
  53974. }
  53975. }
  53976. // Geometries
  53977. var geometries = parsedData.geometries;
  53978. if (geometries !== undefined && geometries !== null) {
  53979. // Boxes
  53980. var boxes = geometries.boxes;
  53981. if (boxes !== undefined && boxes !== null) {
  53982. for (index = 0, cache = boxes.length; index < cache; index++) {
  53983. var parsedBox = boxes[index];
  53984. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53985. }
  53986. }
  53987. // Spheres
  53988. var spheres = geometries.spheres;
  53989. if (spheres !== undefined && spheres !== null) {
  53990. for (index = 0, cache = spheres.length; index < cache; index++) {
  53991. var parsedSphere = spheres[index];
  53992. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53993. }
  53994. }
  53995. // Cylinders
  53996. var cylinders = geometries.cylinders;
  53997. if (cylinders !== undefined && cylinders !== null) {
  53998. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53999. var parsedCylinder = cylinders[index];
  54000. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  54001. }
  54002. }
  54003. // Toruses
  54004. var toruses = geometries.toruses;
  54005. if (toruses !== undefined && toruses !== null) {
  54006. for (index = 0, cache = toruses.length; index < cache; index++) {
  54007. var parsedTorus = toruses[index];
  54008. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  54009. }
  54010. }
  54011. // Grounds
  54012. var grounds = geometries.grounds;
  54013. if (grounds !== undefined && grounds !== null) {
  54014. for (index = 0, cache = grounds.length; index < cache; index++) {
  54015. var parsedGround = grounds[index];
  54016. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  54017. }
  54018. }
  54019. // Planes
  54020. var planes = geometries.planes;
  54021. if (planes !== undefined && planes !== null) {
  54022. for (index = 0, cache = planes.length; index < cache; index++) {
  54023. var parsedPlane = planes[index];
  54024. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  54025. }
  54026. }
  54027. // TorusKnots
  54028. var torusKnots = geometries.torusKnots;
  54029. if (torusKnots !== undefined && torusKnots !== null) {
  54030. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54031. var parsedTorusKnot = torusKnots[index];
  54032. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  54033. }
  54034. }
  54035. // VertexData
  54036. var vertexData = geometries.vertexData;
  54037. if (vertexData !== undefined && vertexData !== null) {
  54038. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54039. var parsedVertexData = vertexData[index];
  54040. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  54041. }
  54042. }
  54043. }
  54044. // Transform nodes
  54045. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  54046. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  54047. var parsedTransformNode = parsedData.transformNodes[index];
  54048. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  54049. }
  54050. }
  54051. // Meshes
  54052. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54053. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54054. var parsedMesh = parsedData.meshes[index];
  54055. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54056. log += (index === 0 ? "\n\tMeshes:" : "");
  54057. log += "\n\t\t" + mesh.toString(fullDetails);
  54058. }
  54059. }
  54060. // Cameras
  54061. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  54062. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  54063. var parsedCamera = parsedData.cameras[index];
  54064. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  54065. log += (index === 0 ? "\n\tCameras:" : "");
  54066. log += "\n\t\t" + camera.toString(fullDetails);
  54067. }
  54068. }
  54069. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  54070. scene.setActiveCameraByID(parsedData.activeCameraID);
  54071. }
  54072. // Browsing all the graph to connect the dots
  54073. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  54074. var camera = scene.cameras[index];
  54075. if (camera._waitingParentId) {
  54076. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  54077. camera._waitingParentId = null;
  54078. }
  54079. }
  54080. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54081. var light_1 = scene.lights[index];
  54082. if (light_1 && light_1._waitingParentId) {
  54083. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  54084. light_1._waitingParentId = null;
  54085. }
  54086. }
  54087. // Sounds
  54088. var loadedSounds = [];
  54089. var loadedSound;
  54090. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  54091. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  54092. var parsedSound = parsedData.sounds[index];
  54093. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54094. if (!parsedSound.url)
  54095. parsedSound.url = parsedSound.name;
  54096. if (!loadedSounds[parsedSound.url]) {
  54097. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  54098. loadedSounds[parsedSound.url] = loadedSound;
  54099. }
  54100. else {
  54101. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  54102. }
  54103. }
  54104. else {
  54105. new BABYLON.Sound(parsedSound.name, null, scene);
  54106. }
  54107. }
  54108. }
  54109. loadedSounds = [];
  54110. // Connect parents & children and parse actions
  54111. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  54112. var transformNode = scene.transformNodes[index];
  54113. if (transformNode._waitingParentId) {
  54114. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  54115. transformNode._waitingParentId = null;
  54116. }
  54117. }
  54118. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54119. var mesh = scene.meshes[index];
  54120. if (mesh._waitingParentId) {
  54121. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  54122. mesh._waitingParentId = null;
  54123. }
  54124. if (mesh._waitingActions) {
  54125. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  54126. mesh._waitingActions = null;
  54127. }
  54128. }
  54129. // freeze world matrix application
  54130. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54131. var currentMesh = scene.meshes[index];
  54132. if (currentMesh._waitingFreezeWorldMatrix) {
  54133. currentMesh.freezeWorldMatrix();
  54134. currentMesh._waitingFreezeWorldMatrix = null;
  54135. }
  54136. else {
  54137. currentMesh.computeWorldMatrix(true);
  54138. }
  54139. }
  54140. // Particles Systems
  54141. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54142. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54143. var parsedParticleSystem = parsedData.particleSystems[index];
  54144. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  54145. }
  54146. }
  54147. // Environment texture
  54148. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  54149. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  54150. if (parsedData.createDefaultSkybox === true) {
  54151. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  54152. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  54153. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  54154. }
  54155. }
  54156. // Lens flares
  54157. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  54158. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  54159. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  54160. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  54161. }
  54162. }
  54163. // Shadows
  54164. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  54165. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  54166. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  54167. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  54168. }
  54169. }
  54170. // Lights exclusions / inclusions
  54171. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54172. var light_2 = scene.lights[index];
  54173. // Excluded check
  54174. if (light_2._excludedMeshesIds.length > 0) {
  54175. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  54176. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  54177. if (excludedMesh) {
  54178. light_2.excludedMeshes.push(excludedMesh);
  54179. }
  54180. }
  54181. light_2._excludedMeshesIds = [];
  54182. }
  54183. // Included check
  54184. if (light_2._includedOnlyMeshesIds.length > 0) {
  54185. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  54186. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  54187. if (includedOnlyMesh) {
  54188. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  54189. }
  54190. }
  54191. light_2._includedOnlyMeshesIds = [];
  54192. }
  54193. }
  54194. // Actions (scene)
  54195. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  54196. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  54197. }
  54198. // Finish
  54199. return true;
  54200. }
  54201. catch (err) {
  54202. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  54203. if (onError) {
  54204. onError(msg, err);
  54205. }
  54206. else {
  54207. BABYLON.Tools.Log(msg);
  54208. throw err;
  54209. }
  54210. }
  54211. finally {
  54212. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54213. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54214. }
  54215. }
  54216. return false;
  54217. }
  54218. });
  54219. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54220. })(BABYLON || (BABYLON = {}));
  54221. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  54222. var BABYLON;
  54223. (function (BABYLON) {
  54224. var FilesInput = /** @class */ (function () {
  54225. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  54226. this.onProcessFileCallback = function () { return true; };
  54227. this._engine = engine;
  54228. this._currentScene = scene;
  54229. this._sceneLoadedCallback = sceneLoadedCallback;
  54230. this._progressCallback = progressCallback;
  54231. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  54232. this._textureLoadingCallback = textureLoadingCallback;
  54233. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  54234. this._onReloadCallback = onReloadCallback;
  54235. this._errorCallback = errorCallback;
  54236. }
  54237. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  54238. var _this = this;
  54239. if (elementToMonitor) {
  54240. this._elementToMonitor = elementToMonitor;
  54241. this._dragEnterHandler = function (e) { _this.drag(e); };
  54242. this._dragOverHandler = function (e) { _this.drag(e); };
  54243. this._dropHandler = function (e) { _this.drop(e); };
  54244. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  54245. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  54246. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  54247. }
  54248. };
  54249. FilesInput.prototype.dispose = function () {
  54250. if (!this._elementToMonitor) {
  54251. return;
  54252. }
  54253. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  54254. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  54255. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  54256. };
  54257. FilesInput.prototype.renderFunction = function () {
  54258. if (this._additionalRenderLoopLogicCallback) {
  54259. this._additionalRenderLoopLogicCallback();
  54260. }
  54261. if (this._currentScene) {
  54262. if (this._textureLoadingCallback) {
  54263. var remaining = this._currentScene.getWaitingItemsCount();
  54264. if (remaining > 0) {
  54265. this._textureLoadingCallback(remaining);
  54266. }
  54267. }
  54268. this._currentScene.render();
  54269. }
  54270. };
  54271. FilesInput.prototype.drag = function (e) {
  54272. e.stopPropagation();
  54273. e.preventDefault();
  54274. };
  54275. FilesInput.prototype.drop = function (eventDrop) {
  54276. eventDrop.stopPropagation();
  54277. eventDrop.preventDefault();
  54278. this.loadFiles(eventDrop);
  54279. };
  54280. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  54281. var _this = this;
  54282. var reader = folder.createReader();
  54283. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  54284. reader.readEntries(function (entries) {
  54285. remaining.count += entries.length;
  54286. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  54287. var entry = entries_1[_i];
  54288. if (entry.isFile) {
  54289. entry.file(function (file) {
  54290. file.correctName = relativePath + file.name;
  54291. files.push(file);
  54292. if (--remaining.count === 0) {
  54293. callback();
  54294. }
  54295. });
  54296. }
  54297. else if (entry.isDirectory) {
  54298. _this._traverseFolder(entry, files, remaining, callback);
  54299. }
  54300. }
  54301. if (--remaining.count) {
  54302. callback();
  54303. }
  54304. });
  54305. };
  54306. FilesInput.prototype._processFiles = function (files) {
  54307. var skippedFiles = 0;
  54308. for (var i = 0; i < files.length; i++) {
  54309. var name = files[i].correctName.toLowerCase();
  54310. var extension = name.split('.').pop();
  54311. if (!this.onProcessFileCallback(files[i], name, extension)) {
  54312. skippedFiles++;
  54313. continue;
  54314. }
  54315. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  54316. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  54317. this._sceneFileToLoad = files[i];
  54318. }
  54319. else {
  54320. FilesInput.FilesToLoad[name] = files[i];
  54321. }
  54322. }
  54323. if (this._onReloadCallback) {
  54324. this._onReloadCallback(this._sceneFileToLoad);
  54325. }
  54326. else if (skippedFiles < files.length) {
  54327. this.reload();
  54328. }
  54329. };
  54330. FilesInput.prototype.loadFiles = function (event) {
  54331. var _this = this;
  54332. if (this._startingProcessingFilesCallback)
  54333. this._startingProcessingFilesCallback();
  54334. // Handling data transfer via drag'n'drop
  54335. if (event && event.dataTransfer && event.dataTransfer.files) {
  54336. this._filesToLoad = event.dataTransfer.files;
  54337. }
  54338. // Handling files from input files
  54339. if (event && event.target && event.target.files) {
  54340. this._filesToLoad = event.target.files;
  54341. }
  54342. if (this._filesToLoad && this._filesToLoad.length > 0) {
  54343. var files_1 = new Array();
  54344. var folders = [];
  54345. var items = event.dataTransfer ? event.dataTransfer.items : null;
  54346. for (var i = 0; i < this._filesToLoad.length; i++) {
  54347. var fileToLoad = this._filesToLoad[i];
  54348. var name_1 = fileToLoad.name.toLowerCase();
  54349. var entry = void 0;
  54350. fileToLoad.correctName = name_1;
  54351. if (items) {
  54352. var item = items[i];
  54353. if (item.getAsEntry) {
  54354. entry = item.getAsEntry();
  54355. }
  54356. else if (item.webkitGetAsEntry) {
  54357. entry = item.webkitGetAsEntry();
  54358. }
  54359. }
  54360. if (!entry) {
  54361. files_1.push(fileToLoad);
  54362. }
  54363. else {
  54364. if (entry.isDirectory) {
  54365. folders.push(entry);
  54366. }
  54367. else {
  54368. files_1.push(fileToLoad);
  54369. }
  54370. }
  54371. }
  54372. if (folders.length === 0) {
  54373. this._processFiles(files_1);
  54374. }
  54375. else {
  54376. var remaining = { count: folders.length };
  54377. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  54378. var folder = folders_1[_i];
  54379. this._traverseFolder(folder, files_1, remaining, function () {
  54380. _this._processFiles(files_1);
  54381. });
  54382. }
  54383. }
  54384. }
  54385. };
  54386. FilesInput.prototype.reload = function () {
  54387. var _this = this;
  54388. // If a ".babylon" file has been provided
  54389. if (this._sceneFileToLoad) {
  54390. if (this._currentScene) {
  54391. if (BABYLON.Tools.errorsCount > 0) {
  54392. BABYLON.Tools.ClearLogCache();
  54393. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  54394. }
  54395. this._engine.stopRenderLoop();
  54396. this._currentScene.dispose();
  54397. }
  54398. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  54399. _this._currentScene = newScene;
  54400. if (_this._sceneLoadedCallback) {
  54401. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  54402. }
  54403. // Wait for textures and shaders to be ready
  54404. _this._currentScene.executeWhenReady(function () {
  54405. _this._engine.runRenderLoop(function () {
  54406. _this.renderFunction();
  54407. });
  54408. });
  54409. }, function (progress) {
  54410. if (_this._progressCallback) {
  54411. _this._progressCallback(progress);
  54412. }
  54413. }, function (scene, message) {
  54414. _this._currentScene = scene;
  54415. if (_this._errorCallback) {
  54416. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  54417. }
  54418. });
  54419. }
  54420. else {
  54421. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  54422. }
  54423. };
  54424. FilesInput.FilesToLoad = {};
  54425. return FilesInput;
  54426. }());
  54427. BABYLON.FilesInput = FilesInput;
  54428. })(BABYLON || (BABYLON = {}));
  54429. //# sourceMappingURL=babylon.filesInput.js.map
  54430. var BABYLON;
  54431. (function (BABYLON) {
  54432. /**
  54433. * This class implement a typical dictionary using a string as key and the generic type T as value.
  54434. * The underlying implementation relies on an associative array to ensure the best performances.
  54435. * The value can be anything including 'null' but except 'undefined'
  54436. */
  54437. var StringDictionary = /** @class */ (function () {
  54438. function StringDictionary() {
  54439. this._count = 0;
  54440. this._data = {};
  54441. }
  54442. /**
  54443. * This will clear this dictionary and copy the content from the 'source' one.
  54444. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  54445. * @param source the dictionary to take the content from and copy to this dictionary
  54446. */
  54447. StringDictionary.prototype.copyFrom = function (source) {
  54448. var _this = this;
  54449. this.clear();
  54450. source.forEach(function (t, v) { return _this.add(t, v); });
  54451. };
  54452. /**
  54453. * Get a value based from its key
  54454. * @param key the given key to get the matching value from
  54455. * @return the value if found, otherwise undefined is returned
  54456. */
  54457. StringDictionary.prototype.get = function (key) {
  54458. var val = this._data[key];
  54459. if (val !== undefined) {
  54460. return val;
  54461. }
  54462. return undefined;
  54463. };
  54464. /**
  54465. * Get a value from its key or add it if it doesn't exist.
  54466. * This method will ensure you that a given key/data will be present in the dictionary.
  54467. * @param key the given key to get the matching value from
  54468. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54469. * The factory will only be invoked if there's no data for the given key.
  54470. * @return the value corresponding to the key.
  54471. */
  54472. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54473. var val = this.get(key);
  54474. if (val !== undefined) {
  54475. return val;
  54476. }
  54477. val = factory(key);
  54478. if (val) {
  54479. this.add(key, val);
  54480. }
  54481. return val;
  54482. };
  54483. /**
  54484. * Get a value from its key if present in the dictionary otherwise add it
  54485. * @param key the key to get the value from
  54486. * @param val if there's no such key/value pair in the dictionary add it with this value
  54487. * @return the value corresponding to the key
  54488. */
  54489. StringDictionary.prototype.getOrAdd = function (key, val) {
  54490. var curVal = this.get(key);
  54491. if (curVal !== undefined) {
  54492. return curVal;
  54493. }
  54494. this.add(key, val);
  54495. return val;
  54496. };
  54497. /**
  54498. * Check if there's a given key in the dictionary
  54499. * @param key the key to check for
  54500. * @return true if the key is present, false otherwise
  54501. */
  54502. StringDictionary.prototype.contains = function (key) {
  54503. return this._data[key] !== undefined;
  54504. };
  54505. /**
  54506. * Add a new key and its corresponding value
  54507. * @param key the key to add
  54508. * @param value the value corresponding to the key
  54509. * @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
  54510. */
  54511. StringDictionary.prototype.add = function (key, value) {
  54512. if (this._data[key] !== undefined) {
  54513. return false;
  54514. }
  54515. this._data[key] = value;
  54516. ++this._count;
  54517. return true;
  54518. };
  54519. StringDictionary.prototype.set = function (key, value) {
  54520. if (this._data[key] === undefined) {
  54521. return false;
  54522. }
  54523. this._data[key] = value;
  54524. return true;
  54525. };
  54526. /**
  54527. * Get the element of the given key and remove it from the dictionary
  54528. * @param key
  54529. */
  54530. StringDictionary.prototype.getAndRemove = function (key) {
  54531. var val = this.get(key);
  54532. if (val !== undefined) {
  54533. delete this._data[key];
  54534. --this._count;
  54535. return val;
  54536. }
  54537. return null;
  54538. };
  54539. /**
  54540. * Remove a key/value from the dictionary.
  54541. * @param key the key to remove
  54542. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54543. */
  54544. StringDictionary.prototype.remove = function (key) {
  54545. if (this.contains(key)) {
  54546. delete this._data[key];
  54547. --this._count;
  54548. return true;
  54549. }
  54550. return false;
  54551. };
  54552. /**
  54553. * Clear the whole content of the dictionary
  54554. */
  54555. StringDictionary.prototype.clear = function () {
  54556. this._data = {};
  54557. this._count = 0;
  54558. };
  54559. Object.defineProperty(StringDictionary.prototype, "count", {
  54560. get: function () {
  54561. return this._count;
  54562. },
  54563. enumerable: true,
  54564. configurable: true
  54565. });
  54566. /**
  54567. * Execute a callback on each key/val of the dictionary.
  54568. * Note that you can remove any element in this dictionary in the callback implementation
  54569. * @param callback the callback to execute on a given key/value pair
  54570. */
  54571. StringDictionary.prototype.forEach = function (callback) {
  54572. for (var cur in this._data) {
  54573. var val = this._data[cur];
  54574. callback(cur, val);
  54575. }
  54576. };
  54577. /**
  54578. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54579. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54580. * Note that you can remove any element in this dictionary in the callback implementation
  54581. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54582. */
  54583. StringDictionary.prototype.first = function (callback) {
  54584. for (var cur in this._data) {
  54585. var val = this._data[cur];
  54586. var res = callback(cur, val);
  54587. if (res) {
  54588. return res;
  54589. }
  54590. }
  54591. return null;
  54592. };
  54593. return StringDictionary;
  54594. }());
  54595. BABYLON.StringDictionary = StringDictionary;
  54596. })(BABYLON || (BABYLON = {}));
  54597. //# sourceMappingURL=babylon.stringDictionary.js.map
  54598. var BABYLON;
  54599. (function (BABYLON) {
  54600. var Tags = /** @class */ (function () {
  54601. function Tags() {
  54602. }
  54603. Tags.EnableFor = function (obj) {
  54604. obj._tags = obj._tags || {};
  54605. obj.hasTags = function () {
  54606. return Tags.HasTags(obj);
  54607. };
  54608. obj.addTags = function (tagsString) {
  54609. return Tags.AddTagsTo(obj, tagsString);
  54610. };
  54611. obj.removeTags = function (tagsString) {
  54612. return Tags.RemoveTagsFrom(obj, tagsString);
  54613. };
  54614. obj.matchesTagsQuery = function (tagsQuery) {
  54615. return Tags.MatchesQuery(obj, tagsQuery);
  54616. };
  54617. };
  54618. Tags.DisableFor = function (obj) {
  54619. delete obj._tags;
  54620. delete obj.hasTags;
  54621. delete obj.addTags;
  54622. delete obj.removeTags;
  54623. delete obj.matchesTagsQuery;
  54624. };
  54625. Tags.HasTags = function (obj) {
  54626. if (!obj._tags) {
  54627. return false;
  54628. }
  54629. return !BABYLON.Tools.IsEmpty(obj._tags);
  54630. };
  54631. Tags.GetTags = function (obj, asString) {
  54632. if (asString === void 0) { asString = true; }
  54633. if (!obj._tags) {
  54634. return null;
  54635. }
  54636. if (asString) {
  54637. var tagsArray = [];
  54638. for (var tag in obj._tags) {
  54639. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54640. tagsArray.push(tag);
  54641. }
  54642. }
  54643. return tagsArray.join(" ");
  54644. }
  54645. else {
  54646. return obj._tags;
  54647. }
  54648. };
  54649. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54650. // a tag cannot start with '||', '&&', and '!'
  54651. // it cannot contain whitespaces
  54652. Tags.AddTagsTo = function (obj, tagsString) {
  54653. if (!tagsString) {
  54654. return;
  54655. }
  54656. if (typeof tagsString !== "string") {
  54657. return;
  54658. }
  54659. var tags = tagsString.split(" ");
  54660. tags.forEach(function (tag, index, array) {
  54661. Tags._AddTagTo(obj, tag);
  54662. });
  54663. };
  54664. Tags._AddTagTo = function (obj, tag) {
  54665. tag = tag.trim();
  54666. if (tag === "" || tag === "true" || tag === "false") {
  54667. return;
  54668. }
  54669. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54670. return;
  54671. }
  54672. Tags.EnableFor(obj);
  54673. obj._tags[tag] = true;
  54674. };
  54675. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54676. if (!Tags.HasTags(obj)) {
  54677. return;
  54678. }
  54679. var tags = tagsString.split(" ");
  54680. for (var t in tags) {
  54681. Tags._RemoveTagFrom(obj, tags[t]);
  54682. }
  54683. };
  54684. Tags._RemoveTagFrom = function (obj, tag) {
  54685. delete obj._tags[tag];
  54686. };
  54687. Tags.MatchesQuery = function (obj, tagsQuery) {
  54688. if (tagsQuery === undefined) {
  54689. return true;
  54690. }
  54691. if (tagsQuery === "") {
  54692. return Tags.HasTags(obj);
  54693. }
  54694. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54695. };
  54696. return Tags;
  54697. }());
  54698. BABYLON.Tags = Tags;
  54699. })(BABYLON || (BABYLON = {}));
  54700. //# sourceMappingURL=babylon.tags.js.map
  54701. var BABYLON;
  54702. (function (BABYLON) {
  54703. var Internals;
  54704. (function (Internals) {
  54705. var AndOrNotEvaluator = /** @class */ (function () {
  54706. function AndOrNotEvaluator() {
  54707. }
  54708. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54709. if (!query.match(/\([^\(\)]*\)/g)) {
  54710. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54711. }
  54712. else {
  54713. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54714. // remove parenthesis
  54715. r = r.slice(1, r.length - 1);
  54716. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54717. });
  54718. }
  54719. if (query === "true") {
  54720. return true;
  54721. }
  54722. if (query === "false") {
  54723. return false;
  54724. }
  54725. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54726. };
  54727. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54728. evaluateCallback = evaluateCallback || (function (r) {
  54729. return r === "true" ? true : false;
  54730. });
  54731. var result;
  54732. var or = parenthesisContent.split("||");
  54733. for (var i in or) {
  54734. if (or.hasOwnProperty(i)) {
  54735. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54736. var and = ori.split("&&");
  54737. if (and.length > 1) {
  54738. for (var j = 0; j < and.length; ++j) {
  54739. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54740. if (andj !== "true" && andj !== "false") {
  54741. if (andj[0] === "!") {
  54742. result = !evaluateCallback(andj.substring(1));
  54743. }
  54744. else {
  54745. result = evaluateCallback(andj);
  54746. }
  54747. }
  54748. else {
  54749. result = andj === "true" ? true : false;
  54750. }
  54751. if (!result) {
  54752. ori = "false";
  54753. break;
  54754. }
  54755. }
  54756. }
  54757. if (result || ori === "true") {
  54758. result = true;
  54759. break;
  54760. }
  54761. // result equals false (or undefined)
  54762. if (ori !== "true" && ori !== "false") {
  54763. if (ori[0] === "!") {
  54764. result = !evaluateCallback(ori.substring(1));
  54765. }
  54766. else {
  54767. result = evaluateCallback(ori);
  54768. }
  54769. }
  54770. else {
  54771. result = ori === "true" ? true : false;
  54772. }
  54773. }
  54774. }
  54775. // the whole parenthesis scope is replaced by 'true' or 'false'
  54776. return result ? "true" : "false";
  54777. };
  54778. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54779. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54780. // remove whitespaces
  54781. r = r.replace(/[\s]/g, function () { return ""; });
  54782. return r.length % 2 ? "!" : "";
  54783. });
  54784. booleanString = booleanString.trim();
  54785. if (booleanString === "!true") {
  54786. booleanString = "false";
  54787. }
  54788. else if (booleanString === "!false") {
  54789. booleanString = "true";
  54790. }
  54791. return booleanString;
  54792. };
  54793. return AndOrNotEvaluator;
  54794. }());
  54795. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54796. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54799. var BABYLON;
  54800. (function (BABYLON) {
  54801. var Database = /** @class */ (function () {
  54802. function Database(urlToScene, callbackManifestChecked) {
  54803. // Handling various flavors of prefixed version of IndexedDB
  54804. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54805. this.callbackManifestChecked = callbackManifestChecked;
  54806. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54807. this.db = null;
  54808. this._enableSceneOffline = false;
  54809. this._enableTexturesOffline = false;
  54810. this.manifestVersionFound = 0;
  54811. this.mustUpdateRessources = false;
  54812. this.hasReachedQuota = false;
  54813. if (!Database.IDBStorageEnabled) {
  54814. this.callbackManifestChecked(true);
  54815. }
  54816. else {
  54817. this.checkManifestFile();
  54818. }
  54819. }
  54820. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54821. get: function () {
  54822. return this._enableSceneOffline;
  54823. },
  54824. enumerable: true,
  54825. configurable: true
  54826. });
  54827. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54828. get: function () {
  54829. return this._enableTexturesOffline;
  54830. },
  54831. enumerable: true,
  54832. configurable: true
  54833. });
  54834. Database.prototype.checkManifestFile = function () {
  54835. var _this = this;
  54836. var noManifestFile = function () {
  54837. _this._enableSceneOffline = false;
  54838. _this._enableTexturesOffline = false;
  54839. _this.callbackManifestChecked(false);
  54840. };
  54841. var timeStampUsed = false;
  54842. var manifestURL = this.currentSceneUrl + ".manifest";
  54843. var xhr = new XMLHttpRequest();
  54844. if (navigator.onLine) {
  54845. // Adding a timestamp to by-pass browsers' cache
  54846. timeStampUsed = true;
  54847. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54848. }
  54849. xhr.open("GET", manifestURL, true);
  54850. xhr.addEventListener("load", function () {
  54851. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54852. try {
  54853. var manifestFile = JSON.parse(xhr.response);
  54854. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54855. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54856. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54857. _this.manifestVersionFound = manifestFile.version;
  54858. }
  54859. if (_this.callbackManifestChecked) {
  54860. _this.callbackManifestChecked(true);
  54861. }
  54862. }
  54863. catch (ex) {
  54864. noManifestFile();
  54865. }
  54866. }
  54867. else {
  54868. noManifestFile();
  54869. }
  54870. }, false);
  54871. xhr.addEventListener("error", function (event) {
  54872. if (timeStampUsed) {
  54873. timeStampUsed = false;
  54874. // Let's retry without the timeStamp
  54875. // It could fail when coupled with HTML5 Offline API
  54876. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54877. xhr.open("GET", retryManifestURL, true);
  54878. xhr.send();
  54879. }
  54880. else {
  54881. noManifestFile();
  54882. }
  54883. }, false);
  54884. try {
  54885. xhr.send();
  54886. }
  54887. catch (ex) {
  54888. BABYLON.Tools.Error("Error on XHR send request.");
  54889. this.callbackManifestChecked(false);
  54890. }
  54891. };
  54892. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54893. var _this = this;
  54894. var handleError = function () {
  54895. _this.isSupported = false;
  54896. if (errorCallback)
  54897. errorCallback();
  54898. };
  54899. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54900. // Your browser doesn't support IndexedDB
  54901. this.isSupported = false;
  54902. if (errorCallback)
  54903. errorCallback();
  54904. }
  54905. else {
  54906. // If the DB hasn't been opened or created yet
  54907. if (!this.db) {
  54908. this.hasReachedQuota = false;
  54909. this.isSupported = true;
  54910. var request = this.idbFactory.open("babylonjs", 1);
  54911. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54912. request.onerror = function (event) {
  54913. handleError();
  54914. };
  54915. // executes when a version change transaction cannot complete due to other active transactions
  54916. request.onblocked = function (event) {
  54917. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54918. handleError();
  54919. };
  54920. // DB has been opened successfully
  54921. request.onsuccess = function (event) {
  54922. _this.db = request.result;
  54923. successCallback();
  54924. };
  54925. // Initialization of the DB. Creating Scenes & Textures stores
  54926. request.onupgradeneeded = function (event) {
  54927. _this.db = (event.target).result;
  54928. if (_this.db) {
  54929. try {
  54930. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54931. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54932. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54933. }
  54934. catch (ex) {
  54935. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54936. handleError();
  54937. }
  54938. }
  54939. };
  54940. }
  54941. else {
  54942. if (successCallback)
  54943. successCallback();
  54944. }
  54945. }
  54946. };
  54947. Database.prototype.loadImageFromDB = function (url, image) {
  54948. var _this = this;
  54949. var completeURL = Database.ReturnFullUrlLocation(url);
  54950. var saveAndLoadImage = function () {
  54951. if (!_this.hasReachedQuota && _this.db !== null) {
  54952. // the texture is not yet in the DB, let's try to save it
  54953. _this._saveImageIntoDBAsync(completeURL, image);
  54954. }
  54955. else {
  54956. image.src = url;
  54957. }
  54958. };
  54959. if (!this.mustUpdateRessources) {
  54960. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54961. }
  54962. else {
  54963. saveAndLoadImage();
  54964. }
  54965. };
  54966. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54967. if (this.isSupported && this.db !== null) {
  54968. var texture;
  54969. var transaction = this.db.transaction(["textures"]);
  54970. transaction.onabort = function (event) {
  54971. image.src = url;
  54972. };
  54973. transaction.oncomplete = function (event) {
  54974. var blobTextureURL;
  54975. if (texture) {
  54976. var URL = window.URL || window.webkitURL;
  54977. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54978. image.onerror = function () {
  54979. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54980. image.src = url;
  54981. };
  54982. image.src = blobTextureURL;
  54983. }
  54984. else {
  54985. notInDBCallback();
  54986. }
  54987. };
  54988. var getRequest = transaction.objectStore("textures").get(url);
  54989. getRequest.onsuccess = function (event) {
  54990. texture = (event.target).result;
  54991. };
  54992. getRequest.onerror = function (event) {
  54993. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54994. image.src = url;
  54995. };
  54996. }
  54997. else {
  54998. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54999. image.src = url;
  55000. }
  55001. };
  55002. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55003. var _this = this;
  55004. if (this.isSupported) {
  55005. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55006. var generateBlobUrl = function () {
  55007. var blobTextureURL;
  55008. if (blob) {
  55009. var URL = window.URL || window.webkitURL;
  55010. try {
  55011. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  55012. }
  55013. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  55014. catch (ex) {
  55015. blobTextureURL = URL.createObjectURL(blob);
  55016. }
  55017. }
  55018. if (blobTextureURL) {
  55019. image.src = blobTextureURL;
  55020. }
  55021. };
  55022. if (Database.IsUASupportingBlobStorage) {
  55023. var xhr = new XMLHttpRequest(), blob;
  55024. xhr.open("GET", url, true);
  55025. xhr.responseType = "blob";
  55026. xhr.addEventListener("load", function () {
  55027. if (xhr.status === 200 && _this.db) {
  55028. // Blob as response (XHR2)
  55029. blob = xhr.response;
  55030. var transaction = _this.db.transaction(["textures"], "readwrite");
  55031. // the transaction could abort because of a QuotaExceededError error
  55032. transaction.onabort = function (event) {
  55033. try {
  55034. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55035. var srcElement = (event.srcElement || event.target);
  55036. var error = srcElement.error;
  55037. if (error && error.name === "QuotaExceededError") {
  55038. _this.hasReachedQuota = true;
  55039. }
  55040. }
  55041. catch (ex) { }
  55042. generateBlobUrl();
  55043. };
  55044. transaction.oncomplete = function (event) {
  55045. generateBlobUrl();
  55046. };
  55047. var newTexture = { textureUrl: url, data: blob };
  55048. try {
  55049. // Put the blob into the dabase
  55050. var addRequest = transaction.objectStore("textures").put(newTexture);
  55051. addRequest.onsuccess = function (event) {
  55052. };
  55053. addRequest.onerror = function (event) {
  55054. generateBlobUrl();
  55055. };
  55056. }
  55057. catch (ex) {
  55058. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  55059. if (ex.code === 25) {
  55060. Database.IsUASupportingBlobStorage = false;
  55061. }
  55062. image.src = url;
  55063. }
  55064. }
  55065. else {
  55066. image.src = url;
  55067. }
  55068. }, false);
  55069. xhr.addEventListener("error", function (event) {
  55070. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  55071. image.src = url;
  55072. }, false);
  55073. xhr.send();
  55074. }
  55075. else {
  55076. image.src = url;
  55077. }
  55078. }
  55079. else {
  55080. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55081. image.src = url;
  55082. }
  55083. };
  55084. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  55085. var _this = this;
  55086. var updateVersion = function () {
  55087. // the version is not yet in the DB or we need to update it
  55088. _this._saveVersionIntoDBAsync(url, versionLoaded);
  55089. };
  55090. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  55091. };
  55092. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  55093. var _this = this;
  55094. if (this.isSupported && this.db) {
  55095. var version;
  55096. try {
  55097. var transaction = this.db.transaction(["versions"]);
  55098. transaction.oncomplete = function (event) {
  55099. if (version) {
  55100. // If the version in the JSON file is > than the version in DB
  55101. if (_this.manifestVersionFound > version.data) {
  55102. _this.mustUpdateRessources = true;
  55103. updateInDBCallback();
  55104. }
  55105. else {
  55106. callback(version.data);
  55107. }
  55108. }
  55109. else {
  55110. _this.mustUpdateRessources = true;
  55111. updateInDBCallback();
  55112. }
  55113. };
  55114. transaction.onabort = function (event) {
  55115. callback(-1);
  55116. };
  55117. var getRequest = transaction.objectStore("versions").get(url);
  55118. getRequest.onsuccess = function (event) {
  55119. version = (event.target).result;
  55120. };
  55121. getRequest.onerror = function (event) {
  55122. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  55123. callback(-1);
  55124. };
  55125. }
  55126. catch (ex) {
  55127. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  55128. callback(-1);
  55129. }
  55130. }
  55131. else {
  55132. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55133. callback(-1);
  55134. }
  55135. };
  55136. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  55137. var _this = this;
  55138. if (this.isSupported && !this.hasReachedQuota && this.db) {
  55139. try {
  55140. // Open a transaction to the database
  55141. var transaction = this.db.transaction(["versions"], "readwrite");
  55142. // the transaction could abort because of a QuotaExceededError error
  55143. transaction.onabort = function (event) {
  55144. try {
  55145. var error = event.srcElement['error'];
  55146. if (error && error.name === "QuotaExceededError") {
  55147. _this.hasReachedQuota = true;
  55148. }
  55149. }
  55150. catch (ex) { }
  55151. callback(-1);
  55152. };
  55153. transaction.oncomplete = function (event) {
  55154. callback(_this.manifestVersionFound);
  55155. };
  55156. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  55157. // Put the scene into the database
  55158. var addRequest = transaction.objectStore("versions").put(newVersion);
  55159. addRequest.onsuccess = function (event) {
  55160. };
  55161. addRequest.onerror = function (event) {
  55162. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  55163. };
  55164. }
  55165. catch (ex) {
  55166. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  55167. callback(-1);
  55168. }
  55169. }
  55170. else {
  55171. callback(-1);
  55172. }
  55173. };
  55174. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  55175. var _this = this;
  55176. var completeUrl = Database.ReturnFullUrlLocation(url);
  55177. var saveAndLoadFile = function () {
  55178. // the scene is not yet in the DB, let's try to save it
  55179. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  55180. };
  55181. this._checkVersionFromDB(completeUrl, function (version) {
  55182. if (version !== -1) {
  55183. if (!_this.mustUpdateRessources) {
  55184. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  55185. }
  55186. else {
  55187. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  55188. }
  55189. }
  55190. else {
  55191. if (errorCallback) {
  55192. errorCallback();
  55193. }
  55194. }
  55195. });
  55196. };
  55197. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  55198. if (this.isSupported && this.db) {
  55199. var targetStore;
  55200. if (url.indexOf(".babylon") !== -1) {
  55201. targetStore = "scenes";
  55202. }
  55203. else {
  55204. targetStore = "textures";
  55205. }
  55206. var file;
  55207. var transaction = this.db.transaction([targetStore]);
  55208. transaction.oncomplete = function (event) {
  55209. if (file) {
  55210. callback(file.data);
  55211. }
  55212. else {
  55213. notInDBCallback();
  55214. }
  55215. };
  55216. transaction.onabort = function (event) {
  55217. notInDBCallback();
  55218. };
  55219. var getRequest = transaction.objectStore(targetStore).get(url);
  55220. getRequest.onsuccess = function (event) {
  55221. file = (event.target).result;
  55222. };
  55223. getRequest.onerror = function (event) {
  55224. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  55225. notInDBCallback();
  55226. };
  55227. }
  55228. else {
  55229. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55230. callback();
  55231. }
  55232. };
  55233. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  55234. var _this = this;
  55235. if (this.isSupported) {
  55236. var targetStore;
  55237. if (url.indexOf(".babylon") !== -1) {
  55238. targetStore = "scenes";
  55239. }
  55240. else {
  55241. targetStore = "textures";
  55242. }
  55243. // Create XHR
  55244. var xhr = new XMLHttpRequest();
  55245. var fileData;
  55246. xhr.open("GET", url, true);
  55247. if (useArrayBuffer) {
  55248. xhr.responseType = "arraybuffer";
  55249. }
  55250. if (progressCallback) {
  55251. xhr.onprogress = progressCallback;
  55252. }
  55253. xhr.addEventListener("load", function () {
  55254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  55255. // Blob as response (XHR2)
  55256. //fileData = xhr.responseText;
  55257. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  55258. if (!_this.hasReachedQuota && _this.db) {
  55259. // Open a transaction to the database
  55260. var transaction = _this.db.transaction([targetStore], "readwrite");
  55261. // the transaction could abort because of a QuotaExceededError error
  55262. transaction.onabort = function (event) {
  55263. try {
  55264. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55265. var error = event.srcElement['error'];
  55266. if (error && error.name === "QuotaExceededError") {
  55267. _this.hasReachedQuota = true;
  55268. }
  55269. }
  55270. catch (ex) { }
  55271. callback(fileData);
  55272. };
  55273. transaction.oncomplete = function (event) {
  55274. callback(fileData);
  55275. };
  55276. var newFile;
  55277. if (targetStore === "scenes") {
  55278. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  55279. }
  55280. else {
  55281. newFile = { textureUrl: url, data: fileData };
  55282. }
  55283. try {
  55284. // Put the scene into the database
  55285. var addRequest = transaction.objectStore(targetStore).put(newFile);
  55286. addRequest.onsuccess = function (event) {
  55287. };
  55288. addRequest.onerror = function (event) {
  55289. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  55290. };
  55291. }
  55292. catch (ex) {
  55293. callback(fileData);
  55294. }
  55295. }
  55296. else {
  55297. callback(fileData);
  55298. }
  55299. }
  55300. else {
  55301. callback();
  55302. }
  55303. }, false);
  55304. xhr.addEventListener("error", function (event) {
  55305. BABYLON.Tools.Error("error on XHR request.");
  55306. callback();
  55307. }, false);
  55308. xhr.send();
  55309. }
  55310. else {
  55311. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55312. callback();
  55313. }
  55314. };
  55315. Database.IsUASupportingBlobStorage = true;
  55316. Database.IDBStorageEnabled = true;
  55317. Database.parseURL = function (url) {
  55318. var a = document.createElement('a');
  55319. a.href = url;
  55320. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  55321. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  55322. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  55323. return absLocation;
  55324. };
  55325. Database.ReturnFullUrlLocation = function (url) {
  55326. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  55327. return (Database.parseURL(window.location.href) + url);
  55328. }
  55329. else {
  55330. return url;
  55331. }
  55332. };
  55333. return Database;
  55334. }());
  55335. BABYLON.Database = Database;
  55336. })(BABYLON || (BABYLON = {}));
  55337. //# sourceMappingURL=babylon.database.js.map
  55338. var BABYLON;
  55339. (function (BABYLON) {
  55340. var FresnelParameters = /** @class */ (function () {
  55341. function FresnelParameters() {
  55342. this._isEnabled = true;
  55343. this.leftColor = BABYLON.Color3.White();
  55344. this.rightColor = BABYLON.Color3.Black();
  55345. this.bias = 0;
  55346. this.power = 1;
  55347. }
  55348. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  55349. get: function () {
  55350. return this._isEnabled;
  55351. },
  55352. set: function (value) {
  55353. if (this._isEnabled === value) {
  55354. return;
  55355. }
  55356. this._isEnabled = value;
  55357. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  55358. },
  55359. enumerable: true,
  55360. configurable: true
  55361. });
  55362. FresnelParameters.prototype.clone = function () {
  55363. var newFresnelParameters = new FresnelParameters();
  55364. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  55365. return newFresnelParameters;
  55366. };
  55367. FresnelParameters.prototype.serialize = function () {
  55368. var serializationObject = {};
  55369. serializationObject.isEnabled = this.isEnabled;
  55370. serializationObject.leftColor = this.leftColor;
  55371. serializationObject.rightColor = this.rightColor;
  55372. serializationObject.bias = this.bias;
  55373. serializationObject.power = this.power;
  55374. return serializationObject;
  55375. };
  55376. FresnelParameters.Parse = function (parsedFresnelParameters) {
  55377. var fresnelParameters = new FresnelParameters();
  55378. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  55379. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  55380. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  55381. fresnelParameters.bias = parsedFresnelParameters.bias;
  55382. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  55383. return fresnelParameters;
  55384. };
  55385. return FresnelParameters;
  55386. }());
  55387. BABYLON.FresnelParameters = FresnelParameters;
  55388. })(BABYLON || (BABYLON = {}));
  55389. //# sourceMappingURL=babylon.fresnelParameters.js.map
  55390. var BABYLON;
  55391. (function (BABYLON) {
  55392. var MultiMaterial = /** @class */ (function (_super) {
  55393. __extends(MultiMaterial, _super);
  55394. function MultiMaterial(name, scene) {
  55395. var _this = _super.call(this, name, scene, true) || this;
  55396. scene.multiMaterials.push(_this);
  55397. _this.subMaterials = new Array();
  55398. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  55399. return _this;
  55400. }
  55401. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  55402. get: function () {
  55403. return this._subMaterials;
  55404. },
  55405. set: function (value) {
  55406. this._subMaterials = value;
  55407. this._hookArray(value);
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. MultiMaterial.prototype._hookArray = function (array) {
  55413. var _this = this;
  55414. var oldPush = array.push;
  55415. array.push = function () {
  55416. var items = [];
  55417. for (var _i = 0; _i < arguments.length; _i++) {
  55418. items[_i] = arguments[_i];
  55419. }
  55420. var result = oldPush.apply(array, items);
  55421. _this._markAllSubMeshesAsTexturesDirty();
  55422. return result;
  55423. };
  55424. var oldSplice = array.splice;
  55425. array.splice = function (index, deleteCount) {
  55426. var deleted = oldSplice.apply(array, [index, deleteCount]);
  55427. _this._markAllSubMeshesAsTexturesDirty();
  55428. return deleted;
  55429. };
  55430. };
  55431. // Properties
  55432. MultiMaterial.prototype.getSubMaterial = function (index) {
  55433. if (index < 0 || index >= this.subMaterials.length) {
  55434. return this.getScene().defaultMaterial;
  55435. }
  55436. return this.subMaterials[index];
  55437. };
  55438. MultiMaterial.prototype.getActiveTextures = function () {
  55439. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  55440. if (subMaterial) {
  55441. return subMaterial.getActiveTextures();
  55442. }
  55443. else {
  55444. return [];
  55445. }
  55446. }));
  55447. var _a;
  55448. };
  55449. // Methods
  55450. MultiMaterial.prototype.getClassName = function () {
  55451. return "MultiMaterial";
  55452. };
  55453. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55454. for (var index = 0; index < this.subMaterials.length; index++) {
  55455. var subMaterial = this.subMaterials[index];
  55456. if (subMaterial) {
  55457. if (subMaterial.storeEffectOnSubMeshes) {
  55458. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55459. return false;
  55460. }
  55461. continue;
  55462. }
  55463. if (!subMaterial.isReady(mesh)) {
  55464. return false;
  55465. }
  55466. }
  55467. }
  55468. return true;
  55469. };
  55470. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55471. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55472. for (var index = 0; index < this.subMaterials.length; index++) {
  55473. var subMaterial = null;
  55474. var current = this.subMaterials[index];
  55475. if (cloneChildren && current) {
  55476. subMaterial = current.clone(name + "-" + current.name);
  55477. }
  55478. else {
  55479. subMaterial = this.subMaterials[index];
  55480. }
  55481. newMultiMaterial.subMaterials.push(subMaterial);
  55482. }
  55483. return newMultiMaterial;
  55484. };
  55485. MultiMaterial.prototype.serialize = function () {
  55486. var serializationObject = {};
  55487. serializationObject.name = this.name;
  55488. serializationObject.id = this.id;
  55489. if (BABYLON.Tags) {
  55490. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55491. }
  55492. serializationObject.materials = [];
  55493. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55494. var subMat = this.subMaterials[matIndex];
  55495. if (subMat) {
  55496. serializationObject.materials.push(subMat.id);
  55497. }
  55498. else {
  55499. serializationObject.materials.push(null);
  55500. }
  55501. }
  55502. return serializationObject;
  55503. };
  55504. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55505. var scene = this.getScene();
  55506. if (!scene) {
  55507. return;
  55508. }
  55509. var index = scene.multiMaterials.indexOf(this);
  55510. if (index >= 0) {
  55511. scene.multiMaterials.splice(index, 1);
  55512. }
  55513. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55514. };
  55515. return MultiMaterial;
  55516. }(BABYLON.Material));
  55517. BABYLON.MultiMaterial = MultiMaterial;
  55518. })(BABYLON || (BABYLON = {}));
  55519. //# sourceMappingURL=babylon.multiMaterial.js.map
  55520. var BABYLON;
  55521. (function (BABYLON) {
  55522. var FreeCameraTouchInput = /** @class */ (function () {
  55523. function FreeCameraTouchInput() {
  55524. this._offsetX = null;
  55525. this._offsetY = null;
  55526. this._pointerPressed = new Array();
  55527. this.touchAngularSensibility = 200000.0;
  55528. this.touchMoveSensibility = 250.0;
  55529. }
  55530. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55531. var _this = this;
  55532. var previousPosition = null;
  55533. if (this._pointerInput === undefined) {
  55534. this._onLostFocus = function (evt) {
  55535. _this._offsetX = null;
  55536. _this._offsetY = null;
  55537. };
  55538. this._pointerInput = function (p, s) {
  55539. var evt = p.event;
  55540. if (evt.pointerType === "mouse") {
  55541. return;
  55542. }
  55543. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55544. if (!noPreventDefault) {
  55545. evt.preventDefault();
  55546. }
  55547. _this._pointerPressed.push(evt.pointerId);
  55548. if (_this._pointerPressed.length !== 1) {
  55549. return;
  55550. }
  55551. previousPosition = {
  55552. x: evt.clientX,
  55553. y: evt.clientY
  55554. };
  55555. }
  55556. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55557. if (!noPreventDefault) {
  55558. evt.preventDefault();
  55559. }
  55560. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55561. if (index === -1) {
  55562. return;
  55563. }
  55564. _this._pointerPressed.splice(index, 1);
  55565. if (index != 0) {
  55566. return;
  55567. }
  55568. previousPosition = null;
  55569. _this._offsetX = null;
  55570. _this._offsetY = null;
  55571. }
  55572. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55573. if (!noPreventDefault) {
  55574. evt.preventDefault();
  55575. }
  55576. if (!previousPosition) {
  55577. return;
  55578. }
  55579. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55580. if (index != 0) {
  55581. return;
  55582. }
  55583. _this._offsetX = evt.clientX - previousPosition.x;
  55584. _this._offsetY = -(evt.clientY - previousPosition.y);
  55585. }
  55586. };
  55587. }
  55588. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55589. if (this._onLostFocus) {
  55590. element.addEventListener("blur", this._onLostFocus);
  55591. }
  55592. };
  55593. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55594. if (this._pointerInput && element) {
  55595. if (this._observer) {
  55596. this.camera.getScene().onPointerObservable.remove(this._observer);
  55597. this._observer = null;
  55598. }
  55599. if (this._onLostFocus) {
  55600. element.removeEventListener("blur", this._onLostFocus);
  55601. this._onLostFocus = null;
  55602. }
  55603. this._pointerPressed = [];
  55604. this._offsetX = null;
  55605. this._offsetY = null;
  55606. }
  55607. };
  55608. FreeCameraTouchInput.prototype.checkInputs = function () {
  55609. if (this._offsetX && this._offsetY) {
  55610. var camera = this.camera;
  55611. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55612. if (this._pointerPressed.length > 1) {
  55613. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55614. }
  55615. else {
  55616. var speed = camera._computeLocalCameraSpeed();
  55617. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55618. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55619. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55620. }
  55621. }
  55622. };
  55623. FreeCameraTouchInput.prototype.getClassName = function () {
  55624. return "FreeCameraTouchInput";
  55625. };
  55626. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55627. return "touch";
  55628. };
  55629. __decorate([
  55630. BABYLON.serialize()
  55631. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55632. __decorate([
  55633. BABYLON.serialize()
  55634. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55635. return FreeCameraTouchInput;
  55636. }());
  55637. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55638. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55639. })(BABYLON || (BABYLON = {}));
  55640. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55641. var BABYLON;
  55642. (function (BABYLON) {
  55643. // We're mainly based on the logic defined into the FreeCamera code
  55644. var TouchCamera = /** @class */ (function (_super) {
  55645. __extends(TouchCamera, _super);
  55646. //-- end properties for backward compatibility for inputs
  55647. function TouchCamera(name, position, scene) {
  55648. var _this = _super.call(this, name, position, scene) || this;
  55649. _this.inputs.addTouch();
  55650. _this._setupInputs();
  55651. return _this;
  55652. }
  55653. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55654. //-- Begin properties for backward compatibility for inputs
  55655. get: function () {
  55656. var touch = this.inputs.attached["touch"];
  55657. if (touch)
  55658. return touch.touchAngularSensibility;
  55659. return 0;
  55660. },
  55661. set: function (value) {
  55662. var touch = this.inputs.attached["touch"];
  55663. if (touch)
  55664. touch.touchAngularSensibility = value;
  55665. },
  55666. enumerable: true,
  55667. configurable: true
  55668. });
  55669. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55670. get: function () {
  55671. var touch = this.inputs.attached["touch"];
  55672. if (touch)
  55673. return touch.touchMoveSensibility;
  55674. return 0;
  55675. },
  55676. set: function (value) {
  55677. var touch = this.inputs.attached["touch"];
  55678. if (touch)
  55679. touch.touchMoveSensibility = value;
  55680. },
  55681. enumerable: true,
  55682. configurable: true
  55683. });
  55684. TouchCamera.prototype.getClassName = function () {
  55685. return "TouchCamera";
  55686. };
  55687. TouchCamera.prototype._setupInputs = function () {
  55688. var mouse = this.inputs.attached["mouse"];
  55689. if (mouse) {
  55690. mouse.touchEnabled = false;
  55691. }
  55692. };
  55693. return TouchCamera;
  55694. }(BABYLON.FreeCamera));
  55695. BABYLON.TouchCamera = TouchCamera;
  55696. })(BABYLON || (BABYLON = {}));
  55697. //# sourceMappingURL=babylon.touchCamera.js.map
  55698. var BABYLON;
  55699. (function (BABYLON) {
  55700. var ProceduralTexture = /** @class */ (function (_super) {
  55701. __extends(ProceduralTexture, _super);
  55702. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55703. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55704. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55705. if (isCube === void 0) { isCube = false; }
  55706. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55707. _this.isCube = isCube;
  55708. _this.isEnabled = true;
  55709. _this._currentRefreshId = -1;
  55710. _this._refreshRate = 1;
  55711. _this._vertexBuffers = {};
  55712. _this._uniforms = new Array();
  55713. _this._samplers = new Array();
  55714. _this._textures = {};
  55715. _this._floats = {};
  55716. _this._floatsArrays = {};
  55717. _this._colors3 = {};
  55718. _this._colors4 = {};
  55719. _this._vectors2 = {};
  55720. _this._vectors3 = {};
  55721. _this._matrices = {};
  55722. _this._fallbackTextureUsed = false;
  55723. scene._proceduralTextures.push(_this);
  55724. _this._engine = scene.getEngine();
  55725. _this.name = name;
  55726. _this.isRenderTarget = true;
  55727. _this._size = size;
  55728. _this._generateMipMaps = generateMipMaps;
  55729. _this.setFragment(fragment);
  55730. _this._fallbackTexture = fallbackTexture;
  55731. if (isCube) {
  55732. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55733. _this.setFloat("face", 0);
  55734. }
  55735. else {
  55736. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55737. }
  55738. // VBO
  55739. var vertices = [];
  55740. vertices.push(1, 1);
  55741. vertices.push(-1, 1);
  55742. vertices.push(-1, -1);
  55743. vertices.push(1, -1);
  55744. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55745. _this._createIndexBuffer();
  55746. return _this;
  55747. }
  55748. ProceduralTexture.prototype._createIndexBuffer = function () {
  55749. var engine = this._engine;
  55750. // Indices
  55751. var indices = [];
  55752. indices.push(0);
  55753. indices.push(1);
  55754. indices.push(2);
  55755. indices.push(0);
  55756. indices.push(2);
  55757. indices.push(3);
  55758. this._indexBuffer = engine.createIndexBuffer(indices);
  55759. };
  55760. ProceduralTexture.prototype._rebuild = function () {
  55761. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55762. if (vb) {
  55763. vb._rebuild();
  55764. }
  55765. this._createIndexBuffer();
  55766. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55767. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55768. }
  55769. };
  55770. ProceduralTexture.prototype.reset = function () {
  55771. if (this._effect === undefined) {
  55772. return;
  55773. }
  55774. var engine = this._engine;
  55775. engine._releaseEffect(this._effect);
  55776. };
  55777. ProceduralTexture.prototype.isReady = function () {
  55778. var _this = this;
  55779. var engine = this._engine;
  55780. var shaders;
  55781. if (!this._fragment) {
  55782. return false;
  55783. }
  55784. if (this._fallbackTextureUsed) {
  55785. return true;
  55786. }
  55787. if (this._fragment.fragmentElement !== undefined) {
  55788. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55789. }
  55790. else {
  55791. shaders = { vertex: "procedural", fragment: this._fragment };
  55792. }
  55793. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55794. _this.releaseInternalTexture();
  55795. if (_this._fallbackTexture) {
  55796. _this._texture = _this._fallbackTexture._texture;
  55797. if (_this._texture) {
  55798. _this._texture.incrementReferences();
  55799. }
  55800. }
  55801. _this._fallbackTextureUsed = true;
  55802. });
  55803. return this._effect.isReady();
  55804. };
  55805. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55806. this._currentRefreshId = -1;
  55807. };
  55808. ProceduralTexture.prototype.setFragment = function (fragment) {
  55809. this._fragment = fragment;
  55810. };
  55811. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55812. get: function () {
  55813. return this._refreshRate;
  55814. },
  55815. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55816. set: function (value) {
  55817. this._refreshRate = value;
  55818. this.resetRefreshCounter();
  55819. },
  55820. enumerable: true,
  55821. configurable: true
  55822. });
  55823. ProceduralTexture.prototype._shouldRender = function () {
  55824. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55825. return false;
  55826. }
  55827. if (this._fallbackTextureUsed) {
  55828. return false;
  55829. }
  55830. if (this._currentRefreshId === -1) {
  55831. this._currentRefreshId = 1;
  55832. return true;
  55833. }
  55834. if (this.refreshRate === this._currentRefreshId) {
  55835. this._currentRefreshId = 1;
  55836. return true;
  55837. }
  55838. this._currentRefreshId++;
  55839. return false;
  55840. };
  55841. ProceduralTexture.prototype.getRenderSize = function () {
  55842. return this._size;
  55843. };
  55844. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55845. if (this._fallbackTextureUsed) {
  55846. return;
  55847. }
  55848. this.releaseInternalTexture();
  55849. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55850. };
  55851. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55852. if (this._uniforms.indexOf(uniformName) === -1) {
  55853. this._uniforms.push(uniformName);
  55854. }
  55855. };
  55856. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55857. if (this._samplers.indexOf(name) === -1) {
  55858. this._samplers.push(name);
  55859. }
  55860. this._textures[name] = texture;
  55861. return this;
  55862. };
  55863. ProceduralTexture.prototype.setFloat = function (name, value) {
  55864. this._checkUniform(name);
  55865. this._floats[name] = value;
  55866. return this;
  55867. };
  55868. ProceduralTexture.prototype.setFloats = function (name, value) {
  55869. this._checkUniform(name);
  55870. this._floatsArrays[name] = value;
  55871. return this;
  55872. };
  55873. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55874. this._checkUniform(name);
  55875. this._colors3[name] = value;
  55876. return this;
  55877. };
  55878. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55879. this._checkUniform(name);
  55880. this._colors4[name] = value;
  55881. return this;
  55882. };
  55883. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55884. this._checkUniform(name);
  55885. this._vectors2[name] = value;
  55886. return this;
  55887. };
  55888. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55889. this._checkUniform(name);
  55890. this._vectors3[name] = value;
  55891. return this;
  55892. };
  55893. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55894. this._checkUniform(name);
  55895. this._matrices[name] = value;
  55896. return this;
  55897. };
  55898. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55899. var scene = this.getScene();
  55900. if (!scene) {
  55901. return;
  55902. }
  55903. var engine = this._engine;
  55904. // Render
  55905. engine.enableEffect(this._effect);
  55906. engine.setState(false);
  55907. // Texture
  55908. for (var name in this._textures) {
  55909. this._effect.setTexture(name, this._textures[name]);
  55910. }
  55911. // Float
  55912. for (name in this._floats) {
  55913. this._effect.setFloat(name, this._floats[name]);
  55914. }
  55915. // Floats
  55916. for (name in this._floatsArrays) {
  55917. this._effect.setArray(name, this._floatsArrays[name]);
  55918. }
  55919. // Color3
  55920. for (name in this._colors3) {
  55921. this._effect.setColor3(name, this._colors3[name]);
  55922. }
  55923. // Color4
  55924. for (name in this._colors4) {
  55925. var color = this._colors4[name];
  55926. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55927. }
  55928. // Vector2
  55929. for (name in this._vectors2) {
  55930. this._effect.setVector2(name, this._vectors2[name]);
  55931. }
  55932. // Vector3
  55933. for (name in this._vectors3) {
  55934. this._effect.setVector3(name, this._vectors3[name]);
  55935. }
  55936. // Matrix
  55937. for (name in this._matrices) {
  55938. this._effect.setMatrix(name, this._matrices[name]);
  55939. }
  55940. if (!this._texture) {
  55941. return;
  55942. }
  55943. if (this.isCube) {
  55944. for (var face = 0; face < 6; face++) {
  55945. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55946. // VBOs
  55947. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55948. this._effect.setFloat("face", face);
  55949. // Clear
  55950. engine.clear(scene.clearColor, true, true, true);
  55951. // Draw order
  55952. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  55953. // Mipmaps
  55954. if (face === 5) {
  55955. engine.generateMipMapsForCubemap(this._texture);
  55956. }
  55957. }
  55958. }
  55959. else {
  55960. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55961. // VBOs
  55962. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55963. // Clear
  55964. engine.clear(scene.clearColor, true, true, true);
  55965. // Draw order
  55966. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  55967. }
  55968. // Unbind
  55969. engine.unBindFramebuffer(this._texture, this.isCube);
  55970. if (this.onGenerated) {
  55971. this.onGenerated();
  55972. }
  55973. };
  55974. ProceduralTexture.prototype.clone = function () {
  55975. var textureSize = this.getSize();
  55976. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55977. // Base texture
  55978. newTexture.hasAlpha = this.hasAlpha;
  55979. newTexture.level = this.level;
  55980. // RenderTarget Texture
  55981. newTexture.coordinatesMode = this.coordinatesMode;
  55982. return newTexture;
  55983. };
  55984. ProceduralTexture.prototype.dispose = function () {
  55985. var scene = this.getScene();
  55986. if (!scene) {
  55987. return;
  55988. }
  55989. var index = scene._proceduralTextures.indexOf(this);
  55990. if (index >= 0) {
  55991. scene._proceduralTextures.splice(index, 1);
  55992. }
  55993. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55994. if (vertexBuffer) {
  55995. vertexBuffer.dispose();
  55996. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55997. }
  55998. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55999. this._indexBuffer = null;
  56000. }
  56001. _super.prototype.dispose.call(this);
  56002. };
  56003. return ProceduralTexture;
  56004. }(BABYLON.Texture));
  56005. BABYLON.ProceduralTexture = ProceduralTexture;
  56006. })(BABYLON || (BABYLON = {}));
  56007. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56008. var BABYLON;
  56009. (function (BABYLON) {
  56010. var CustomProceduralTexture = /** @class */ (function (_super) {
  56011. __extends(CustomProceduralTexture, _super);
  56012. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  56013. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  56014. _this._animate = true;
  56015. _this._time = 0;
  56016. _this._texturePath = texturePath;
  56017. //Try to load json
  56018. _this.loadJson(texturePath);
  56019. _this.refreshRate = 1;
  56020. return _this;
  56021. }
  56022. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  56023. var _this = this;
  56024. var noConfigFile = function () {
  56025. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  56026. try {
  56027. _this.setFragment(_this._texturePath);
  56028. }
  56029. catch (ex) {
  56030. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  56031. }
  56032. };
  56033. var configFileUrl = jsonUrl + "/config.json";
  56034. var xhr = new XMLHttpRequest();
  56035. xhr.open("GET", configFileUrl, true);
  56036. xhr.addEventListener("load", function () {
  56037. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56038. try {
  56039. _this._config = JSON.parse(xhr.response);
  56040. _this.updateShaderUniforms();
  56041. _this.updateTextures();
  56042. _this.setFragment(_this._texturePath + "/custom");
  56043. _this._animate = _this._config.animate;
  56044. _this.refreshRate = _this._config.refreshrate;
  56045. }
  56046. catch (ex) {
  56047. noConfigFile();
  56048. }
  56049. }
  56050. else {
  56051. noConfigFile();
  56052. }
  56053. }, false);
  56054. xhr.addEventListener("error", function () {
  56055. noConfigFile();
  56056. }, false);
  56057. try {
  56058. xhr.send();
  56059. }
  56060. catch (ex) {
  56061. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  56062. }
  56063. };
  56064. CustomProceduralTexture.prototype.isReady = function () {
  56065. if (!_super.prototype.isReady.call(this)) {
  56066. return false;
  56067. }
  56068. for (var name in this._textures) {
  56069. var texture = this._textures[name];
  56070. if (!texture.isReady()) {
  56071. return false;
  56072. }
  56073. }
  56074. return true;
  56075. };
  56076. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56077. var scene = this.getScene();
  56078. if (this._animate && scene) {
  56079. this._time += scene.getAnimationRatio() * 0.03;
  56080. this.updateShaderUniforms();
  56081. }
  56082. _super.prototype.render.call(this, useCameraPostProcess);
  56083. };
  56084. CustomProceduralTexture.prototype.updateTextures = function () {
  56085. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  56086. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  56087. }
  56088. };
  56089. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  56090. if (this._config) {
  56091. for (var j = 0; j < this._config.uniforms.length; j++) {
  56092. var uniform = this._config.uniforms[j];
  56093. switch (uniform.type) {
  56094. case "float":
  56095. this.setFloat(uniform.name, uniform.value);
  56096. break;
  56097. case "color3":
  56098. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  56099. break;
  56100. case "color4":
  56101. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  56102. break;
  56103. case "vector2":
  56104. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  56105. break;
  56106. case "vector3":
  56107. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  56108. break;
  56109. }
  56110. }
  56111. }
  56112. this.setFloat("time", this._time);
  56113. };
  56114. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  56115. get: function () {
  56116. return this._animate;
  56117. },
  56118. set: function (value) {
  56119. this._animate = value;
  56120. },
  56121. enumerable: true,
  56122. configurable: true
  56123. });
  56124. return CustomProceduralTexture;
  56125. }(BABYLON.ProceduralTexture));
  56126. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  56127. })(BABYLON || (BABYLON = {}));
  56128. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  56129. var BABYLON;
  56130. (function (BABYLON) {
  56131. var FreeCameraGamepadInput = /** @class */ (function () {
  56132. function FreeCameraGamepadInput() {
  56133. this.gamepadAngularSensibility = 200;
  56134. this.gamepadMoveSensibility = 40;
  56135. // private members
  56136. this._cameraTransform = BABYLON.Matrix.Identity();
  56137. this._deltaTransform = BABYLON.Vector3.Zero();
  56138. this._vector3 = BABYLON.Vector3.Zero();
  56139. this._vector2 = BABYLON.Vector2.Zero();
  56140. }
  56141. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56142. var _this = this;
  56143. var manager = this.camera.getScene().gamepadManager;
  56144. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56145. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56146. // prioritize XBOX gamepads.
  56147. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56148. _this.gamepad = gamepad;
  56149. }
  56150. }
  56151. });
  56152. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56153. if (_this.gamepad === gamepad) {
  56154. _this.gamepad = null;
  56155. }
  56156. });
  56157. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56158. };
  56159. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  56160. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56161. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56162. this.gamepad = null;
  56163. };
  56164. FreeCameraGamepadInput.prototype.checkInputs = function () {
  56165. if (this.gamepad && this.gamepad.leftStick) {
  56166. var camera = this.camera;
  56167. var LSValues = this.gamepad.leftStick;
  56168. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  56169. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56170. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  56171. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  56172. var RSValues = this.gamepad.rightStick;
  56173. if (RSValues) {
  56174. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  56175. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  56176. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  56177. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  56178. }
  56179. else {
  56180. RSValues = { x: 0, y: 0 };
  56181. }
  56182. if (!camera.rotationQuaternion) {
  56183. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  56184. }
  56185. else {
  56186. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  56187. }
  56188. var speed = camera._computeLocalCameraSpeed() * 50.0;
  56189. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  56190. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  56191. camera.cameraDirection.addInPlace(this._deltaTransform);
  56192. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  56193. camera.cameraRotation.addInPlace(this._vector2);
  56194. }
  56195. };
  56196. FreeCameraGamepadInput.prototype.getClassName = function () {
  56197. return "FreeCameraGamepadInput";
  56198. };
  56199. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  56200. return "gamepad";
  56201. };
  56202. __decorate([
  56203. BABYLON.serialize()
  56204. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  56205. __decorate([
  56206. BABYLON.serialize()
  56207. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56208. return FreeCameraGamepadInput;
  56209. }());
  56210. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  56211. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  56212. })(BABYLON || (BABYLON = {}));
  56213. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  56214. var BABYLON;
  56215. (function (BABYLON) {
  56216. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  56217. function ArcRotateCameraGamepadInput() {
  56218. this.gamepadRotationSensibility = 80;
  56219. this.gamepadMoveSensibility = 40;
  56220. }
  56221. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56222. var _this = this;
  56223. var manager = this.camera.getScene().gamepadManager;
  56224. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56225. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56226. // prioritize XBOX gamepads.
  56227. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56228. _this.gamepad = gamepad;
  56229. }
  56230. }
  56231. });
  56232. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56233. if (_this.gamepad === gamepad) {
  56234. _this.gamepad = null;
  56235. }
  56236. });
  56237. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56238. };
  56239. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  56240. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56241. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56242. this.gamepad = null;
  56243. };
  56244. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  56245. if (this.gamepad) {
  56246. var camera = this.camera;
  56247. var RSValues = this.gamepad.rightStick;
  56248. if (RSValues) {
  56249. if (RSValues.x != 0) {
  56250. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  56251. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  56252. camera.inertialAlphaOffset += normalizedRX;
  56253. }
  56254. }
  56255. if (RSValues.y != 0) {
  56256. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  56257. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  56258. camera.inertialBetaOffset += normalizedRY;
  56259. }
  56260. }
  56261. }
  56262. var LSValues = this.gamepad.leftStick;
  56263. if (LSValues && LSValues.y != 0) {
  56264. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56265. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  56266. this.camera.inertialRadiusOffset -= normalizedLY;
  56267. }
  56268. }
  56269. }
  56270. };
  56271. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  56272. return "ArcRotateCameraGamepadInput";
  56273. };
  56274. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  56275. return "gamepad";
  56276. };
  56277. __decorate([
  56278. BABYLON.serialize()
  56279. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  56280. __decorate([
  56281. BABYLON.serialize()
  56282. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56283. return ArcRotateCameraGamepadInput;
  56284. }());
  56285. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  56286. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  56287. })(BABYLON || (BABYLON = {}));
  56288. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  56289. var BABYLON;
  56290. (function (BABYLON) {
  56291. var GamepadManager = /** @class */ (function () {
  56292. function GamepadManager(_scene) {
  56293. var _this = this;
  56294. this._scene = _scene;
  56295. this._babylonGamepads = [];
  56296. this._oneGamepadConnected = false;
  56297. this._isMonitoring = false;
  56298. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  56299. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56300. this._gamepadEventSupported = false;
  56301. }
  56302. else {
  56303. this._gamepadEventSupported = 'GamepadEvent' in window;
  56304. this._gamepadSupport = (navigator.getGamepads ||
  56305. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  56306. }
  56307. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  56308. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  56309. for (var i in _this._babylonGamepads) {
  56310. var gamepad = _this._babylonGamepads[i];
  56311. if (gamepad && gamepad._isConnected) {
  56312. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  56313. }
  56314. }
  56315. });
  56316. this._onGamepadConnectedEvent = function (evt) {
  56317. var gamepad = evt.gamepad;
  56318. if (gamepad.index in _this._babylonGamepads) {
  56319. if (_this._babylonGamepads[gamepad.index].isConnected) {
  56320. return;
  56321. }
  56322. }
  56323. var newGamepad;
  56324. if (_this._babylonGamepads[gamepad.index]) {
  56325. newGamepad = _this._babylonGamepads[gamepad.index];
  56326. newGamepad.browserGamepad = gamepad;
  56327. newGamepad._isConnected = true;
  56328. }
  56329. else {
  56330. newGamepad = _this._addNewGamepad(gamepad);
  56331. }
  56332. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56333. _this._startMonitoringGamepads();
  56334. };
  56335. this._onGamepadDisconnectedEvent = function (evt) {
  56336. var gamepad = evt.gamepad;
  56337. // Remove the gamepad from the list of gamepads to monitor.
  56338. for (var i in _this._babylonGamepads) {
  56339. if (_this._babylonGamepads[i].index === gamepad.index) {
  56340. var disconnectedGamepad = _this._babylonGamepads[i];
  56341. disconnectedGamepad._isConnected = false;
  56342. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  56343. break;
  56344. }
  56345. }
  56346. };
  56347. if (this._gamepadSupport) {
  56348. //first add already-connected gamepads
  56349. this._updateGamepadObjects();
  56350. if (this._babylonGamepads.length) {
  56351. this._startMonitoringGamepads();
  56352. }
  56353. // Checking if the gamepad connected event is supported (like in Firefox)
  56354. if (this._gamepadEventSupported) {
  56355. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  56356. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  56357. }
  56358. else {
  56359. this._startMonitoringGamepads();
  56360. }
  56361. }
  56362. }
  56363. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  56364. get: function () {
  56365. return this._babylonGamepads;
  56366. },
  56367. enumerable: true,
  56368. configurable: true
  56369. });
  56370. GamepadManager.prototype.getGamepadByType = function (type) {
  56371. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  56372. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  56373. var gamepad = _a[_i];
  56374. if (gamepad && gamepad.type === type) {
  56375. return gamepad;
  56376. }
  56377. }
  56378. return null;
  56379. };
  56380. GamepadManager.prototype.dispose = function () {
  56381. if (this._gamepadEventSupported) {
  56382. if (this._onGamepadConnectedEvent) {
  56383. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  56384. }
  56385. if (this._onGamepadDisconnectedEvent) {
  56386. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  56387. }
  56388. this._onGamepadConnectedEvent = null;
  56389. this._onGamepadDisconnectedEvent = null;
  56390. }
  56391. this._babylonGamepads.forEach(function (gamepad) {
  56392. gamepad.dispose();
  56393. });
  56394. this.onGamepadConnectedObservable.clear();
  56395. this.onGamepadDisconnectedObservable.clear();
  56396. this._oneGamepadConnected = false;
  56397. this._stopMonitoringGamepads();
  56398. this._babylonGamepads = [];
  56399. };
  56400. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  56401. if (!this._oneGamepadConnected) {
  56402. this._oneGamepadConnected = true;
  56403. }
  56404. var newGamepad;
  56405. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  56406. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  56407. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  56408. }
  56409. else if (gamepad.pose) {
  56410. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  56411. }
  56412. else {
  56413. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  56414. }
  56415. this._babylonGamepads[newGamepad.index] = newGamepad;
  56416. return newGamepad;
  56417. };
  56418. GamepadManager.prototype._startMonitoringGamepads = function () {
  56419. if (!this._isMonitoring) {
  56420. this._isMonitoring = true;
  56421. //back-comp
  56422. if (!this._scene) {
  56423. this._checkGamepadsStatus();
  56424. }
  56425. }
  56426. };
  56427. GamepadManager.prototype._stopMonitoringGamepads = function () {
  56428. this._isMonitoring = false;
  56429. };
  56430. GamepadManager.prototype._checkGamepadsStatus = function () {
  56431. var _this = this;
  56432. // Hack to be compatible Chrome
  56433. this._updateGamepadObjects();
  56434. for (var i in this._babylonGamepads) {
  56435. var gamepad = this._babylonGamepads[i];
  56436. if (!gamepad || !gamepad.isConnected) {
  56437. continue;
  56438. }
  56439. gamepad.update();
  56440. }
  56441. if (this._isMonitoring && !this._scene) {
  56442. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  56443. }
  56444. };
  56445. // This function is called only on Chrome, which does not properly support
  56446. // connection/disconnection events and forces you to recopy again the gamepad object
  56447. GamepadManager.prototype._updateGamepadObjects = function () {
  56448. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56449. for (var i = 0; i < gamepads.length; i++) {
  56450. if (gamepads[i]) {
  56451. if (!this._babylonGamepads[gamepads[i].index]) {
  56452. var newGamepad = this._addNewGamepad(gamepads[i]);
  56453. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56454. }
  56455. else {
  56456. // Forced to copy again this object for Chrome for unknown reason
  56457. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56458. if (!this._babylonGamepads[i].isConnected) {
  56459. this._babylonGamepads[i]._isConnected = true;
  56460. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56461. }
  56462. }
  56463. }
  56464. }
  56465. };
  56466. return GamepadManager;
  56467. }());
  56468. BABYLON.GamepadManager = GamepadManager;
  56469. })(BABYLON || (BABYLON = {}));
  56470. //# sourceMappingURL=babylon.gamepadManager.js.map
  56471. var BABYLON;
  56472. (function (BABYLON) {
  56473. var StickValues = /** @class */ (function () {
  56474. function StickValues(x, y) {
  56475. this.x = x;
  56476. this.y = y;
  56477. }
  56478. return StickValues;
  56479. }());
  56480. BABYLON.StickValues = StickValues;
  56481. var Gamepad = /** @class */ (function () {
  56482. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56483. if (leftStickX === void 0) { leftStickX = 0; }
  56484. if (leftStickY === void 0) { leftStickY = 1; }
  56485. if (rightStickX === void 0) { rightStickX = 2; }
  56486. if (rightStickY === void 0) { rightStickY = 3; }
  56487. this.id = id;
  56488. this.index = index;
  56489. this.browserGamepad = browserGamepad;
  56490. this._isConnected = true;
  56491. this._invertLeftStickY = false;
  56492. this.type = Gamepad.GAMEPAD;
  56493. this._leftStickAxisX = leftStickX;
  56494. this._leftStickAxisY = leftStickY;
  56495. this._rightStickAxisX = rightStickX;
  56496. this._rightStickAxisY = rightStickY;
  56497. if (this.browserGamepad.axes.length >= 2) {
  56498. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56499. }
  56500. if (this.browserGamepad.axes.length >= 4) {
  56501. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56502. }
  56503. }
  56504. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56505. get: function () {
  56506. return this._isConnected;
  56507. },
  56508. enumerable: true,
  56509. configurable: true
  56510. });
  56511. Gamepad.prototype.onleftstickchanged = function (callback) {
  56512. this._onleftstickchanged = callback;
  56513. };
  56514. Gamepad.prototype.onrightstickchanged = function (callback) {
  56515. this._onrightstickchanged = callback;
  56516. };
  56517. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56518. get: function () {
  56519. return this._leftStick;
  56520. },
  56521. set: function (newValues) {
  56522. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56523. this._onleftstickchanged(newValues);
  56524. }
  56525. this._leftStick = newValues;
  56526. },
  56527. enumerable: true,
  56528. configurable: true
  56529. });
  56530. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56531. get: function () {
  56532. return this._rightStick;
  56533. },
  56534. set: function (newValues) {
  56535. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56536. this._onrightstickchanged(newValues);
  56537. }
  56538. this._rightStick = newValues;
  56539. },
  56540. enumerable: true,
  56541. configurable: true
  56542. });
  56543. Gamepad.prototype.update = function () {
  56544. if (this._leftStick) {
  56545. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56546. if (this._invertLeftStickY) {
  56547. this.leftStick.y *= -1;
  56548. }
  56549. }
  56550. if (this._rightStick) {
  56551. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56552. }
  56553. };
  56554. Gamepad.prototype.dispose = function () {
  56555. };
  56556. Gamepad.GAMEPAD = 0;
  56557. Gamepad.GENERIC = 1;
  56558. Gamepad.XBOX = 2;
  56559. Gamepad.POSE_ENABLED = 3;
  56560. return Gamepad;
  56561. }());
  56562. BABYLON.Gamepad = Gamepad;
  56563. var GenericPad = /** @class */ (function (_super) {
  56564. __extends(GenericPad, _super);
  56565. function GenericPad(id, index, browserGamepad) {
  56566. var _this = _super.call(this, id, index, browserGamepad) || this;
  56567. _this.onButtonDownObservable = new BABYLON.Observable();
  56568. _this.onButtonUpObservable = new BABYLON.Observable();
  56569. _this.type = Gamepad.GENERIC;
  56570. _this._buttons = new Array(browserGamepad.buttons.length);
  56571. return _this;
  56572. }
  56573. GenericPad.prototype.onbuttondown = function (callback) {
  56574. this._onbuttondown = callback;
  56575. };
  56576. GenericPad.prototype.onbuttonup = function (callback) {
  56577. this._onbuttonup = callback;
  56578. };
  56579. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56580. if (newValue !== currentValue) {
  56581. if (newValue === 1) {
  56582. if (this._onbuttondown) {
  56583. this._onbuttondown(buttonIndex);
  56584. }
  56585. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56586. }
  56587. if (newValue === 0) {
  56588. if (this._onbuttonup) {
  56589. this._onbuttonup(buttonIndex);
  56590. }
  56591. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56592. }
  56593. }
  56594. return newValue;
  56595. };
  56596. GenericPad.prototype.update = function () {
  56597. _super.prototype.update.call(this);
  56598. for (var index = 0; index < this._buttons.length; index++) {
  56599. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56600. }
  56601. };
  56602. GenericPad.prototype.dispose = function () {
  56603. _super.prototype.dispose.call(this);
  56604. this.onButtonDownObservable.clear();
  56605. this.onButtonUpObservable.clear();
  56606. };
  56607. return GenericPad;
  56608. }(Gamepad));
  56609. BABYLON.GenericPad = GenericPad;
  56610. })(BABYLON || (BABYLON = {}));
  56611. //# sourceMappingURL=babylon.gamepad.js.map
  56612. var BABYLON;
  56613. (function (BABYLON) {
  56614. var Xbox360Button;
  56615. (function (Xbox360Button) {
  56616. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56617. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56618. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56619. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56620. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56621. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56622. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56623. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56624. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56625. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56626. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56627. var Xbox360Dpad;
  56628. (function (Xbox360Dpad) {
  56629. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56630. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56631. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56632. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56633. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56634. var Xbox360Pad = /** @class */ (function (_super) {
  56635. __extends(Xbox360Pad, _super);
  56636. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56637. if (xboxOne === void 0) { xboxOne = false; }
  56638. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56639. _this._leftTrigger = 0;
  56640. _this._rightTrigger = 0;
  56641. _this.onButtonDownObservable = new BABYLON.Observable();
  56642. _this.onButtonUpObservable = new BABYLON.Observable();
  56643. _this.onPadDownObservable = new BABYLON.Observable();
  56644. _this.onPadUpObservable = new BABYLON.Observable();
  56645. _this._buttonA = 0;
  56646. _this._buttonB = 0;
  56647. _this._buttonX = 0;
  56648. _this._buttonY = 0;
  56649. _this._buttonBack = 0;
  56650. _this._buttonStart = 0;
  56651. _this._buttonLB = 0;
  56652. _this._buttonRB = 0;
  56653. _this._buttonLeftStick = 0;
  56654. _this._buttonRightStick = 0;
  56655. _this._dPadUp = 0;
  56656. _this._dPadDown = 0;
  56657. _this._dPadLeft = 0;
  56658. _this._dPadRight = 0;
  56659. _this._isXboxOnePad = false;
  56660. _this.type = BABYLON.Gamepad.XBOX;
  56661. _this._isXboxOnePad = xboxOne;
  56662. return _this;
  56663. }
  56664. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56665. this._onlefttriggerchanged = callback;
  56666. };
  56667. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56668. this._onrighttriggerchanged = callback;
  56669. };
  56670. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56671. get: function () {
  56672. return this._leftTrigger;
  56673. },
  56674. set: function (newValue) {
  56675. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56676. this._onlefttriggerchanged(newValue);
  56677. }
  56678. this._leftTrigger = newValue;
  56679. },
  56680. enumerable: true,
  56681. configurable: true
  56682. });
  56683. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56684. get: function () {
  56685. return this._rightTrigger;
  56686. },
  56687. set: function (newValue) {
  56688. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56689. this._onrighttriggerchanged(newValue);
  56690. }
  56691. this._rightTrigger = newValue;
  56692. },
  56693. enumerable: true,
  56694. configurable: true
  56695. });
  56696. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56697. this._onbuttondown = callback;
  56698. };
  56699. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56700. this._onbuttonup = callback;
  56701. };
  56702. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56703. this._ondpaddown = callback;
  56704. };
  56705. Xbox360Pad.prototype.ondpadup = function (callback) {
  56706. this._ondpadup = callback;
  56707. };
  56708. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56709. if (newValue !== currentValue) {
  56710. if (newValue === 1) {
  56711. if (this._onbuttondown) {
  56712. this._onbuttondown(buttonType);
  56713. }
  56714. this.onButtonDownObservable.notifyObservers(buttonType);
  56715. }
  56716. if (newValue === 0) {
  56717. if (this._onbuttonup) {
  56718. this._onbuttonup(buttonType);
  56719. }
  56720. this.onButtonUpObservable.notifyObservers(buttonType);
  56721. }
  56722. }
  56723. return newValue;
  56724. };
  56725. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56726. if (newValue !== currentValue) {
  56727. if (newValue === 1) {
  56728. if (this._ondpaddown) {
  56729. this._ondpaddown(buttonType);
  56730. }
  56731. this.onPadDownObservable.notifyObservers(buttonType);
  56732. }
  56733. if (newValue === 0) {
  56734. if (this._ondpadup) {
  56735. this._ondpadup(buttonType);
  56736. }
  56737. this.onPadUpObservable.notifyObservers(buttonType);
  56738. }
  56739. }
  56740. return newValue;
  56741. };
  56742. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56743. get: function () {
  56744. return this._buttonA;
  56745. },
  56746. set: function (value) {
  56747. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56748. },
  56749. enumerable: true,
  56750. configurable: true
  56751. });
  56752. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56753. get: function () {
  56754. return this._buttonB;
  56755. },
  56756. set: function (value) {
  56757. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56758. },
  56759. enumerable: true,
  56760. configurable: true
  56761. });
  56762. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56763. get: function () {
  56764. return this._buttonX;
  56765. },
  56766. set: function (value) {
  56767. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56768. },
  56769. enumerable: true,
  56770. configurable: true
  56771. });
  56772. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56773. get: function () {
  56774. return this._buttonY;
  56775. },
  56776. set: function (value) {
  56777. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56778. },
  56779. enumerable: true,
  56780. configurable: true
  56781. });
  56782. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56783. get: function () {
  56784. return this._buttonStart;
  56785. },
  56786. set: function (value) {
  56787. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56788. },
  56789. enumerable: true,
  56790. configurable: true
  56791. });
  56792. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56793. get: function () {
  56794. return this._buttonBack;
  56795. },
  56796. set: function (value) {
  56797. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56798. },
  56799. enumerable: true,
  56800. configurable: true
  56801. });
  56802. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56803. get: function () {
  56804. return this._buttonLB;
  56805. },
  56806. set: function (value) {
  56807. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56808. },
  56809. enumerable: true,
  56810. configurable: true
  56811. });
  56812. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56813. get: function () {
  56814. return this._buttonRB;
  56815. },
  56816. set: function (value) {
  56817. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56818. },
  56819. enumerable: true,
  56820. configurable: true
  56821. });
  56822. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56823. get: function () {
  56824. return this._buttonLeftStick;
  56825. },
  56826. set: function (value) {
  56827. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56828. },
  56829. enumerable: true,
  56830. configurable: true
  56831. });
  56832. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56833. get: function () {
  56834. return this._buttonRightStick;
  56835. },
  56836. set: function (value) {
  56837. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56838. },
  56839. enumerable: true,
  56840. configurable: true
  56841. });
  56842. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56843. get: function () {
  56844. return this._dPadUp;
  56845. },
  56846. set: function (value) {
  56847. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56848. },
  56849. enumerable: true,
  56850. configurable: true
  56851. });
  56852. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56853. get: function () {
  56854. return this._dPadDown;
  56855. },
  56856. set: function (value) {
  56857. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56858. },
  56859. enumerable: true,
  56860. configurable: true
  56861. });
  56862. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56863. get: function () {
  56864. return this._dPadLeft;
  56865. },
  56866. set: function (value) {
  56867. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56868. },
  56869. enumerable: true,
  56870. configurable: true
  56871. });
  56872. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56873. get: function () {
  56874. return this._dPadRight;
  56875. },
  56876. set: function (value) {
  56877. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56878. },
  56879. enumerable: true,
  56880. configurable: true
  56881. });
  56882. Xbox360Pad.prototype.update = function () {
  56883. _super.prototype.update.call(this);
  56884. if (this._isXboxOnePad) {
  56885. this.buttonA = this.browserGamepad.buttons[0].value;
  56886. this.buttonB = this.browserGamepad.buttons[1].value;
  56887. this.buttonX = this.browserGamepad.buttons[2].value;
  56888. this.buttonY = this.browserGamepad.buttons[3].value;
  56889. this.buttonLB = this.browserGamepad.buttons[4].value;
  56890. this.buttonRB = this.browserGamepad.buttons[5].value;
  56891. this.leftTrigger = this.browserGamepad.axes[2];
  56892. this.rightTrigger = this.browserGamepad.axes[5];
  56893. this.buttonBack = this.browserGamepad.buttons[9].value;
  56894. this.buttonStart = this.browserGamepad.buttons[8].value;
  56895. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56896. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56897. this.dPadUp = this.browserGamepad.buttons[11].value;
  56898. this.dPadDown = this.browserGamepad.buttons[12].value;
  56899. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56900. this.dPadRight = this.browserGamepad.buttons[14].value;
  56901. }
  56902. else {
  56903. this.buttonA = this.browserGamepad.buttons[0].value;
  56904. this.buttonB = this.browserGamepad.buttons[1].value;
  56905. this.buttonX = this.browserGamepad.buttons[2].value;
  56906. this.buttonY = this.browserGamepad.buttons[3].value;
  56907. this.buttonLB = this.browserGamepad.buttons[4].value;
  56908. this.buttonRB = this.browserGamepad.buttons[5].value;
  56909. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56910. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56911. this.buttonBack = this.browserGamepad.buttons[8].value;
  56912. this.buttonStart = this.browserGamepad.buttons[9].value;
  56913. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56914. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56915. this.dPadUp = this.browserGamepad.buttons[12].value;
  56916. this.dPadDown = this.browserGamepad.buttons[13].value;
  56917. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56918. this.dPadRight = this.browserGamepad.buttons[15].value;
  56919. }
  56920. };
  56921. Xbox360Pad.prototype.dispose = function () {
  56922. _super.prototype.dispose.call(this);
  56923. this.onButtonDownObservable.clear();
  56924. this.onButtonUpObservable.clear();
  56925. this.onPadDownObservable.clear();
  56926. this.onPadUpObservable.clear();
  56927. };
  56928. return Xbox360Pad;
  56929. }(BABYLON.Gamepad));
  56930. BABYLON.Xbox360Pad = Xbox360Pad;
  56931. })(BABYLON || (BABYLON = {}));
  56932. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56933. var BABYLON;
  56934. (function (BABYLON) {
  56935. var PoseEnabledControllerType;
  56936. (function (PoseEnabledControllerType) {
  56937. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56938. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56939. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56940. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56941. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56942. var PoseEnabledControllerHelper = /** @class */ (function () {
  56943. function PoseEnabledControllerHelper() {
  56944. }
  56945. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56946. // Oculus Touch
  56947. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56948. return new BABYLON.OculusTouchController(vrGamepad);
  56949. }
  56950. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56951. return new BABYLON.WindowsMotionController(vrGamepad);
  56952. }
  56953. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56954. return new BABYLON.ViveController(vrGamepad);
  56955. }
  56956. else {
  56957. return new BABYLON.GenericController(vrGamepad);
  56958. }
  56959. };
  56960. return PoseEnabledControllerHelper;
  56961. }());
  56962. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56963. var PoseEnabledController = /** @class */ (function (_super) {
  56964. __extends(PoseEnabledController, _super);
  56965. function PoseEnabledController(browserGamepad) {
  56966. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56967. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  56968. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  56969. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  56970. // Represents device position and rotation in babylon space
  56971. _this.devicePosition = BABYLON.Vector3.Zero();
  56972. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56973. _this.deviceScaleFactor = 1;
  56974. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56975. _this._deviceToWorld = BABYLON.Matrix.Identity();
  56976. _this._workingMatrix = BABYLON.Matrix.Identity();
  56977. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56978. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56979. _this.position = BABYLON.Vector3.Zero();
  56980. _this.rotationQuaternion = new BABYLON.Quaternion();
  56981. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56982. _this._calculatedRotation = new BABYLON.Quaternion();
  56983. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56984. return _this;
  56985. }
  56986. PoseEnabledController.prototype.update = function () {
  56987. _super.prototype.update.call(this);
  56988. var pose = this.browserGamepad.pose;
  56989. this.updateFromDevice(pose);
  56990. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  56991. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  56992. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  56993. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  56994. if (this._mesh) {
  56995. this._mesh.position.copyFrom(this.devicePosition);
  56996. if (this._mesh.rotationQuaternion) {
  56997. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  56998. }
  56999. }
  57000. };
  57001. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57002. if (poseData) {
  57003. this.rawPose = poseData;
  57004. if (poseData.position) {
  57005. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  57006. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  57007. this._deviceRoomPosition.z *= -1;
  57008. }
  57009. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  57010. this._calculatedPosition.addInPlace(this.position);
  57011. }
  57012. var pose = this.rawPose;
  57013. if (poseData.orientation && pose.orientation) {
  57014. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  57015. if (this._mesh) {
  57016. if (this._mesh.getScene().useRightHandedSystem) {
  57017. this._deviceRoomRotationQuaternion.z *= -1;
  57018. this._deviceRoomRotationQuaternion.w *= -1;
  57019. }
  57020. else {
  57021. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  57022. }
  57023. }
  57024. // if the camera is set, rotate to the camera's rotation
  57025. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  57026. }
  57027. }
  57028. };
  57029. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  57030. if (this._mesh) {
  57031. this._mesh.parent = null;
  57032. }
  57033. this._mesh = mesh;
  57034. if (this._poseControlledCamera) {
  57035. this._mesh.parent = this._poseControlledCamera;
  57036. }
  57037. if (!this._mesh.rotationQuaternion) {
  57038. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  57039. }
  57040. };
  57041. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  57042. this._poseControlledCamera = camera;
  57043. if (this._mesh) {
  57044. this._mesh.parent = this._poseControlledCamera;
  57045. }
  57046. };
  57047. PoseEnabledController.prototype.dispose = function () {
  57048. if (this._mesh) {
  57049. this._mesh.dispose();
  57050. }
  57051. this._mesh = null;
  57052. _super.prototype.dispose.call(this);
  57053. };
  57054. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  57055. get: function () {
  57056. return this._mesh;
  57057. },
  57058. enumerable: true,
  57059. configurable: true
  57060. });
  57061. PoseEnabledController.prototype.getForwardRay = function (length) {
  57062. if (length === void 0) { length = 100; }
  57063. if (!this.mesh) {
  57064. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  57065. }
  57066. var m = this.mesh.getWorldMatrix();
  57067. var origin = m.getTranslation();
  57068. var forward = new BABYLON.Vector3(0, 0, -1);
  57069. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57070. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57071. return new BABYLON.Ray(origin, direction, length);
  57072. };
  57073. return PoseEnabledController;
  57074. }(BABYLON.Gamepad));
  57075. BABYLON.PoseEnabledController = PoseEnabledController;
  57076. })(BABYLON || (BABYLON = {}));
  57077. //# sourceMappingURL=babylon.poseEnabledController.js.map
  57078. var BABYLON;
  57079. (function (BABYLON) {
  57080. var WebVRController = /** @class */ (function (_super) {
  57081. __extends(WebVRController, _super);
  57082. function WebVRController(vrGamepad) {
  57083. var _this = _super.call(this, vrGamepad) || this;
  57084. // Observables
  57085. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  57086. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  57087. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  57088. _this.onPadStateChangedObservable = new BABYLON.Observable();
  57089. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  57090. _this.pad = { x: 0, y: 0 };
  57091. // avoid GC, store state in a tmp object
  57092. _this._changes = {
  57093. pressChanged: false,
  57094. touchChanged: false,
  57095. valueChanged: false,
  57096. changed: false
  57097. };
  57098. _this._buttons = new Array(vrGamepad.buttons.length);
  57099. _this.hand = vrGamepad.hand;
  57100. return _this;
  57101. }
  57102. WebVRController.prototype.onButtonStateChange = function (callback) {
  57103. this._onButtonStateChange = callback;
  57104. };
  57105. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  57106. get: function () {
  57107. return this._defaultModel;
  57108. },
  57109. enumerable: true,
  57110. configurable: true
  57111. });
  57112. WebVRController.prototype.update = function () {
  57113. _super.prototype.update.call(this);
  57114. for (var index = 0; index < this._buttons.length; index++) {
  57115. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  57116. }
  57117. ;
  57118. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  57119. this.pad.x = this.leftStick.x;
  57120. this.pad.y = this.leftStick.y;
  57121. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  57122. }
  57123. };
  57124. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  57125. if (!newState) {
  57126. newState = {
  57127. pressed: false,
  57128. touched: false,
  57129. value: 0
  57130. };
  57131. }
  57132. if (!currentState) {
  57133. this._buttons[buttonIndex] = {
  57134. pressed: newState.pressed,
  57135. touched: newState.touched,
  57136. value: newState.value
  57137. };
  57138. return;
  57139. }
  57140. this._checkChanges(newState, currentState);
  57141. if (this._changes.changed) {
  57142. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  57143. this.handleButtonChange(buttonIndex, newState, this._changes);
  57144. }
  57145. this._buttons[buttonIndex].pressed = newState.pressed;
  57146. this._buttons[buttonIndex].touched = newState.touched;
  57147. // oculus triggers are never 0, thou not touched.
  57148. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  57149. };
  57150. WebVRController.prototype._checkChanges = function (newState, currentState) {
  57151. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  57152. this._changes.touchChanged = newState.touched !== currentState.touched;
  57153. this._changes.valueChanged = newState.value !== currentState.value;
  57154. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  57155. return this._changes;
  57156. };
  57157. WebVRController.prototype.dispose = function () {
  57158. _super.prototype.dispose.call(this);
  57159. this.onTriggerStateChangedObservable.clear();
  57160. this.onMainButtonStateChangedObservable.clear();
  57161. this.onSecondaryButtonStateChangedObservable.clear();
  57162. this.onPadStateChangedObservable.clear();
  57163. this.onPadValuesChangedObservable.clear();
  57164. };
  57165. return WebVRController;
  57166. }(BABYLON.PoseEnabledController));
  57167. BABYLON.WebVRController = WebVRController;
  57168. })(BABYLON || (BABYLON = {}));
  57169. //# sourceMappingURL=babylon.webVRController.js.map
  57170. var BABYLON;
  57171. (function (BABYLON) {
  57172. var OculusTouchController = /** @class */ (function (_super) {
  57173. __extends(OculusTouchController, _super);
  57174. function OculusTouchController(vrGamepad) {
  57175. var _this = _super.call(this, vrGamepad) || this;
  57176. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  57177. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  57178. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  57179. return _this;
  57180. }
  57181. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57182. var _this = this;
  57183. var meshName;
  57184. // Hand
  57185. if (this.hand === 'left') {
  57186. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  57187. }
  57188. else {
  57189. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  57190. }
  57191. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  57192. /*
  57193. Parent Mesh name: oculus_touch_left
  57194. - body
  57195. - trigger
  57196. - thumbstick
  57197. - grip
  57198. - button_y
  57199. - button_x
  57200. - button_enter
  57201. */
  57202. _this._defaultModel = newMeshes[1];
  57203. _this.attachToMesh(_this._defaultModel);
  57204. if (meshLoaded) {
  57205. meshLoaded(_this._defaultModel);
  57206. }
  57207. });
  57208. };
  57209. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  57210. // helper getters for left and right hand.
  57211. get: function () {
  57212. if (this.hand === 'right') {
  57213. return this.onMainButtonStateChangedObservable;
  57214. }
  57215. else {
  57216. throw new Error('No A button on left hand');
  57217. }
  57218. },
  57219. enumerable: true,
  57220. configurable: true
  57221. });
  57222. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  57223. get: function () {
  57224. if (this.hand === 'right') {
  57225. return this.onSecondaryButtonStateChangedObservable;
  57226. }
  57227. else {
  57228. throw new Error('No B button on left hand');
  57229. }
  57230. },
  57231. enumerable: true,
  57232. configurable: true
  57233. });
  57234. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  57235. get: function () {
  57236. if (this.hand === 'left') {
  57237. return this.onMainButtonStateChangedObservable;
  57238. }
  57239. else {
  57240. throw new Error('No X button on right hand');
  57241. }
  57242. },
  57243. enumerable: true,
  57244. configurable: true
  57245. });
  57246. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  57247. get: function () {
  57248. if (this.hand === 'left') {
  57249. return this.onSecondaryButtonStateChangedObservable;
  57250. }
  57251. else {
  57252. throw new Error('No Y button on right hand');
  57253. }
  57254. },
  57255. enumerable: true,
  57256. configurable: true
  57257. });
  57258. /*
  57259. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  57260. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  57261. 2) secondary trigger (same)
  57262. 3) A (right) X (left), touch, pressed = value
  57263. 4) B / Y
  57264. 5) thumb rest
  57265. */
  57266. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57267. var notifyObject = state; //{ state: state, changes: changes };
  57268. var triggerDirection = this.hand === 'right' ? -1 : 1;
  57269. switch (buttonIdx) {
  57270. case 0:
  57271. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57272. return;
  57273. case 1:// index trigger
  57274. if (this._defaultModel) {
  57275. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  57276. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  57277. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  57278. }
  57279. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57280. return;
  57281. case 2:// secondary trigger
  57282. if (this._defaultModel) {
  57283. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  57284. }
  57285. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  57286. return;
  57287. case 3:
  57288. if (this._defaultModel) {
  57289. if (notifyObject.pressed) {
  57290. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  57291. }
  57292. else {
  57293. (this._defaultModel.getChildren()[1]).position.y = 0;
  57294. }
  57295. }
  57296. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57297. return;
  57298. case 4:
  57299. if (this._defaultModel) {
  57300. if (notifyObject.pressed) {
  57301. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57302. }
  57303. else {
  57304. (this._defaultModel.getChildren()[2]).position.y = 0;
  57305. }
  57306. }
  57307. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57308. return;
  57309. case 5:
  57310. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  57311. return;
  57312. }
  57313. };
  57314. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  57315. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  57316. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  57317. return OculusTouchController;
  57318. }(BABYLON.WebVRController));
  57319. BABYLON.OculusTouchController = OculusTouchController;
  57320. })(BABYLON || (BABYLON = {}));
  57321. //# sourceMappingURL=babylon.oculusTouchController.js.map
  57322. var BABYLON;
  57323. (function (BABYLON) {
  57324. var ViveController = /** @class */ (function (_super) {
  57325. __extends(ViveController, _super);
  57326. function ViveController(vrGamepad) {
  57327. var _this = _super.call(this, vrGamepad) || this;
  57328. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  57329. _this._invertLeftStickY = true;
  57330. return _this;
  57331. }
  57332. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57333. var _this = this;
  57334. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  57335. /*
  57336. Parent Mesh name: ViveWand
  57337. - body
  57338. - r_gripper
  57339. - l_gripper
  57340. - menu_button
  57341. - system_button
  57342. - trackpad
  57343. - trigger
  57344. - LED
  57345. */
  57346. _this._defaultModel = newMeshes[1];
  57347. _this.attachToMesh(_this._defaultModel);
  57348. if (meshLoaded) {
  57349. meshLoaded(_this._defaultModel);
  57350. }
  57351. });
  57352. };
  57353. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  57354. get: function () {
  57355. return this.onMainButtonStateChangedObservable;
  57356. },
  57357. enumerable: true,
  57358. configurable: true
  57359. });
  57360. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  57361. get: function () {
  57362. return this.onMainButtonStateChangedObservable;
  57363. },
  57364. enumerable: true,
  57365. configurable: true
  57366. });
  57367. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  57368. get: function () {
  57369. return this.onSecondaryButtonStateChangedObservable;
  57370. },
  57371. enumerable: true,
  57372. configurable: true
  57373. });
  57374. /**
  57375. * Vive mapping:
  57376. * 0: touchpad
  57377. * 1: trigger
  57378. * 2: left AND right buttons
  57379. * 3: menu button
  57380. */
  57381. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57382. var notifyObject = state; //{ state: state, changes: changes };
  57383. switch (buttonIdx) {
  57384. case 0:
  57385. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57386. return;
  57387. case 1:// index trigger
  57388. if (this._defaultModel) {
  57389. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  57390. }
  57391. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57392. return;
  57393. case 2:// left AND right button
  57394. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57395. return;
  57396. case 3:
  57397. if (this._defaultModel) {
  57398. if (notifyObject.pressed) {
  57399. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57400. }
  57401. else {
  57402. (this._defaultModel.getChildren()[2]).position.y = 0;
  57403. }
  57404. }
  57405. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57406. return;
  57407. }
  57408. };
  57409. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  57410. ViveController.MODEL_FILENAME = 'wand.babylon';
  57411. return ViveController;
  57412. }(BABYLON.WebVRController));
  57413. BABYLON.ViveController = ViveController;
  57414. })(BABYLON || (BABYLON = {}));
  57415. //# sourceMappingURL=babylon.viveController.js.map
  57416. var BABYLON;
  57417. (function (BABYLON) {
  57418. var GenericController = /** @class */ (function (_super) {
  57419. __extends(GenericController, _super);
  57420. function GenericController(vrGamepad) {
  57421. return _super.call(this, vrGamepad) || this;
  57422. }
  57423. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57424. var _this = this;
  57425. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  57426. _this._defaultModel = newMeshes[1];
  57427. _this.attachToMesh(_this._defaultModel);
  57428. if (meshLoaded) {
  57429. meshLoaded(_this._defaultModel);
  57430. }
  57431. });
  57432. };
  57433. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57434. console.log("Button id: " + buttonIdx + "state: ");
  57435. console.dir(state);
  57436. };
  57437. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  57438. GenericController.MODEL_FILENAME = 'generic.babylon';
  57439. return GenericController;
  57440. }(BABYLON.WebVRController));
  57441. BABYLON.GenericController = GenericController;
  57442. })(BABYLON || (BABYLON = {}));
  57443. //# sourceMappingURL=babylon.genericController.js.map
  57444. var BABYLON;
  57445. (function (BABYLON) {
  57446. var LoadedMeshInfo = /** @class */ (function () {
  57447. function LoadedMeshInfo() {
  57448. this.buttonMeshes = {};
  57449. this.axisMeshes = {};
  57450. }
  57451. return LoadedMeshInfo;
  57452. }());
  57453. var WindowsMotionController = /** @class */ (function (_super) {
  57454. __extends(WindowsMotionController, _super);
  57455. function WindowsMotionController(vrGamepad) {
  57456. var _this = _super.call(this, vrGamepad) || this;
  57457. _this._mapping = {
  57458. // Semantic button names
  57459. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  57460. // A mapping of the button name to glTF model node name
  57461. // that should be transformed by button value.
  57462. buttonMeshNames: {
  57463. 'trigger': 'SELECT',
  57464. 'menu': 'MENU',
  57465. 'grip': 'GRASP',
  57466. 'thumbstick': 'THUMBSTICK_PRESS',
  57467. 'trackpad': 'TOUCHPAD_PRESS'
  57468. },
  57469. // This mapping is used to translate from the Motion Controller to Babylon semantics
  57470. buttonObservableNames: {
  57471. 'trigger': 'onTriggerStateChangedObservable',
  57472. 'menu': 'onSecondaryButtonStateChangedObservable',
  57473. 'grip': 'onMainButtonStateChangedObservable',
  57474. 'thumbstick': 'onPadStateChangedObservable',
  57475. 'trackpad': 'onTrackpadChangedObservable'
  57476. },
  57477. // A mapping of the axis name to glTF model node name
  57478. // that should be transformed by axis value.
  57479. // This array mirrors the browserGamepad.axes array, such that
  57480. // the mesh corresponding to axis 0 is in this array index 0.
  57481. axisMeshNames: [
  57482. 'THUMBSTICK_X',
  57483. 'THUMBSTICK_Y',
  57484. 'TOUCHPAD_TOUCH_X',
  57485. 'TOUCHPAD_TOUCH_Y'
  57486. ],
  57487. pointingPoseMeshName: 'POINTING_POSE'
  57488. };
  57489. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57490. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  57491. _this.trackpad = { x: 0, y: 0 };
  57492. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57493. _this._loadedMeshInfo = null;
  57494. return _this;
  57495. }
  57496. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57497. get: function () {
  57498. return this.onTriggerStateChangedObservable;
  57499. },
  57500. enumerable: true,
  57501. configurable: true
  57502. });
  57503. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57504. get: function () {
  57505. return this.onSecondaryButtonStateChangedObservable;
  57506. },
  57507. enumerable: true,
  57508. configurable: true
  57509. });
  57510. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57511. get: function () {
  57512. return this.onMainButtonStateChangedObservable;
  57513. },
  57514. enumerable: true,
  57515. configurable: true
  57516. });
  57517. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57518. get: function () {
  57519. return this.onPadStateChangedObservable;
  57520. },
  57521. enumerable: true,
  57522. configurable: true
  57523. });
  57524. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57525. get: function () {
  57526. return this.onTrackpadChangedObservable;
  57527. },
  57528. enumerable: true,
  57529. configurable: true
  57530. });
  57531. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  57532. get: function () {
  57533. return this.onTrackpadValuesChangedObservable;
  57534. },
  57535. enumerable: true,
  57536. configurable: true
  57537. });
  57538. /**
  57539. * Called once per frame by the engine.
  57540. */
  57541. WindowsMotionController.prototype.update = function () {
  57542. _super.prototype.update.call(this);
  57543. // Only need to animate axes if there is a loaded mesh
  57544. if (this._loadedMeshInfo) {
  57545. if (this.browserGamepad.axes) {
  57546. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  57547. this.trackpad.x = this.browserGamepad["axes"][2];
  57548. this.trackpad.y = this.browserGamepad["axes"][3];
  57549. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  57550. }
  57551. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57552. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57553. }
  57554. }
  57555. }
  57556. };
  57557. /**
  57558. * Called once for each button that changed state since the last frame
  57559. * @param buttonIdx Which button index changed
  57560. * @param state New state of the button
  57561. * @param changes Which properties on the state changed since last frame
  57562. */
  57563. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57564. var buttonName = this._mapping.buttons[buttonIdx];
  57565. if (!buttonName) {
  57566. return;
  57567. }
  57568. // Only emit events for buttons that we know how to map from index to name
  57569. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57570. if (observable) {
  57571. observable.notifyObservers(state);
  57572. }
  57573. this.lerpButtonTransform(buttonName, state.value);
  57574. };
  57575. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57576. // If there is no loaded mesh, there is nothing to transform.
  57577. if (!this._loadedMeshInfo) {
  57578. return;
  57579. }
  57580. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57581. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57582. return;
  57583. }
  57584. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57585. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57586. };
  57587. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57588. if (!this._loadedMeshInfo) {
  57589. return;
  57590. }
  57591. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57592. if (!meshInfo) {
  57593. return;
  57594. }
  57595. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57596. return;
  57597. }
  57598. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57599. var lerpValue = axisValue * 0.5 + 0.5;
  57600. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57601. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57602. };
  57603. /**
  57604. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57605. * @param scene scene in which to add meshes
  57606. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57607. */
  57608. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57609. var _this = this;
  57610. if (forceDefault === void 0) { forceDefault = false; }
  57611. var path;
  57612. var filename;
  57613. // Checking if GLB loader is present
  57614. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable("glb")) {
  57615. // Determine the device specific folder based on the ID suffix
  57616. var device = 'default';
  57617. if (this.id && !forceDefault) {
  57618. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57619. device = ((match && match[0]) || device);
  57620. }
  57621. // Hand
  57622. if (this.hand === 'left') {
  57623. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57624. }
  57625. else {
  57626. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57627. }
  57628. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57629. }
  57630. else {
  57631. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57632. path = BABYLON.GenericController.MODEL_BASE_URL;
  57633. filename = BABYLON.GenericController.MODEL_FILENAME;
  57634. }
  57635. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57636. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57637. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57638. if (!_this._loadedMeshInfo) {
  57639. return;
  57640. }
  57641. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57642. _this.attachToMesh(_this._defaultModel);
  57643. if (meshLoaded) {
  57644. meshLoaded(_this._defaultModel);
  57645. }
  57646. }, null, function (scene, message) {
  57647. BABYLON.Tools.Log(message);
  57648. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57649. if (!forceDefault) {
  57650. _this.initControllerMesh(scene, meshLoaded, true);
  57651. }
  57652. });
  57653. };
  57654. /**
  57655. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57656. * can be transformed by button presses and axes values, based on this._mapping.
  57657. *
  57658. * @param scene scene in which the meshes exist
  57659. * @param meshes list of meshes that make up the controller model to process
  57660. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57661. */
  57662. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57663. var loadedMeshInfo = null;
  57664. // Create a new mesh to contain the glTF hierarchy
  57665. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57666. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57667. var childMesh = null;
  57668. for (var i = 0; i < meshes.length; i++) {
  57669. var mesh = meshes[i];
  57670. if (!mesh.parent) {
  57671. // Exclude controller meshes from picking results
  57672. mesh.isPickable = false;
  57673. // Handle root node, attach to the new parentMesh
  57674. childMesh = mesh;
  57675. break;
  57676. }
  57677. }
  57678. if (childMesh) {
  57679. childMesh.setParent(parentMesh);
  57680. // Create our mesh info. Note that this method will always return non-null.
  57681. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57682. }
  57683. else {
  57684. BABYLON.Tools.Warn('Could not find root node in model file.');
  57685. }
  57686. return loadedMeshInfo;
  57687. };
  57688. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57689. var loadedMeshInfo = new LoadedMeshInfo();
  57690. var i;
  57691. loadedMeshInfo.rootNode = rootNode;
  57692. // Reset the caches
  57693. loadedMeshInfo.buttonMeshes = {};
  57694. loadedMeshInfo.axisMeshes = {};
  57695. // Button Meshes
  57696. for (i = 0; i < this._mapping.buttons.length; i++) {
  57697. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57698. if (!buttonMeshName) {
  57699. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57700. continue;
  57701. }
  57702. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57703. if (!buttonMesh) {
  57704. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57705. continue;
  57706. }
  57707. var buttonMeshInfo = {
  57708. index: i,
  57709. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57710. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57711. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57712. };
  57713. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57714. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57715. }
  57716. else {
  57717. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57718. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57719. '(VALUE: ' + !!buttonMeshInfo.value +
  57720. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57721. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57722. ')');
  57723. }
  57724. }
  57725. // Axis Meshes
  57726. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57727. var axisMeshName = this._mapping.axisMeshNames[i];
  57728. if (!axisMeshName) {
  57729. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57730. continue;
  57731. }
  57732. var axisMesh = getChildByName(rootNode, axisMeshName);
  57733. if (!axisMesh) {
  57734. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57735. continue;
  57736. }
  57737. var axisMeshInfo = {
  57738. index: i,
  57739. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57740. min: getImmediateChildByName(axisMesh, 'MIN'),
  57741. max: getImmediateChildByName(axisMesh, 'MAX')
  57742. };
  57743. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57744. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57745. }
  57746. else {
  57747. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57748. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57749. '(VALUE: ' + !!axisMeshInfo.value +
  57750. ', MIN: ' + !!axisMeshInfo.min +
  57751. ', MAX:' + !!axisMeshInfo.max +
  57752. ')');
  57753. }
  57754. }
  57755. // Pointing Ray
  57756. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57757. if (!loadedMeshInfo.pointingPoseNode) {
  57758. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57759. }
  57760. return loadedMeshInfo;
  57761. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57762. function getChildByName(node, name) {
  57763. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57764. }
  57765. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57766. function getImmediateChildByName(node, name) {
  57767. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57768. }
  57769. };
  57770. WindowsMotionController.prototype.getForwardRay = function (length) {
  57771. if (length === void 0) { length = 100; }
  57772. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57773. return _super.prototype.getForwardRay.call(this, length);
  57774. }
  57775. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57776. var origin = m.getTranslation();
  57777. var forward = new BABYLON.Vector3(0, 0, -1);
  57778. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57779. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57780. return new BABYLON.Ray(origin, direction, length);
  57781. };
  57782. WindowsMotionController.prototype.dispose = function () {
  57783. _super.prototype.dispose.call(this);
  57784. this.onTrackpadChangedObservable.clear();
  57785. };
  57786. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57787. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57788. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57789. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57790. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57791. return WindowsMotionController;
  57792. }(BABYLON.WebVRController));
  57793. BABYLON.WindowsMotionController = WindowsMotionController;
  57794. })(BABYLON || (BABYLON = {}));
  57795. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57796. var BABYLON;
  57797. (function (BABYLON) {
  57798. var FollowCamera = /** @class */ (function (_super) {
  57799. __extends(FollowCamera, _super);
  57800. function FollowCamera(name, position, scene, lockedTarget) {
  57801. if (lockedTarget === void 0) { lockedTarget = null; }
  57802. var _this = _super.call(this, name, position, scene) || this;
  57803. _this.radius = 12;
  57804. _this.rotationOffset = 0;
  57805. _this.heightOffset = 4;
  57806. _this.cameraAcceleration = 0.05;
  57807. _this.maxCameraSpeed = 20;
  57808. _this.lockedTarget = lockedTarget;
  57809. return _this;
  57810. }
  57811. FollowCamera.prototype.getRadians = function (degrees) {
  57812. return degrees * Math.PI / 180;
  57813. };
  57814. FollowCamera.prototype.follow = function (cameraTarget) {
  57815. if (!cameraTarget)
  57816. return;
  57817. var yRotation;
  57818. if (cameraTarget.rotationQuaternion) {
  57819. var rotMatrix = new BABYLON.Matrix();
  57820. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57821. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57822. }
  57823. else {
  57824. yRotation = cameraTarget.rotation.y;
  57825. }
  57826. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57827. var targetPosition = cameraTarget.getAbsolutePosition();
  57828. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57829. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57830. var dx = targetX - this.position.x;
  57831. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57832. var dz = (targetZ) - this.position.z;
  57833. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57834. var vy = dy * this.cameraAcceleration;
  57835. var vz = dz * this.cameraAcceleration * 2;
  57836. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57837. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57838. }
  57839. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57840. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57841. }
  57842. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57843. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57844. }
  57845. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57846. this.setTarget(targetPosition);
  57847. };
  57848. FollowCamera.prototype._checkInputs = function () {
  57849. _super.prototype._checkInputs.call(this);
  57850. if (this.lockedTarget) {
  57851. this.follow(this.lockedTarget);
  57852. }
  57853. };
  57854. FollowCamera.prototype.getClassName = function () {
  57855. return "FollowCamera";
  57856. };
  57857. __decorate([
  57858. BABYLON.serialize()
  57859. ], FollowCamera.prototype, "radius", void 0);
  57860. __decorate([
  57861. BABYLON.serialize()
  57862. ], FollowCamera.prototype, "rotationOffset", void 0);
  57863. __decorate([
  57864. BABYLON.serialize()
  57865. ], FollowCamera.prototype, "heightOffset", void 0);
  57866. __decorate([
  57867. BABYLON.serialize()
  57868. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57869. __decorate([
  57870. BABYLON.serialize()
  57871. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57872. __decorate([
  57873. BABYLON.serializeAsMeshReference("lockedTargetId")
  57874. ], FollowCamera.prototype, "lockedTarget", void 0);
  57875. return FollowCamera;
  57876. }(BABYLON.TargetCamera));
  57877. BABYLON.FollowCamera = FollowCamera;
  57878. var ArcFollowCamera = /** @class */ (function (_super) {
  57879. __extends(ArcFollowCamera, _super);
  57880. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57881. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57882. _this.alpha = alpha;
  57883. _this.beta = beta;
  57884. _this.radius = radius;
  57885. _this.target = target;
  57886. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57887. _this.follow();
  57888. return _this;
  57889. }
  57890. ArcFollowCamera.prototype.follow = function () {
  57891. if (!this.target) {
  57892. return;
  57893. }
  57894. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57895. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57896. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57897. var targetPosition = this.target.getAbsolutePosition();
  57898. this.position = targetPosition.add(this._cartesianCoordinates);
  57899. this.setTarget(targetPosition);
  57900. };
  57901. ArcFollowCamera.prototype._checkInputs = function () {
  57902. _super.prototype._checkInputs.call(this);
  57903. this.follow();
  57904. };
  57905. ArcFollowCamera.prototype.getClassName = function () {
  57906. return "ArcFollowCamera";
  57907. };
  57908. return ArcFollowCamera;
  57909. }(BABYLON.TargetCamera));
  57910. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57911. })(BABYLON || (BABYLON = {}));
  57912. //# sourceMappingURL=babylon.followCamera.js.map
  57913. var BABYLON;
  57914. (function (BABYLON) {
  57915. // We're mainly based on the logic defined into the FreeCamera code
  57916. var UniversalCamera = /** @class */ (function (_super) {
  57917. __extends(UniversalCamera, _super);
  57918. //-- end properties for backward compatibility for inputs
  57919. function UniversalCamera(name, position, scene) {
  57920. var _this = _super.call(this, name, position, scene) || this;
  57921. _this.inputs.addGamepad();
  57922. return _this;
  57923. }
  57924. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57925. //-- Begin properties for backward compatibility for inputs
  57926. get: function () {
  57927. var gamepad = this.inputs.attached["gamepad"];
  57928. if (gamepad)
  57929. return gamepad.gamepadAngularSensibility;
  57930. return 0;
  57931. },
  57932. set: function (value) {
  57933. var gamepad = this.inputs.attached["gamepad"];
  57934. if (gamepad)
  57935. gamepad.gamepadAngularSensibility = value;
  57936. },
  57937. enumerable: true,
  57938. configurable: true
  57939. });
  57940. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57941. get: function () {
  57942. var gamepad = this.inputs.attached["gamepad"];
  57943. if (gamepad)
  57944. return gamepad.gamepadMoveSensibility;
  57945. return 0;
  57946. },
  57947. set: function (value) {
  57948. var gamepad = this.inputs.attached["gamepad"];
  57949. if (gamepad)
  57950. gamepad.gamepadMoveSensibility = value;
  57951. },
  57952. enumerable: true,
  57953. configurable: true
  57954. });
  57955. UniversalCamera.prototype.getClassName = function () {
  57956. return "UniversalCamera";
  57957. };
  57958. return UniversalCamera;
  57959. }(BABYLON.TouchCamera));
  57960. BABYLON.UniversalCamera = UniversalCamera;
  57961. })(BABYLON || (BABYLON = {}));
  57962. //# sourceMappingURL=babylon.universalCamera.js.map
  57963. var BABYLON;
  57964. (function (BABYLON) {
  57965. // We're mainly based on the logic defined into the FreeCamera code
  57966. var GamepadCamera = /** @class */ (function (_super) {
  57967. __extends(GamepadCamera, _super);
  57968. //-- end properties for backward compatibility for inputs
  57969. function GamepadCamera(name, position, scene) {
  57970. return _super.call(this, name, position, scene) || this;
  57971. }
  57972. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57973. //-- Begin properties for backward compatibility for inputs
  57974. get: function () {
  57975. var gamepad = this.inputs.attached["gamepad"];
  57976. if (gamepad)
  57977. return gamepad.gamepadAngularSensibility;
  57978. return 0;
  57979. },
  57980. set: function (value) {
  57981. var gamepad = this.inputs.attached["gamepad"];
  57982. if (gamepad)
  57983. gamepad.gamepadAngularSensibility = value;
  57984. },
  57985. enumerable: true,
  57986. configurable: true
  57987. });
  57988. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57989. get: function () {
  57990. var gamepad = this.inputs.attached["gamepad"];
  57991. if (gamepad)
  57992. return gamepad.gamepadMoveSensibility;
  57993. return 0;
  57994. },
  57995. set: function (value) {
  57996. var gamepad = this.inputs.attached["gamepad"];
  57997. if (gamepad)
  57998. gamepad.gamepadMoveSensibility = value;
  57999. },
  58000. enumerable: true,
  58001. configurable: true
  58002. });
  58003. GamepadCamera.prototype.getClassName = function () {
  58004. return "GamepadCamera";
  58005. };
  58006. return GamepadCamera;
  58007. }(BABYLON.UniversalCamera));
  58008. BABYLON.GamepadCamera = GamepadCamera;
  58009. })(BABYLON || (BABYLON = {}));
  58010. //# sourceMappingURL=babylon.gamepadCamera.js.map
  58011. var BABYLON;
  58012. (function (BABYLON) {
  58013. var PostProcessRenderPipelineManager = /** @class */ (function () {
  58014. function PostProcessRenderPipelineManager() {
  58015. this._renderPipelines = {};
  58016. }
  58017. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  58018. this._renderPipelines[renderPipeline._name] = renderPipeline;
  58019. };
  58020. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  58021. if (unique === void 0) { unique = false; }
  58022. var renderPipeline = this._renderPipelines[renderPipelineName];
  58023. if (!renderPipeline) {
  58024. return;
  58025. }
  58026. renderPipeline._attachCameras(cameras, unique);
  58027. };
  58028. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  58029. var renderPipeline = this._renderPipelines[renderPipelineName];
  58030. if (!renderPipeline) {
  58031. return;
  58032. }
  58033. renderPipeline._detachCameras(cameras);
  58034. };
  58035. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58036. var renderPipeline = this._renderPipelines[renderPipelineName];
  58037. if (!renderPipeline) {
  58038. return;
  58039. }
  58040. renderPipeline._enableEffect(renderEffectName, cameras);
  58041. };
  58042. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58043. var renderPipeline = this._renderPipelines[renderPipelineName];
  58044. if (!renderPipeline) {
  58045. return;
  58046. }
  58047. renderPipeline._disableEffect(renderEffectName, cameras);
  58048. };
  58049. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  58050. var renderPipeline = this._renderPipelines[renderPipelineName];
  58051. if (!renderPipeline) {
  58052. return;
  58053. }
  58054. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  58055. };
  58056. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  58057. var renderPipeline = this._renderPipelines[renderPipelineName];
  58058. if (!renderPipeline) {
  58059. return;
  58060. }
  58061. renderPipeline._disableDisplayOnlyPass(cameras);
  58062. };
  58063. PostProcessRenderPipelineManager.prototype.update = function () {
  58064. for (var renderPipelineName in this._renderPipelines) {
  58065. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58066. var pipeline = this._renderPipelines[renderPipelineName];
  58067. if (!pipeline.isSupported) {
  58068. pipeline.dispose();
  58069. delete this._renderPipelines[renderPipelineName];
  58070. }
  58071. else {
  58072. pipeline._update();
  58073. }
  58074. }
  58075. }
  58076. };
  58077. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  58078. for (var renderPipelineName in this._renderPipelines) {
  58079. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58080. var pipeline = this._renderPipelines[renderPipelineName];
  58081. pipeline._rebuild();
  58082. }
  58083. }
  58084. };
  58085. PostProcessRenderPipelineManager.prototype.dispose = function () {
  58086. for (var renderPipelineName in this._renderPipelines) {
  58087. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58088. var pipeline = this._renderPipelines[renderPipelineName];
  58089. pipeline.dispose();
  58090. }
  58091. }
  58092. };
  58093. return PostProcessRenderPipelineManager;
  58094. }());
  58095. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  58096. })(BABYLON || (BABYLON = {}));
  58097. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  58098. var BABYLON;
  58099. (function (BABYLON) {
  58100. var PostProcessRenderPass = /** @class */ (function () {
  58101. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  58102. this._refCount = 0;
  58103. this._name = name;
  58104. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  58105. this.setRenderList(renderList);
  58106. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  58107. this._renderTexture.onAfterRenderObservable.add(afterRender);
  58108. this._scene = scene;
  58109. this._renderList = renderList;
  58110. }
  58111. // private
  58112. PostProcessRenderPass.prototype._incRefCount = function () {
  58113. if (this._refCount === 0) {
  58114. this._scene.customRenderTargets.push(this._renderTexture);
  58115. }
  58116. return ++this._refCount;
  58117. };
  58118. PostProcessRenderPass.prototype._decRefCount = function () {
  58119. this._refCount--;
  58120. if (this._refCount <= 0) {
  58121. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  58122. }
  58123. return this._refCount;
  58124. };
  58125. PostProcessRenderPass.prototype._update = function () {
  58126. this.setRenderList(this._renderList);
  58127. };
  58128. // public
  58129. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  58130. this._renderTexture.renderList = renderList;
  58131. };
  58132. PostProcessRenderPass.prototype.getRenderTexture = function () {
  58133. return this._renderTexture;
  58134. };
  58135. return PostProcessRenderPass;
  58136. }());
  58137. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  58138. })(BABYLON || (BABYLON = {}));
  58139. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  58140. var BABYLON;
  58141. (function (BABYLON) {
  58142. var PostProcessRenderEffect = /** @class */ (function () {
  58143. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  58144. this._name = name;
  58145. this._singleInstance = singleInstance || true;
  58146. this._getPostProcess = getPostProcess;
  58147. this._cameras = {};
  58148. this._indicesForCamera = {};
  58149. this._postProcesses = {};
  58150. this._renderPasses = {};
  58151. this._renderEffectAsPasses = {};
  58152. }
  58153. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  58154. get: function () {
  58155. for (var index in this._postProcesses) {
  58156. if (!this._postProcesses[index].isSupported) {
  58157. return false;
  58158. }
  58159. }
  58160. return true;
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. PostProcessRenderEffect.prototype._update = function () {
  58166. for (var renderPassName in this._renderPasses) {
  58167. this._renderPasses[renderPassName]._update();
  58168. }
  58169. };
  58170. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  58171. this._renderPasses[renderPass._name] = renderPass;
  58172. this._linkParameters();
  58173. };
  58174. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  58175. delete this._renderPasses[renderPass._name];
  58176. this._linkParameters();
  58177. };
  58178. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  58179. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  58180. this._linkParameters();
  58181. };
  58182. PostProcessRenderEffect.prototype.getPass = function (passName) {
  58183. for (var renderPassName in this._renderPasses) {
  58184. if (renderPassName === passName) {
  58185. return this._renderPasses[passName];
  58186. }
  58187. }
  58188. return null;
  58189. };
  58190. PostProcessRenderEffect.prototype.emptyPasses = function () {
  58191. this._renderPasses = {};
  58192. this._linkParameters();
  58193. };
  58194. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  58195. var cameraKey;
  58196. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58197. if (!cams) {
  58198. return;
  58199. }
  58200. for (var i = 0; i < cams.length; i++) {
  58201. var camera = cams[i];
  58202. var cameraName = camera.name;
  58203. if (this._singleInstance) {
  58204. cameraKey = 0;
  58205. }
  58206. else {
  58207. cameraKey = cameraName;
  58208. }
  58209. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  58210. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  58211. if (!this._indicesForCamera[cameraName]) {
  58212. this._indicesForCamera[cameraName] = [];
  58213. }
  58214. this._indicesForCamera[cameraName].push(index);
  58215. if (!this._cameras[cameraName]) {
  58216. this._cameras[cameraName] = camera;
  58217. }
  58218. for (var passName in this._renderPasses) {
  58219. this._renderPasses[passName]._incRefCount();
  58220. }
  58221. }
  58222. this._linkParameters();
  58223. };
  58224. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  58225. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58226. if (!cams) {
  58227. return;
  58228. }
  58229. for (var i = 0; i < cams.length; i++) {
  58230. var camera = cams[i];
  58231. var cameraName = camera.name;
  58232. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58233. if (this._cameras[cameraName]) {
  58234. //this._indicesForCamera.splice(index, 1);
  58235. this._cameras[cameraName] = null;
  58236. }
  58237. for (var passName in this._renderPasses) {
  58238. this._renderPasses[passName]._decRefCount();
  58239. }
  58240. }
  58241. };
  58242. PostProcessRenderEffect.prototype._enable = function (cameras) {
  58243. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58244. if (!cams) {
  58245. return;
  58246. }
  58247. for (var i = 0; i < cams.length; i++) {
  58248. var camera = cams[i];
  58249. var cameraName = camera.name;
  58250. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  58251. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  58252. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  58253. }
  58254. }
  58255. for (var passName in this._renderPasses) {
  58256. this._renderPasses[passName]._incRefCount();
  58257. }
  58258. }
  58259. };
  58260. PostProcessRenderEffect.prototype._disable = function (cameras) {
  58261. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58262. if (!cams) {
  58263. return;
  58264. }
  58265. for (var i = 0; i < cams.length; i++) {
  58266. var camera = cams[i];
  58267. var cameraName = camera.Name;
  58268. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58269. for (var passName in this._renderPasses) {
  58270. this._renderPasses[passName]._decRefCount();
  58271. }
  58272. }
  58273. };
  58274. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  58275. if (this._singleInstance) {
  58276. return this._postProcesses[0];
  58277. }
  58278. else {
  58279. if (!camera) {
  58280. return null;
  58281. }
  58282. return this._postProcesses[camera.name];
  58283. }
  58284. };
  58285. PostProcessRenderEffect.prototype._linkParameters = function () {
  58286. var _this = this;
  58287. for (var index in this._postProcesses) {
  58288. if (this.applyParameters) {
  58289. this.applyParameters(this._postProcesses[index]);
  58290. }
  58291. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  58292. _this._linkTextures(effect);
  58293. });
  58294. }
  58295. };
  58296. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  58297. for (var renderPassName in this._renderPasses) {
  58298. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  58299. }
  58300. for (var renderEffectName in this._renderEffectAsPasses) {
  58301. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  58302. }
  58303. };
  58304. return PostProcessRenderEffect;
  58305. }());
  58306. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  58307. })(BABYLON || (BABYLON = {}));
  58308. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  58309. var BABYLON;
  58310. (function (BABYLON) {
  58311. var PostProcessRenderPipeline = /** @class */ (function () {
  58312. function PostProcessRenderPipeline(engine, name) {
  58313. this._engine = engine;
  58314. this._name = name;
  58315. this._renderEffects = {};
  58316. this._renderEffectsForIsolatedPass = new Array();
  58317. this._cameras = [];
  58318. }
  58319. PostProcessRenderPipeline.prototype.getClassName = function () {
  58320. return "PostProcessRenderPipeline";
  58321. };
  58322. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  58323. get: function () {
  58324. for (var renderEffectName in this._renderEffects) {
  58325. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58326. if (!this._renderEffects[renderEffectName].isSupported) {
  58327. return false;
  58328. }
  58329. }
  58330. }
  58331. return true;
  58332. },
  58333. enumerable: true,
  58334. configurable: true
  58335. });
  58336. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  58337. this._renderEffects[renderEffect._name] = renderEffect;
  58338. };
  58339. // private
  58340. PostProcessRenderPipeline.prototype._rebuild = function () {
  58341. };
  58342. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  58343. var renderEffects = this._renderEffects[renderEffectName];
  58344. if (!renderEffects) {
  58345. return;
  58346. }
  58347. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58348. };
  58349. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  58350. var renderEffects = this._renderEffects[renderEffectName];
  58351. if (!renderEffects) {
  58352. return;
  58353. }
  58354. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58355. };
  58356. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  58357. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58358. if (!cams) {
  58359. return;
  58360. }
  58361. var indicesToDelete = [];
  58362. var i;
  58363. for (i = 0; i < cams.length; i++) {
  58364. var camera = cams[i];
  58365. var cameraName = camera.name;
  58366. if (this._cameras.indexOf(camera) === -1) {
  58367. this._cameras[cameraName] = camera;
  58368. }
  58369. else if (unique) {
  58370. indicesToDelete.push(i);
  58371. }
  58372. }
  58373. for (i = 0; i < indicesToDelete.length; i++) {
  58374. cameras.splice(indicesToDelete[i], 1);
  58375. }
  58376. for (var renderEffectName in this._renderEffects) {
  58377. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58378. this._renderEffects[renderEffectName]._attachCameras(cams);
  58379. }
  58380. }
  58381. };
  58382. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  58383. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58384. if (!cams) {
  58385. return;
  58386. }
  58387. for (var renderEffectName in this._renderEffects) {
  58388. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58389. this._renderEffects[renderEffectName]._detachCameras(cams);
  58390. }
  58391. }
  58392. for (var i = 0; i < cams.length; i++) {
  58393. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  58394. }
  58395. };
  58396. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  58397. var _this = this;
  58398. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58399. if (!cams) {
  58400. return;
  58401. }
  58402. var pass = null;
  58403. var renderEffectName;
  58404. for (renderEffectName in this._renderEffects) {
  58405. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58406. pass = this._renderEffects[renderEffectName].getPass(passName);
  58407. if (pass != null) {
  58408. break;
  58409. }
  58410. }
  58411. }
  58412. if (pass === null) {
  58413. return;
  58414. }
  58415. for (renderEffectName in this._renderEffects) {
  58416. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58417. this._renderEffects[renderEffectName]._disable(cams);
  58418. }
  58419. }
  58420. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  58421. for (var i = 0; i < cams.length; i++) {
  58422. var camera = cams[i];
  58423. var cameraName = camera.name;
  58424. 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); });
  58425. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  58426. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  58427. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  58428. }
  58429. };
  58430. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  58431. var _this = this;
  58432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58433. if (!cams) {
  58434. return;
  58435. }
  58436. for (var i = 0; i < cams.length; i++) {
  58437. var camera = cams[i];
  58438. var cameraName = camera.name;
  58439. 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); });
  58440. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  58441. }
  58442. for (var renderEffectName in this._renderEffects) {
  58443. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58444. this._renderEffects[renderEffectName]._enable(cams);
  58445. }
  58446. }
  58447. };
  58448. PostProcessRenderPipeline.prototype._update = function () {
  58449. for (var renderEffectName in this._renderEffects) {
  58450. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58451. this._renderEffects[renderEffectName]._update();
  58452. }
  58453. }
  58454. for (var i = 0; i < this._cameras.length; i++) {
  58455. var cameraName = this._cameras[i].name;
  58456. if (this._renderEffectsForIsolatedPass[cameraName]) {
  58457. this._renderEffectsForIsolatedPass[cameraName]._update();
  58458. }
  58459. }
  58460. };
  58461. PostProcessRenderPipeline.prototype._reset = function () {
  58462. this._renderEffects = {};
  58463. this._renderEffectsForIsolatedPass = new Array();
  58464. };
  58465. PostProcessRenderPipeline.prototype.dispose = function () {
  58466. // Must be implemented by children
  58467. };
  58468. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  58469. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  58470. __decorate([
  58471. BABYLON.serialize()
  58472. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  58473. return PostProcessRenderPipeline;
  58474. }());
  58475. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58476. })(BABYLON || (BABYLON = {}));
  58477. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58478. var BABYLON;
  58479. (function (BABYLON) {
  58480. var DepthRenderer = /** @class */ (function () {
  58481. function DepthRenderer(scene, type) {
  58482. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58483. var _this = this;
  58484. this._scene = scene;
  58485. var engine = scene.getEngine();
  58486. // Render target
  58487. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58488. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58489. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58490. this._depthMap.refreshRate = 1;
  58491. this._depthMap.renderParticles = false;
  58492. this._depthMap.renderList = null;
  58493. // set default depth value to 1.0 (far away)
  58494. this._depthMap.onClearObservable.add(function (engine) {
  58495. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58496. });
  58497. // Custom render function
  58498. var renderSubMesh = function (subMesh) {
  58499. var mesh = subMesh.getRenderingMesh();
  58500. var scene = _this._scene;
  58501. var engine = scene.getEngine();
  58502. var material = subMesh.getMaterial();
  58503. if (!material) {
  58504. return;
  58505. }
  58506. // Culling and reverse (right handed system)
  58507. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58508. // Managing instances
  58509. var batch = mesh._getInstancesRenderList(subMesh._id);
  58510. if (batch.mustReturn) {
  58511. return;
  58512. }
  58513. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58514. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58515. engine.enableEffect(_this._effect);
  58516. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58517. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58518. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58519. // Alpha test
  58520. if (material && material.needAlphaTesting()) {
  58521. var alphaTexture = material.getAlphaTestTexture();
  58522. if (alphaTexture) {
  58523. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58524. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58525. }
  58526. }
  58527. // Bones
  58528. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58529. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58530. }
  58531. // Draw
  58532. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58533. }
  58534. };
  58535. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58536. var index;
  58537. if (depthOnlySubMeshes.length) {
  58538. engine.setColorWrite(false);
  58539. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58540. renderSubMesh(depthOnlySubMeshes.data[index]);
  58541. }
  58542. engine.setColorWrite(true);
  58543. }
  58544. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58545. renderSubMesh(opaqueSubMeshes.data[index]);
  58546. }
  58547. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58548. renderSubMesh(alphaTestSubMeshes.data[index]);
  58549. }
  58550. };
  58551. }
  58552. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58553. var material = subMesh.getMaterial();
  58554. if (material.disableDepthWrite) {
  58555. return false;
  58556. }
  58557. var defines = [];
  58558. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58559. var mesh = subMesh.getMesh();
  58560. // Alpha test
  58561. if (material && material.needAlphaTesting()) {
  58562. defines.push("#define ALPHATEST");
  58563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58564. attribs.push(BABYLON.VertexBuffer.UVKind);
  58565. defines.push("#define UV1");
  58566. }
  58567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58568. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58569. defines.push("#define UV2");
  58570. }
  58571. }
  58572. // Bones
  58573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58576. if (mesh.numBoneInfluencers > 4) {
  58577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58579. }
  58580. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58581. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58582. }
  58583. else {
  58584. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58585. }
  58586. // Instances
  58587. if (useInstances) {
  58588. defines.push("#define INSTANCES");
  58589. attribs.push("world0");
  58590. attribs.push("world1");
  58591. attribs.push("world2");
  58592. attribs.push("world3");
  58593. }
  58594. // Get correct effect
  58595. var join = defines.join("\n");
  58596. if (this._cachedDefines !== join) {
  58597. this._cachedDefines = join;
  58598. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58599. }
  58600. return this._effect.isReady();
  58601. };
  58602. DepthRenderer.prototype.getDepthMap = function () {
  58603. return this._depthMap;
  58604. };
  58605. // Methods
  58606. DepthRenderer.prototype.dispose = function () {
  58607. this._depthMap.dispose();
  58608. };
  58609. return DepthRenderer;
  58610. }());
  58611. BABYLON.DepthRenderer = DepthRenderer;
  58612. })(BABYLON || (BABYLON = {}));
  58613. //# sourceMappingURL=babylon.depthRenderer.js.map
  58614. var BABYLON;
  58615. (function (BABYLON) {
  58616. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58617. __extends(SSAORenderingPipeline, _super);
  58618. /**
  58619. * @constructor
  58620. * @param {string} name - The rendering pipeline name
  58621. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58622. * @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 }
  58623. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58624. */
  58625. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58626. var _this = _super.call(this, scene.getEngine(), name) || this;
  58627. // Members
  58628. /**
  58629. * The PassPostProcess id in the pipeline that contains the original scene color
  58630. * @type {string}
  58631. */
  58632. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58633. /**
  58634. * The SSAO PostProcess id in the pipeline
  58635. * @type {string}
  58636. */
  58637. _this.SSAORenderEffect = "SSAORenderEffect";
  58638. /**
  58639. * The horizontal blur PostProcess id in the pipeline
  58640. * @type {string}
  58641. */
  58642. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58643. /**
  58644. * The vertical blur PostProcess id in the pipeline
  58645. * @type {string}
  58646. */
  58647. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58648. /**
  58649. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58650. * @type {string}
  58651. */
  58652. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58653. /**
  58654. * The output strength of the SSAO post-process. Default value is 1.0.
  58655. * @type {number}
  58656. */
  58657. _this.totalStrength = 1.0;
  58658. /**
  58659. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58660. * @type {number}
  58661. */
  58662. _this.radius = 0.0001;
  58663. /**
  58664. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58665. * Must not be equal to fallOff and superior to fallOff.
  58666. * Default value is 0.975
  58667. * @type {number}
  58668. */
  58669. _this.area = 0.0075;
  58670. /**
  58671. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58672. * Must not be equal to area and inferior to area.
  58673. * Default value is 0.0
  58674. * @type {number}
  58675. */
  58676. _this.fallOff = 0.000001;
  58677. /**
  58678. * The base color of the SSAO post-process
  58679. * The final result is "base + ssao" between [0, 1]
  58680. * @type {number}
  58681. */
  58682. _this.base = 0.5;
  58683. _this._firstUpdate = true;
  58684. _this._scene = scene;
  58685. // Set up assets
  58686. _this._createRandomTexture();
  58687. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58688. var ssaoRatio = ratio.ssaoRatio || ratio;
  58689. var combineRatio = ratio.combineRatio || ratio;
  58690. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58691. _this._createSSAOPostProcess(ssaoRatio);
  58692. _this._createBlurPostProcess(ssaoRatio);
  58693. _this._createSSAOCombinePostProcess(combineRatio);
  58694. // Set up pipeline
  58695. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58696. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58697. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58698. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58699. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58700. // Finish
  58701. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58702. if (cameras)
  58703. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58704. return _this;
  58705. }
  58706. // Public Methods
  58707. /**
  58708. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58709. */
  58710. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58711. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58712. for (var i = 0; i < this._scene.cameras.length; i++) {
  58713. var camera = this._scene.cameras[i];
  58714. this._originalColorPostProcess.dispose(camera);
  58715. this._ssaoPostProcess.dispose(camera);
  58716. this._blurHPostProcess.dispose(camera);
  58717. this._blurVPostProcess.dispose(camera);
  58718. this._ssaoCombinePostProcess.dispose(camera);
  58719. }
  58720. this._randomTexture.dispose();
  58721. if (disableDepthRender)
  58722. this._scene.disableDepthRenderer();
  58723. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58724. _super.prototype.dispose.call(this);
  58725. };
  58726. // Private Methods
  58727. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58728. var _this = this;
  58729. var size = 16;
  58730. 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);
  58731. 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);
  58732. this._blurHPostProcess.onActivateObservable.add(function () {
  58733. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58734. _this._blurHPostProcess.kernel = size * dw;
  58735. });
  58736. this._blurVPostProcess.onActivateObservable.add(function () {
  58737. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58738. _this._blurVPostProcess.kernel = size * dw;
  58739. });
  58740. };
  58741. SSAORenderingPipeline.prototype._rebuild = function () {
  58742. this._firstUpdate = true;
  58743. _super.prototype._rebuild.call(this);
  58744. };
  58745. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58746. var _this = this;
  58747. var numSamples = 16;
  58748. var sampleSphere = [
  58749. 0.5381, 0.1856, -0.4319,
  58750. 0.1379, 0.2486, 0.4430,
  58751. 0.3371, 0.5679, -0.0057,
  58752. -0.6999, -0.0451, -0.0019,
  58753. 0.0689, -0.1598, -0.8547,
  58754. 0.0560, 0.0069, -0.1843,
  58755. -0.0146, 0.1402, 0.0762,
  58756. 0.0100, -0.1924, -0.0344,
  58757. -0.3577, -0.5301, -0.4358,
  58758. -0.3169, 0.1063, 0.0158,
  58759. 0.0103, -0.5869, 0.0046,
  58760. -0.0897, -0.4940, 0.3287,
  58761. 0.7119, -0.0154, -0.0918,
  58762. -0.0533, 0.0596, -0.5411,
  58763. 0.0352, -0.0631, 0.5460,
  58764. -0.4776, 0.2847, -0.0271
  58765. ];
  58766. var samplesFactor = 1.0 / numSamples;
  58767. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58768. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58769. "area", "fallOff", "base", "range", "viewport"
  58770. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58771. this._ssaoPostProcess.onApply = function (effect) {
  58772. if (_this._firstUpdate) {
  58773. effect.setArray3("sampleSphere", sampleSphere);
  58774. effect.setFloat("samplesFactor", samplesFactor);
  58775. effect.setFloat("randTextureTiles", 4.0);
  58776. }
  58777. effect.setFloat("totalStrength", _this.totalStrength);
  58778. effect.setFloat("radius", _this.radius);
  58779. effect.setFloat("area", _this.area);
  58780. effect.setFloat("fallOff", _this.fallOff);
  58781. effect.setFloat("base", _this.base);
  58782. effect.setTexture("textureSampler", _this._depthTexture);
  58783. effect.setTexture("randomSampler", _this._randomTexture);
  58784. };
  58785. };
  58786. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58787. var _this = this;
  58788. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58789. this._ssaoCombinePostProcess.onApply = function (effect) {
  58790. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58791. };
  58792. };
  58793. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58794. var size = 512;
  58795. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58796. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58797. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58798. var context = this._randomTexture.getContext();
  58799. var rand = function (min, max) {
  58800. return Math.random() * (max - min) + min;
  58801. };
  58802. var randVector = BABYLON.Vector3.Zero();
  58803. for (var x = 0; x < size; x++) {
  58804. for (var y = 0; y < size; y++) {
  58805. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58806. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58807. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58808. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58809. context.fillRect(x, y, 1, 1);
  58810. }
  58811. }
  58812. this._randomTexture.update(false);
  58813. };
  58814. __decorate([
  58815. BABYLON.serialize()
  58816. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58817. __decorate([
  58818. BABYLON.serialize()
  58819. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58820. __decorate([
  58821. BABYLON.serialize()
  58822. ], SSAORenderingPipeline.prototype, "area", void 0);
  58823. __decorate([
  58824. BABYLON.serialize()
  58825. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58826. __decorate([
  58827. BABYLON.serialize()
  58828. ], SSAORenderingPipeline.prototype, "base", void 0);
  58829. return SSAORenderingPipeline;
  58830. }(BABYLON.PostProcessRenderPipeline));
  58831. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58832. })(BABYLON || (BABYLON = {}));
  58833. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58834. var BABYLON;
  58835. (function (BABYLON) {
  58836. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58837. __extends(SSAO2RenderingPipeline, _super);
  58838. /**
  58839. * @constructor
  58840. * @param {string} name - The rendering pipeline name
  58841. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58842. * @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 }
  58843. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58844. */
  58845. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58846. var _this = _super.call(this, scene.getEngine(), name) || this;
  58847. // Members
  58848. /**
  58849. * The PassPostProcess id in the pipeline that contains the original scene color
  58850. * @type {string}
  58851. */
  58852. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58853. /**
  58854. * The SSAO PostProcess id in the pipeline
  58855. * @type {string}
  58856. */
  58857. _this.SSAORenderEffect = "SSAORenderEffect";
  58858. /**
  58859. * The horizontal blur PostProcess id in the pipeline
  58860. * @type {string}
  58861. */
  58862. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58863. /**
  58864. * The vertical blur PostProcess id in the pipeline
  58865. * @type {string}
  58866. */
  58867. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58868. /**
  58869. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58870. * @type {string}
  58871. */
  58872. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58873. /**
  58874. * The output strength of the SSAO post-process. Default value is 1.0.
  58875. * @type {number}
  58876. */
  58877. _this.totalStrength = 1.0;
  58878. /**
  58879. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58880. * @type {number}
  58881. */
  58882. _this.maxZ = 100.0;
  58883. /**
  58884. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58885. * @type {number}
  58886. */
  58887. _this.minZAspect = 0.2;
  58888. /**
  58889. * Number of samples used for the SSAO calculations. Default value is 8
  58890. * @type {number}
  58891. */
  58892. _this._samples = 8;
  58893. /**
  58894. * Are we using bilateral blur ?
  58895. * @type {boolean}
  58896. */
  58897. _this._expensiveBlur = true;
  58898. /**
  58899. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58900. * @type {number}
  58901. */
  58902. _this.radius = 2.0;
  58903. /**
  58904. * The base color of the SSAO post-process
  58905. * The final result is "base + ssao" between [0, 1]
  58906. * @type {number}
  58907. */
  58908. _this.base = 0.1;
  58909. _this._firstUpdate = true;
  58910. _this._scene = scene;
  58911. if (!_this.isSupported) {
  58912. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58913. return _this;
  58914. }
  58915. var ssaoRatio = ratio.ssaoRatio || ratio;
  58916. var blurRatio = ratio.blurRatio || ratio;
  58917. // Set up assets
  58918. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58919. _this._createRandomTexture();
  58920. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58921. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58922. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58923. _this._createSSAOPostProcess(1.0);
  58924. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58925. _this._createSSAOCombinePostProcess(blurRatio);
  58926. // Set up pipeline
  58927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58928. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58929. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58930. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58931. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58932. // Finish
  58933. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58934. if (cameras)
  58935. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58936. return _this;
  58937. }
  58938. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58939. get: function () {
  58940. return this._samples;
  58941. },
  58942. set: function (n) {
  58943. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58944. this._samples = n;
  58945. this._sampleSphere = this._generateHemisphere();
  58946. this._firstUpdate = true;
  58947. },
  58948. enumerable: true,
  58949. configurable: true
  58950. });
  58951. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58952. get: function () {
  58953. return this._expensiveBlur;
  58954. },
  58955. set: function (b) {
  58956. 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"]);
  58957. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58958. this._expensiveBlur = b;
  58959. this._firstUpdate = true;
  58960. },
  58961. enumerable: true,
  58962. configurable: true
  58963. });
  58964. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58965. /**
  58966. * Support test.
  58967. * @type {boolean}
  58968. */
  58969. get: function () {
  58970. var engine = BABYLON.Engine.LastCreatedEngine;
  58971. if (!engine) {
  58972. return false;
  58973. }
  58974. return engine.getCaps().drawBuffersExtension;
  58975. },
  58976. enumerable: true,
  58977. configurable: true
  58978. });
  58979. // Public Methods
  58980. /**
  58981. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58982. */
  58983. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58984. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58985. for (var i = 0; i < this._scene.cameras.length; i++) {
  58986. var camera = this._scene.cameras[i];
  58987. this._originalColorPostProcess.dispose(camera);
  58988. this._ssaoPostProcess.dispose(camera);
  58989. this._blurHPostProcess.dispose(camera);
  58990. this._blurVPostProcess.dispose(camera);
  58991. this._ssaoCombinePostProcess.dispose(camera);
  58992. }
  58993. this._randomTexture.dispose();
  58994. if (disableGeometryBufferRenderer)
  58995. this._scene.disableGeometryBufferRenderer();
  58996. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58997. _super.prototype.dispose.call(this);
  58998. };
  58999. // Private Methods
  59000. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  59001. var _this = this;
  59002. this._samplerOffsets = [];
  59003. var expensive = this.expensiveBlur;
  59004. for (var i = -8; i < 8; i++) {
  59005. this._samplerOffsets.push(i * 2 + 0.5);
  59006. }
  59007. 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");
  59008. this._blurHPostProcess.onApply = function (effect) {
  59009. if (!_this._scene.activeCamera) {
  59010. return;
  59011. }
  59012. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  59013. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59014. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59015. effect.setFloat("radius", _this.radius);
  59016. effect.setTexture("depthSampler", _this._depthTexture);
  59017. if (_this._firstUpdate) {
  59018. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59019. }
  59020. };
  59021. 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");
  59022. this._blurVPostProcess.onApply = function (effect) {
  59023. if (!_this._scene.activeCamera) {
  59024. return;
  59025. }
  59026. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  59027. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59028. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59029. effect.setFloat("radius", _this.radius);
  59030. effect.setTexture("depthSampler", _this._depthTexture);
  59031. if (_this._firstUpdate) {
  59032. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59033. _this._firstUpdate = false;
  59034. }
  59035. };
  59036. };
  59037. SSAO2RenderingPipeline.prototype._rebuild = function () {
  59038. this._firstUpdate = true;
  59039. _super.prototype._rebuild.call(this);
  59040. };
  59041. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  59042. var numSamples = this.samples;
  59043. var result = [];
  59044. var vector, scale;
  59045. var rand = function (min, max) {
  59046. return Math.random() * (max - min) + min;
  59047. };
  59048. var i = 0;
  59049. while (i < numSamples) {
  59050. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  59051. vector.normalize();
  59052. scale = i / numSamples;
  59053. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  59054. vector.scaleInPlace(scale);
  59055. result.push(vector.x, vector.y, vector.z);
  59056. i++;
  59057. }
  59058. return result;
  59059. };
  59060. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59061. var _this = this;
  59062. var numSamples = this.samples;
  59063. this._sampleSphere = this._generateHemisphere();
  59064. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  59065. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59066. "base", "range", "projection", "near", "far", "texelSize",
  59067. "xViewport", "yViewport", "maxZ", "minZAspect"
  59068. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59069. this._ssaoPostProcess.onApply = function (effect) {
  59070. if (_this._firstUpdate) {
  59071. effect.setArray3("sampleSphere", _this._sampleSphere);
  59072. effect.setFloat("randTextureTiles", 4.0);
  59073. }
  59074. if (!_this._scene.activeCamera) {
  59075. return;
  59076. }
  59077. effect.setFloat("samplesFactor", 1 / _this.samples);
  59078. effect.setFloat("totalStrength", _this.totalStrength);
  59079. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  59080. effect.setFloat("radius", _this.radius);
  59081. effect.setFloat("maxZ", _this.maxZ);
  59082. effect.setFloat("minZAspect", _this.minZAspect);
  59083. effect.setFloat("base", _this.base);
  59084. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59085. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59086. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  59087. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  59088. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  59089. effect.setTexture("textureSampler", _this._depthTexture);
  59090. effect.setTexture("normalSampler", _this._normalTexture);
  59091. effect.setTexture("randomSampler", _this._randomTexture);
  59092. };
  59093. };
  59094. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59095. var _this = this;
  59096. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59097. this._ssaoCombinePostProcess.onApply = function (effect) {
  59098. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59099. };
  59100. };
  59101. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  59102. var size = 512;
  59103. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59104. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59105. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59106. var context = this._randomTexture.getContext();
  59107. var rand = function (min, max) {
  59108. return Math.random() * (max - min) + min;
  59109. };
  59110. var randVector = BABYLON.Vector3.Zero();
  59111. for (var x = 0; x < size; x++) {
  59112. for (var y = 0; y < size; y++) {
  59113. randVector.x = rand(0.0, 1.0);
  59114. randVector.y = rand(0.0, 1.0);
  59115. randVector.z = 0.0;
  59116. randVector.normalize();
  59117. randVector.scaleInPlace(255);
  59118. randVector.x = Math.floor(randVector.x);
  59119. randVector.y = Math.floor(randVector.y);
  59120. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59121. context.fillRect(x, y, 1, 1);
  59122. }
  59123. }
  59124. this._randomTexture.update(false);
  59125. };
  59126. __decorate([
  59127. BABYLON.serialize()
  59128. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  59129. __decorate([
  59130. BABYLON.serialize()
  59131. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  59132. __decorate([
  59133. BABYLON.serialize()
  59134. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  59135. __decorate([
  59136. BABYLON.serialize("samples")
  59137. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  59138. __decorate([
  59139. BABYLON.serialize("expensiveBlur")
  59140. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  59141. __decorate([
  59142. BABYLON.serialize()
  59143. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  59144. __decorate([
  59145. BABYLON.serialize()
  59146. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  59147. return SSAO2RenderingPipeline;
  59148. }(BABYLON.PostProcessRenderPipeline));
  59149. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  59150. })(BABYLON || (BABYLON = {}));
  59151. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  59152. // BABYLON.JS Chromatic Aberration GLSL Shader
  59153. // Author: Olivier Guyot
  59154. // Separates very slightly R, G and B colors on the edges of the screen
  59155. // Inspired by Francois Tarlier & Martins Upitis
  59156. var BABYLON;
  59157. (function (BABYLON) {
  59158. var LensRenderingPipeline = /** @class */ (function (_super) {
  59159. __extends(LensRenderingPipeline, _super);
  59160. /**
  59161. * @constructor
  59162. *
  59163. * Effect parameters are as follow:
  59164. * {
  59165. * chromatic_aberration: number; // from 0 to x (1 for realism)
  59166. * edge_blur: number; // from 0 to x (1 for realism)
  59167. * distortion: number; // from 0 to x (1 for realism)
  59168. * grain_amount: number; // from 0 to 1
  59169. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  59170. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  59171. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  59172. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  59173. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  59174. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  59175. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  59176. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  59177. * }
  59178. * Note: if an effect parameter is unset, effect is disabled
  59179. *
  59180. * @param {string} name - The rendering pipeline name
  59181. * @param {object} parameters - An object containing all parameters (see above)
  59182. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59183. * @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)
  59184. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59185. */
  59186. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  59187. if (ratio === void 0) { ratio = 1.0; }
  59188. var _this = _super.call(this, scene.getEngine(), name) || this;
  59189. // Lens effects can be of the following:
  59190. // - chromatic aberration (slight shift of RGB colors)
  59191. // - blur on the edge of the lens
  59192. // - lens distortion
  59193. // - depth-of-field blur & highlights enhancing
  59194. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  59195. // - grain effect (noise or custom texture)
  59196. // Two additional texture samplers are needed:
  59197. // - depth map (for depth-of-field)
  59198. // - grain texture
  59199. /**
  59200. * The chromatic aberration PostProcess id in the pipeline
  59201. * @type {string}
  59202. */
  59203. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  59204. /**
  59205. * The highlights enhancing PostProcess id in the pipeline
  59206. * @type {string}
  59207. */
  59208. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  59209. /**
  59210. * The depth-of-field PostProcess id in the pipeline
  59211. * @type {string}
  59212. */
  59213. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  59214. _this._scene = scene;
  59215. // Fetch texture samplers
  59216. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59217. if (parameters.grain_texture) {
  59218. _this._grainTexture = parameters.grain_texture;
  59219. }
  59220. else {
  59221. _this._createGrainTexture();
  59222. }
  59223. // save parameters
  59224. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  59225. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  59226. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  59227. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  59228. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  59229. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  59230. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  59231. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  59232. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  59233. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  59234. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  59235. // Create effects
  59236. _this._createChromaticAberrationPostProcess(ratio);
  59237. _this._createHighlightsPostProcess(ratio);
  59238. _this._createDepthOfFieldPostProcess(ratio / 4);
  59239. // Set up pipeline
  59240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  59241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  59242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  59243. if (_this._highlightsGain === -1) {
  59244. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  59245. }
  59246. // Finish
  59247. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59248. if (cameras) {
  59249. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59250. }
  59251. return _this;
  59252. }
  59253. // public methods (self explanatory)
  59254. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  59255. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  59256. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  59257. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  59258. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  59259. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  59260. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  59261. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  59262. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  59263. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  59264. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  59265. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  59266. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  59267. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  59268. };
  59269. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  59270. this._highlightsPostProcess.updateEffect();
  59271. };
  59272. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  59273. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  59274. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  59275. this._highlightsGain = amount;
  59276. };
  59277. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  59278. if (this._highlightsGain === -1) {
  59279. this._highlightsGain = 1.0;
  59280. }
  59281. this._highlightsThreshold = amount;
  59282. };
  59283. LensRenderingPipeline.prototype.disableHighlights = function () {
  59284. this._highlightsGain = -1;
  59285. };
  59286. /**
  59287. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  59288. */
  59289. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59290. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59291. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59292. this._chromaticAberrationPostProcess = null;
  59293. this._highlightsPostProcess = null;
  59294. this._depthOfFieldPostProcess = null;
  59295. this._grainTexture.dispose();
  59296. if (disableDepthRender)
  59297. this._scene.disableDepthRenderer();
  59298. };
  59299. // colors shifting and distortion
  59300. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  59301. var _this = this;
  59302. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  59303. [], // samplers
  59304. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59305. this._chromaticAberrationPostProcess.onApply = function (effect) {
  59306. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  59307. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59308. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59309. };
  59310. };
  59311. // highlights enhancing
  59312. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  59313. var _this = this;
  59314. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  59315. [], // samplers
  59316. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  59317. this._highlightsPostProcess.onApply = function (effect) {
  59318. effect.setFloat('gain', _this._highlightsGain);
  59319. effect.setFloat('threshold', _this._highlightsThreshold);
  59320. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  59321. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59322. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59323. };
  59324. };
  59325. // colors shifting and distortion
  59326. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  59327. var _this = this;
  59328. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  59329. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  59330. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  59331. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59332. this._depthOfFieldPostProcess.onApply = function (effect) {
  59333. effect.setTexture("depthSampler", _this._depthTexture);
  59334. effect.setTexture("grainSampler", _this._grainTexture);
  59335. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  59336. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  59337. effect.setFloat('grain_amount', _this._grainAmount);
  59338. effect.setBool('blur_noise', _this._blurNoise);
  59339. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59340. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59341. effect.setFloat('distortion', _this._distortion);
  59342. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  59343. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  59344. effect.setFloat('aperture', _this._dofAperture);
  59345. effect.setFloat('darken', _this._dofDarken);
  59346. effect.setFloat('edge_blur', _this._edgeBlur);
  59347. effect.setBool('highlights', (_this._highlightsGain !== -1));
  59348. if (_this._scene.activeCamera) {
  59349. effect.setFloat('near', _this._scene.activeCamera.minZ);
  59350. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  59351. }
  59352. };
  59353. };
  59354. // creates a black and white random noise texture, 512x512
  59355. LensRenderingPipeline.prototype._createGrainTexture = function () {
  59356. var size = 512;
  59357. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59358. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59359. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59360. var context = this._grainTexture.getContext();
  59361. var rand = function (min, max) {
  59362. return Math.random() * (max - min) + min;
  59363. };
  59364. var value;
  59365. for (var x = 0; x < size; x++) {
  59366. for (var y = 0; y < size; y++) {
  59367. value = Math.floor(rand(0.42, 0.58) * 255);
  59368. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  59369. context.fillRect(x, y, 1, 1);
  59370. }
  59371. }
  59372. this._grainTexture.update(false);
  59373. };
  59374. return LensRenderingPipeline;
  59375. }(BABYLON.PostProcessRenderPipeline));
  59376. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  59377. })(BABYLON || (BABYLON = {}));
  59378. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  59379. var BABYLON;
  59380. (function (BABYLON) {
  59381. var StandardRenderingPipeline = /** @class */ (function (_super) {
  59382. __extends(StandardRenderingPipeline, _super);
  59383. /**
  59384. * @constructor
  59385. * @param {string} name - The rendering pipeline name
  59386. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59387. * @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)
  59388. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59389. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59390. */
  59391. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59392. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59393. var _this = _super.call(this, scene.getEngine(), name) || this;
  59394. _this.downSampleX4PostProcess = null;
  59395. _this.brightPassPostProcess = null;
  59396. _this.blurHPostProcesses = [];
  59397. _this.blurVPostProcesses = [];
  59398. _this.textureAdderPostProcess = null;
  59399. _this.volumetricLightPostProcess = null;
  59400. _this.volumetricLightSmoothXPostProcess = null;
  59401. _this.volumetricLightSmoothYPostProcess = null;
  59402. _this.volumetricLightMergePostProces = null;
  59403. _this.volumetricLightFinalPostProcess = null;
  59404. _this.luminancePostProcess = null;
  59405. _this.luminanceDownSamplePostProcesses = [];
  59406. _this.hdrPostProcess = null;
  59407. _this.textureAdderFinalPostProcess = null;
  59408. _this.lensFlareFinalPostProcess = null;
  59409. _this.hdrFinalPostProcess = null;
  59410. _this.lensFlarePostProcess = null;
  59411. _this.lensFlareComposePostProcess = null;
  59412. _this.motionBlurPostProcess = null;
  59413. _this.depthOfFieldPostProcess = null;
  59414. // Values
  59415. _this.brightThreshold = 1.0;
  59416. _this.blurWidth = 512.0;
  59417. _this.horizontalBlur = false;
  59418. _this.exposure = 1.0;
  59419. _this.lensTexture = null;
  59420. _this.volumetricLightCoefficient = 0.2;
  59421. _this.volumetricLightPower = 4.0;
  59422. _this.volumetricLightBlurScale = 64.0;
  59423. _this.sourceLight = null;
  59424. _this.hdrMinimumLuminance = 1.0;
  59425. _this.hdrDecreaseRate = 0.5;
  59426. _this.hdrIncreaseRate = 0.5;
  59427. _this.lensColorTexture = null;
  59428. _this.lensFlareStrength = 20.0;
  59429. _this.lensFlareGhostDispersal = 1.4;
  59430. _this.lensFlareHaloWidth = 0.7;
  59431. _this.lensFlareDistortionStrength = 16.0;
  59432. _this.lensStarTexture = null;
  59433. _this.lensFlareDirtTexture = null;
  59434. _this.depthOfFieldDistance = 10.0;
  59435. _this.depthOfFieldBlurWidth = 64.0;
  59436. _this.motionStrength = 1.0;
  59437. // IAnimatable
  59438. _this.animations = [];
  59439. _this._currentDepthOfFieldSource = null;
  59440. _this._hdrCurrentLuminance = 1.0;
  59441. // Getters and setters
  59442. _this._bloomEnabled = true;
  59443. _this._depthOfFieldEnabled = false;
  59444. _this._vlsEnabled = false;
  59445. _this._lensFlareEnabled = false;
  59446. _this._hdrEnabled = false;
  59447. _this._motionBlurEnabled = false;
  59448. _this._motionBlurSamples = 64.0;
  59449. _this._volumetricLightStepsCount = 50.0;
  59450. _this._cameras = cameras || [];
  59451. // Initialize
  59452. _this._scene = scene;
  59453. _this._basePostProcess = originalPostProcess;
  59454. _this._ratio = ratio;
  59455. // Misc
  59456. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59457. // Finish
  59458. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59459. _this._buildPipeline();
  59460. return _this;
  59461. }
  59462. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  59463. get: function () {
  59464. return this._bloomEnabled;
  59465. },
  59466. set: function (enabled) {
  59467. if (this._bloomEnabled === enabled) {
  59468. return;
  59469. }
  59470. this._bloomEnabled = enabled;
  59471. this._buildPipeline();
  59472. },
  59473. enumerable: true,
  59474. configurable: true
  59475. });
  59476. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59477. get: function () {
  59478. return this._depthOfFieldEnabled;
  59479. },
  59480. set: function (enabled) {
  59481. if (this._depthOfFieldEnabled === enabled) {
  59482. return;
  59483. }
  59484. this._depthOfFieldEnabled = enabled;
  59485. this._buildPipeline();
  59486. },
  59487. enumerable: true,
  59488. configurable: true
  59489. });
  59490. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59491. get: function () {
  59492. return this._lensFlareEnabled;
  59493. },
  59494. set: function (enabled) {
  59495. if (this._lensFlareEnabled === enabled) {
  59496. return;
  59497. }
  59498. this._lensFlareEnabled = enabled;
  59499. this._buildPipeline();
  59500. },
  59501. enumerable: true,
  59502. configurable: true
  59503. });
  59504. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59505. get: function () {
  59506. return this._hdrEnabled;
  59507. },
  59508. set: function (enabled) {
  59509. if (this._hdrEnabled === enabled) {
  59510. return;
  59511. }
  59512. this._hdrEnabled = enabled;
  59513. this._buildPipeline();
  59514. },
  59515. enumerable: true,
  59516. configurable: true
  59517. });
  59518. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59519. get: function () {
  59520. return this._vlsEnabled;
  59521. },
  59522. set: function (enabled) {
  59523. if (this._vlsEnabled === enabled) {
  59524. return;
  59525. }
  59526. if (enabled) {
  59527. var geometry = this._scene.enableGeometryBufferRenderer();
  59528. if (!geometry) {
  59529. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59530. return;
  59531. }
  59532. }
  59533. this._vlsEnabled = enabled;
  59534. this._buildPipeline();
  59535. },
  59536. enumerable: true,
  59537. configurable: true
  59538. });
  59539. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59540. get: function () {
  59541. return this._motionBlurEnabled;
  59542. },
  59543. set: function (enabled) {
  59544. if (this._motionBlurEnabled === enabled) {
  59545. return;
  59546. }
  59547. this._motionBlurEnabled = enabled;
  59548. this._buildPipeline();
  59549. },
  59550. enumerable: true,
  59551. configurable: true
  59552. });
  59553. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59554. get: function () {
  59555. return this._volumetricLightStepsCount;
  59556. },
  59557. set: function (count) {
  59558. if (this.volumetricLightPostProcess) {
  59559. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59560. }
  59561. this._volumetricLightStepsCount = count;
  59562. },
  59563. enumerable: true,
  59564. configurable: true
  59565. });
  59566. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59567. get: function () {
  59568. return this._motionBlurSamples;
  59569. },
  59570. set: function (samples) {
  59571. if (this.motionBlurPostProcess) {
  59572. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59573. }
  59574. this._motionBlurSamples = samples;
  59575. },
  59576. enumerable: true,
  59577. configurable: true
  59578. });
  59579. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59580. var _this = this;
  59581. var ratio = this._ratio;
  59582. var scene = this._scene;
  59583. this._disposePostProcesses();
  59584. this._reset();
  59585. // Create pass post-process
  59586. if (!this._basePostProcess) {
  59587. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59588. this.originalPostProcess.onApply = function (effect) {
  59589. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59590. };
  59591. }
  59592. else {
  59593. this.originalPostProcess = this._basePostProcess;
  59594. }
  59595. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59596. this._currentDepthOfFieldSource = this.originalPostProcess;
  59597. if (this._vlsEnabled) {
  59598. // Create volumetric light
  59599. this._createVolumetricLightPostProcess(scene, ratio);
  59600. // Create volumetric light final post-process
  59601. 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);
  59602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59603. }
  59604. if (this._bloomEnabled) {
  59605. // Create down sample X4 post-process
  59606. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59607. // Create bright pass post-process
  59608. this._createBrightPassPostProcess(scene, ratio / 2);
  59609. // Create gaussian blur post-processes (down sampling blurs)
  59610. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59611. // Create texture adder post-process
  59612. this._createTextureAdderPostProcess(scene, ratio);
  59613. // Create depth-of-field source post-process
  59614. 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);
  59615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59616. }
  59617. if (this._lensFlareEnabled) {
  59618. // Create lens flare post-process
  59619. this._createLensFlarePostProcess(scene, ratio);
  59620. // Create depth-of-field source post-process post lens-flare and disable it now
  59621. 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);
  59622. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59623. }
  59624. if (this._hdrEnabled) {
  59625. // Create luminance
  59626. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59627. // Create HDR
  59628. this._createHdrPostProcess(scene, ratio);
  59629. // Create depth-of-field source post-process post hdr and disable it now
  59630. 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);
  59631. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59632. }
  59633. if (this._depthOfFieldEnabled) {
  59634. // Create gaussian blur used by depth-of-field
  59635. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59636. // Create depth-of-field post-process
  59637. this._createDepthOfFieldPostProcess(scene, ratio);
  59638. }
  59639. if (this._motionBlurEnabled) {
  59640. // Create motion blur post-process
  59641. this._createMotionBlurPostProcess(scene, ratio);
  59642. }
  59643. if (this._cameras !== null) {
  59644. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59645. }
  59646. };
  59647. // Down Sample X4 Post-Processs
  59648. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59649. var _this = this;
  59650. var downSampleX4Offsets = new Array(32);
  59651. 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);
  59652. this.downSampleX4PostProcess.onApply = function (effect) {
  59653. var id = 0;
  59654. var width = _this.downSampleX4PostProcess.width;
  59655. var height = _this.downSampleX4PostProcess.height;
  59656. for (var i = -2; i < 2; i++) {
  59657. for (var j = -2; j < 2; j++) {
  59658. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59659. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59660. id += 2;
  59661. }
  59662. }
  59663. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59664. };
  59665. // Add to pipeline
  59666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59667. };
  59668. // Brightpass Post-Process
  59669. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59670. var _this = this;
  59671. var brightOffsets = new Array(8);
  59672. 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);
  59673. this.brightPassPostProcess.onApply = function (effect) {
  59674. var sU = (1.0 / _this.brightPassPostProcess.width);
  59675. var sV = (1.0 / _this.brightPassPostProcess.height);
  59676. brightOffsets[0] = -0.5 * sU;
  59677. brightOffsets[1] = 0.5 * sV;
  59678. brightOffsets[2] = 0.5 * sU;
  59679. brightOffsets[3] = 0.5 * sV;
  59680. brightOffsets[4] = -0.5 * sU;
  59681. brightOffsets[5] = -0.5 * sV;
  59682. brightOffsets[6] = 0.5 * sU;
  59683. brightOffsets[7] = -0.5 * sV;
  59684. effect.setArray2("dsOffsets", brightOffsets);
  59685. effect.setFloat("brightThreshold", _this.brightThreshold);
  59686. };
  59687. // Add to pipeline
  59688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59689. };
  59690. // Create blur H&V post-processes
  59691. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59692. var _this = this;
  59693. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59694. var engine = scene.getEngine();
  59695. 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);
  59696. 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);
  59697. blurX.onActivateObservable.add(function () {
  59698. var dw = blurX.width / engine.getRenderWidth();
  59699. blurX.kernel = _this[blurWidthKey] * dw;
  59700. });
  59701. blurY.onActivateObservable.add(function () {
  59702. var dw = blurY.height / engine.getRenderHeight();
  59703. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59704. });
  59705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59707. this.blurHPostProcesses.push(blurX);
  59708. this.blurVPostProcesses.push(blurY);
  59709. };
  59710. // Create texture adder post-process
  59711. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59712. var _this = this;
  59713. 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);
  59714. this.textureAdderPostProcess.onApply = function (effect) {
  59715. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59716. effect.setTexture("lensSampler", _this.lensTexture);
  59717. effect.setFloat("exposure", _this.exposure);
  59718. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59719. };
  59720. // Add to pipeline
  59721. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59722. };
  59723. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59724. var _this = this;
  59725. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59726. geometryRenderer.enablePosition = true;
  59727. var geometry = geometryRenderer.getGBuffer();
  59728. // Base post-process
  59729. 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));
  59730. var depthValues = BABYLON.Vector2.Zero();
  59731. this.volumetricLightPostProcess.onApply = function (effect) {
  59732. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59733. var generator = _this.sourceLight.getShadowGenerator();
  59734. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59735. effect.setTexture("positionSampler", geometry.textures[2]);
  59736. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59737. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59738. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59739. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59740. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59741. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59742. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59743. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59744. effect.setVector2("depthValues", depthValues);
  59745. }
  59746. };
  59747. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59748. // Smooth
  59749. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59750. // Merge
  59751. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59752. this.volumetricLightMergePostProces.onApply = function (effect) {
  59753. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59754. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59755. };
  59756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59757. };
  59758. // Create luminance
  59759. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59760. var _this = this;
  59761. // Create luminance
  59762. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59763. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59764. var offsets = [];
  59765. this.luminancePostProcess.onApply = function (effect) {
  59766. var sU = (1.0 / _this.luminancePostProcess.width);
  59767. var sV = (1.0 / _this.luminancePostProcess.height);
  59768. offsets[0] = -0.5 * sU;
  59769. offsets[1] = 0.5 * sV;
  59770. offsets[2] = 0.5 * sU;
  59771. offsets[3] = 0.5 * sV;
  59772. offsets[4] = -0.5 * sU;
  59773. offsets[5] = -0.5 * sV;
  59774. offsets[6] = 0.5 * sU;
  59775. offsets[7] = -0.5 * sV;
  59776. effect.setArray2("lumOffsets", offsets);
  59777. };
  59778. // Add to pipeline
  59779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59780. // Create down sample luminance
  59781. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59782. var size = Math.pow(3, i);
  59783. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59784. if (i === 0) {
  59785. defines += "#define FINAL_DOWN_SAMPLER";
  59786. }
  59787. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59788. this.luminanceDownSamplePostProcesses.push(postProcess);
  59789. }
  59790. // Create callbacks and add effects
  59791. var lastLuminance = this.luminancePostProcess;
  59792. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59793. var downSampleOffsets = new Array(18);
  59794. pp.onApply = function (effect) {
  59795. if (!lastLuminance) {
  59796. return;
  59797. }
  59798. var id = 0;
  59799. for (var x = -1; x < 2; x++) {
  59800. for (var y = -1; y < 2; y++) {
  59801. downSampleOffsets[id] = x / lastLuminance.width;
  59802. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59803. id += 2;
  59804. }
  59805. }
  59806. effect.setArray2("dsOffsets", downSampleOffsets);
  59807. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59808. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59809. lastLuminance = _this.luminancePostProcess;
  59810. }
  59811. else {
  59812. lastLuminance = pp;
  59813. }
  59814. };
  59815. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59816. pp.onAfterRender = function (effect) {
  59817. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59818. 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);
  59819. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59820. };
  59821. }
  59822. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59823. });
  59824. };
  59825. // Create HDR post-process
  59826. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59827. var _this = this;
  59828. 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);
  59829. var outputLiminance = 1;
  59830. var time = 0;
  59831. var lastTime = 0;
  59832. this.hdrPostProcess.onApply = function (effect) {
  59833. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59834. time += scene.getEngine().getDeltaTime();
  59835. if (outputLiminance < 0) {
  59836. outputLiminance = _this._hdrCurrentLuminance;
  59837. }
  59838. else {
  59839. var dt = (lastTime - time) / 1000.0;
  59840. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59841. outputLiminance += _this.hdrDecreaseRate * dt;
  59842. }
  59843. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59844. outputLiminance -= _this.hdrIncreaseRate * dt;
  59845. }
  59846. else {
  59847. outputLiminance = _this._hdrCurrentLuminance;
  59848. }
  59849. }
  59850. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59851. effect.setFloat("averageLuminance", outputLiminance);
  59852. lastTime = time;
  59853. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59854. };
  59855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59856. };
  59857. // Create lens flare post-process
  59858. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59859. var _this = this;
  59860. 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);
  59861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59862. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59863. 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);
  59864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59865. var resolution = new BABYLON.Vector2(0, 0);
  59866. // Lens flare
  59867. this.lensFlarePostProcess.onApply = function (effect) {
  59868. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59869. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59870. effect.setFloat("strength", _this.lensFlareStrength);
  59871. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59872. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59873. // Shift
  59874. resolution.x = _this.lensFlarePostProcess.width;
  59875. resolution.y = _this.lensFlarePostProcess.height;
  59876. effect.setVector2("resolution", resolution);
  59877. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59878. };
  59879. // Compose
  59880. 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);
  59881. 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);
  59882. this.lensFlareComposePostProcess.onApply = function (effect) {
  59883. if (!_this._scene.activeCamera) {
  59884. return;
  59885. }
  59886. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59887. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59888. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59889. // Lens start rotation matrix
  59890. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59891. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59892. 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));
  59893. camRot *= 4.0;
  59894. 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);
  59895. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59896. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59897. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59898. };
  59899. };
  59900. // Create depth-of-field post-process
  59901. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59902. var _this = this;
  59903. 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);
  59904. this.depthOfFieldPostProcess.onApply = function (effect) {
  59905. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59906. effect.setTexture("depthSampler", _this._getDepthTexture());
  59907. effect.setFloat("distance", _this.depthOfFieldDistance);
  59908. };
  59909. // Add to pipeline
  59910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59911. };
  59912. // Create motion blur post-process
  59913. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59914. var _this = this;
  59915. 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);
  59916. var motionScale = 0;
  59917. var prevViewProjection = BABYLON.Matrix.Identity();
  59918. var invViewProjection = BABYLON.Matrix.Identity();
  59919. var viewProjection = BABYLON.Matrix.Identity();
  59920. var screenSize = BABYLON.Vector2.Zero();
  59921. this.motionBlurPostProcess.onApply = function (effect) {
  59922. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59923. viewProjection.invertToRef(invViewProjection);
  59924. effect.setMatrix("inverseViewProjection", invViewProjection);
  59925. effect.setMatrix("prevViewProjection", prevViewProjection);
  59926. prevViewProjection = viewProjection;
  59927. screenSize.x = _this.motionBlurPostProcess.width;
  59928. screenSize.y = _this.motionBlurPostProcess.height;
  59929. effect.setVector2("screenSize", screenSize);
  59930. motionScale = scene.getEngine().getFps() / 60.0;
  59931. effect.setFloat("motionScale", motionScale);
  59932. effect.setFloat("motionStrength", _this.motionStrength);
  59933. effect.setTexture("depthSampler", _this._getDepthTexture());
  59934. };
  59935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59936. };
  59937. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59938. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59939. var renderer = this._scene.enableGeometryBufferRenderer();
  59940. return renderer.getGBuffer().textures[0];
  59941. }
  59942. return this._scene.enableDepthRenderer().getDepthMap();
  59943. };
  59944. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59945. for (var i = 0; i < this._cameras.length; i++) {
  59946. var camera = this._cameras[i];
  59947. if (this.originalPostProcess) {
  59948. this.originalPostProcess.dispose(camera);
  59949. }
  59950. if (this.downSampleX4PostProcess) {
  59951. this.downSampleX4PostProcess.dispose(camera);
  59952. }
  59953. if (this.brightPassPostProcess) {
  59954. this.brightPassPostProcess.dispose(camera);
  59955. }
  59956. if (this.textureAdderPostProcess) {
  59957. this.textureAdderPostProcess.dispose(camera);
  59958. }
  59959. if (this.textureAdderFinalPostProcess) {
  59960. this.textureAdderFinalPostProcess.dispose(camera);
  59961. }
  59962. if (this.volumetricLightPostProcess) {
  59963. this.volumetricLightPostProcess.dispose(camera);
  59964. }
  59965. if (this.volumetricLightSmoothXPostProcess) {
  59966. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59967. }
  59968. if (this.volumetricLightSmoothYPostProcess) {
  59969. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59970. }
  59971. if (this.volumetricLightMergePostProces) {
  59972. this.volumetricLightMergePostProces.dispose(camera);
  59973. }
  59974. if (this.volumetricLightFinalPostProcess) {
  59975. this.volumetricLightFinalPostProcess.dispose(camera);
  59976. }
  59977. if (this.lensFlarePostProcess) {
  59978. this.lensFlarePostProcess.dispose(camera);
  59979. }
  59980. if (this.lensFlareComposePostProcess) {
  59981. this.lensFlareComposePostProcess.dispose(camera);
  59982. }
  59983. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59984. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59985. }
  59986. if (this.luminancePostProcess) {
  59987. this.luminancePostProcess.dispose(camera);
  59988. }
  59989. if (this.hdrPostProcess) {
  59990. this.hdrPostProcess.dispose(camera);
  59991. }
  59992. if (this.hdrFinalPostProcess) {
  59993. this.hdrFinalPostProcess.dispose(camera);
  59994. }
  59995. if (this.depthOfFieldPostProcess) {
  59996. this.depthOfFieldPostProcess.dispose(camera);
  59997. }
  59998. if (this.motionBlurPostProcess) {
  59999. this.motionBlurPostProcess.dispose(camera);
  60000. }
  60001. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  60002. this.blurHPostProcesses[j].dispose(camera);
  60003. }
  60004. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  60005. this.blurVPostProcesses[j].dispose(camera);
  60006. }
  60007. }
  60008. this.originalPostProcess = null;
  60009. this.downSampleX4PostProcess = null;
  60010. this.brightPassPostProcess = null;
  60011. this.textureAdderPostProcess = null;
  60012. this.textureAdderFinalPostProcess = null;
  60013. this.volumetricLightPostProcess = null;
  60014. this.volumetricLightSmoothXPostProcess = null;
  60015. this.volumetricLightSmoothYPostProcess = null;
  60016. this.volumetricLightMergePostProces = null;
  60017. this.volumetricLightFinalPostProcess = null;
  60018. this.lensFlarePostProcess = null;
  60019. this.lensFlareComposePostProcess = null;
  60020. this.luminancePostProcess = null;
  60021. this.hdrPostProcess = null;
  60022. this.hdrFinalPostProcess = null;
  60023. this.depthOfFieldPostProcess = null;
  60024. this.motionBlurPostProcess = null;
  60025. this.luminanceDownSamplePostProcesses = [];
  60026. this.blurHPostProcesses = [];
  60027. this.blurVPostProcesses = [];
  60028. };
  60029. // Dispose
  60030. StandardRenderingPipeline.prototype.dispose = function () {
  60031. this._disposePostProcesses();
  60032. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60033. _super.prototype.dispose.call(this);
  60034. };
  60035. // Serialize rendering pipeline
  60036. StandardRenderingPipeline.prototype.serialize = function () {
  60037. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60038. serializationObject.customType = "StandardRenderingPipeline";
  60039. return serializationObject;
  60040. };
  60041. /**
  60042. * Static members
  60043. */
  60044. // Parse serialized pipeline
  60045. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60046. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60047. };
  60048. // Luminance steps
  60049. StandardRenderingPipeline.LuminanceSteps = 6;
  60050. __decorate([
  60051. BABYLON.serialize()
  60052. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60053. __decorate([
  60054. BABYLON.serialize()
  60055. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60056. __decorate([
  60057. BABYLON.serialize()
  60058. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60059. __decorate([
  60060. BABYLON.serialize()
  60061. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60062. __decorate([
  60063. BABYLON.serializeAsTexture("lensTexture")
  60064. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60065. __decorate([
  60066. BABYLON.serialize()
  60067. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  60068. __decorate([
  60069. BABYLON.serialize()
  60070. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  60071. __decorate([
  60072. BABYLON.serialize()
  60073. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  60074. __decorate([
  60075. BABYLON.serialize()
  60076. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  60077. __decorate([
  60078. BABYLON.serialize()
  60079. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  60080. __decorate([
  60081. BABYLON.serialize()
  60082. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  60083. __decorate([
  60084. BABYLON.serializeAsTexture("lensColorTexture")
  60085. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60086. __decorate([
  60087. BABYLON.serialize()
  60088. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  60089. __decorate([
  60090. BABYLON.serialize()
  60091. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  60092. __decorate([
  60093. BABYLON.serialize()
  60094. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  60095. __decorate([
  60096. BABYLON.serialize()
  60097. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  60098. __decorate([
  60099. BABYLON.serializeAsTexture("lensStarTexture")
  60100. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  60101. __decorate([
  60102. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  60103. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  60104. __decorate([
  60105. BABYLON.serialize()
  60106. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  60107. __decorate([
  60108. BABYLON.serialize()
  60109. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  60110. __decorate([
  60111. BABYLON.serialize()
  60112. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  60113. __decorate([
  60114. BABYLON.serialize()
  60115. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  60116. __decorate([
  60117. BABYLON.serialize()
  60118. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  60119. __decorate([
  60120. BABYLON.serialize()
  60121. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  60122. __decorate([
  60123. BABYLON.serialize()
  60124. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  60125. __decorate([
  60126. BABYLON.serialize()
  60127. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  60128. __decorate([
  60129. BABYLON.serialize()
  60130. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  60131. __decorate([
  60132. BABYLON.serialize()
  60133. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  60134. __decorate([
  60135. BABYLON.serialize()
  60136. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  60137. __decorate([
  60138. BABYLON.serialize()
  60139. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  60140. return StandardRenderingPipeline;
  60141. }(BABYLON.PostProcessRenderPipeline));
  60142. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  60143. })(BABYLON || (BABYLON = {}));
  60144. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  60145. var BABYLON;
  60146. (function (BABYLON) {
  60147. var FxaaPostProcess = /** @class */ (function (_super) {
  60148. __extends(FxaaPostProcess, _super);
  60149. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60150. if (camera === void 0) { camera = null; }
  60151. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60152. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  60153. _this.onApplyObservable.add(function (effect) {
  60154. var texelSize = _this.texelSize;
  60155. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  60156. });
  60157. return _this;
  60158. }
  60159. return FxaaPostProcess;
  60160. }(BABYLON.PostProcess));
  60161. BABYLON.FxaaPostProcess = FxaaPostProcess;
  60162. })(BABYLON || (BABYLON = {}));
  60163. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  60164. var BABYLON;
  60165. (function (BABYLON) {
  60166. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  60167. __extends(DefaultRenderingPipeline, _super);
  60168. /**
  60169. * @constructor
  60170. * @param {string} name - The rendering pipeline name
  60171. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60172. * @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)
  60173. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60174. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  60175. */
  60176. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  60177. if (automaticBuild === void 0) { automaticBuild = true; }
  60178. var _this = _super.call(this, scene.getEngine(), name) || this;
  60179. _this.PassPostProcessId = "PassPostProcessEffect";
  60180. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  60181. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  60182. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  60183. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  60184. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  60185. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  60186. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  60187. // IAnimatable
  60188. _this.animations = [];
  60189. // Values
  60190. _this._bloomEnabled = false;
  60191. _this._fxaaEnabled = false;
  60192. _this._imageProcessingEnabled = true;
  60193. _this._bloomScale = 0.6;
  60194. _this._buildAllowed = true;
  60195. /**
  60196. * Specifies the size of the bloom blur kernel, relative to the final output size
  60197. */
  60198. _this.bloomKernel = 64;
  60199. /**
  60200. * Specifies the weight of the bloom in the final rendering
  60201. */
  60202. _this._bloomWeight = 0.15;
  60203. _this._cameras = cameras || [];
  60204. _this._buildAllowed = automaticBuild;
  60205. // Initialize
  60206. _this._scene = scene;
  60207. var caps = _this._scene.getEngine().getCaps();
  60208. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  60209. // Misc
  60210. if (_this._hdr) {
  60211. if (caps.textureHalfFloatRender) {
  60212. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60213. }
  60214. else if (caps.textureFloatRender) {
  60215. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60216. }
  60217. }
  60218. else {
  60219. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60220. }
  60221. // Attach
  60222. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60223. _this._buildPipeline();
  60224. return _this;
  60225. }
  60226. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  60227. get: function () {
  60228. return this._bloomWeight;
  60229. },
  60230. set: function (value) {
  60231. if (this._bloomWeight === value) {
  60232. return;
  60233. }
  60234. this._bloomWeight = value;
  60235. if (this._hdr && this.copyBack) {
  60236. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  60237. }
  60238. },
  60239. enumerable: true,
  60240. configurable: true
  60241. });
  60242. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  60243. get: function () {
  60244. return this._bloomScale;
  60245. },
  60246. set: function (value) {
  60247. if (this._bloomScale === value) {
  60248. return;
  60249. }
  60250. this._bloomScale = value;
  60251. this._buildPipeline();
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  60257. get: function () {
  60258. return this._bloomEnabled;
  60259. },
  60260. set: function (enabled) {
  60261. if (this._bloomEnabled === enabled) {
  60262. return;
  60263. }
  60264. this._bloomEnabled = enabled;
  60265. this._buildPipeline();
  60266. },
  60267. enumerable: true,
  60268. configurable: true
  60269. });
  60270. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  60271. get: function () {
  60272. return this._fxaaEnabled;
  60273. },
  60274. set: function (enabled) {
  60275. if (this._fxaaEnabled === enabled) {
  60276. return;
  60277. }
  60278. this._fxaaEnabled = enabled;
  60279. this._buildPipeline();
  60280. },
  60281. enumerable: true,
  60282. configurable: true
  60283. });
  60284. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  60285. get: function () {
  60286. return this._imageProcessingEnabled;
  60287. },
  60288. set: function (enabled) {
  60289. if (this._imageProcessingEnabled === enabled) {
  60290. return;
  60291. }
  60292. this._imageProcessingEnabled = enabled;
  60293. this._buildPipeline();
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. /**
  60299. * Force the compilation of the entire pipeline.
  60300. */
  60301. DefaultRenderingPipeline.prototype.prepare = function () {
  60302. var previousState = this._buildAllowed;
  60303. this._buildAllowed = true;
  60304. this._buildPipeline();
  60305. this._buildAllowed = previousState;
  60306. };
  60307. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  60308. var _this = this;
  60309. if (!this._buildAllowed) {
  60310. return;
  60311. }
  60312. var engine = this._scene.getEngine();
  60313. this._disposePostProcesses();
  60314. this._reset();
  60315. if (this.bloomEnabled) {
  60316. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60317. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  60318. if (!this._hdr) {
  60319. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60320. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  60321. this.highlights.autoClear = false;
  60322. this.highlights.alwaysForcePOT = true;
  60323. }
  60324. 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);
  60325. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  60326. this.blurX.alwaysForcePOT = true;
  60327. this.blurX.autoClear = false;
  60328. this.blurX.onActivateObservable.add(function () {
  60329. var dw = _this.blurX.width / engine.getRenderWidth(true);
  60330. _this.blurX.kernel = _this.bloomKernel * dw;
  60331. });
  60332. 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);
  60333. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  60334. this.blurY.alwaysForcePOT = true;
  60335. this.blurY.autoClear = false;
  60336. this.blurY.onActivateObservable.add(function () {
  60337. var dh = _this.blurY.height / engine.getRenderHeight(true);
  60338. _this.blurY.kernel = _this.bloomKernel * dh;
  60339. });
  60340. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60341. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  60342. this.copyBack.alwaysForcePOT = true;
  60343. if (this._hdr) {
  60344. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  60345. var w = this.bloomWeight;
  60346. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  60347. }
  60348. else {
  60349. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  60350. }
  60351. this.copyBack.autoClear = false;
  60352. }
  60353. if (this._imageProcessingEnabled) {
  60354. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60355. if (this._hdr) {
  60356. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  60357. }
  60358. else {
  60359. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  60360. }
  60361. }
  60362. if (this.fxaaEnabled) {
  60363. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60364. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  60365. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60366. }
  60367. else if (this._hdr && this.imageProcessing) {
  60368. this.finalMerge = this.imageProcessing;
  60369. }
  60370. else {
  60371. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60372. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  60373. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60374. }
  60375. if (this.bloomEnabled) {
  60376. if (this._hdr) {
  60377. this.copyBack.shareOutputWith(this.blurX);
  60378. if (this.imageProcessing) {
  60379. this.imageProcessing.shareOutputWith(this.pass);
  60380. this.imageProcessing.autoClear = false;
  60381. }
  60382. else if (this.fxaa) {
  60383. this.fxaa.shareOutputWith(this.pass);
  60384. }
  60385. else {
  60386. this.finalMerge.shareOutputWith(this.pass);
  60387. }
  60388. }
  60389. else {
  60390. if (this.fxaa) {
  60391. this.fxaa.shareOutputWith(this.pass);
  60392. }
  60393. else {
  60394. this.finalMerge.shareOutputWith(this.pass);
  60395. }
  60396. }
  60397. }
  60398. if (this._cameras !== null) {
  60399. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60400. }
  60401. };
  60402. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  60403. for (var i = 0; i < this._cameras.length; i++) {
  60404. var camera = this._cameras[i];
  60405. if (this.pass) {
  60406. this.pass.dispose(camera);
  60407. }
  60408. if (this.highlights) {
  60409. this.highlights.dispose(camera);
  60410. }
  60411. if (this.blurX) {
  60412. this.blurX.dispose(camera);
  60413. }
  60414. if (this.blurY) {
  60415. this.blurY.dispose(camera);
  60416. }
  60417. if (this.copyBack) {
  60418. this.copyBack.dispose(camera);
  60419. }
  60420. if (this.imageProcessing) {
  60421. this.imageProcessing.dispose(camera);
  60422. }
  60423. if (this.fxaa) {
  60424. this.fxaa.dispose(camera);
  60425. }
  60426. if (this.finalMerge) {
  60427. this.finalMerge.dispose(camera);
  60428. }
  60429. }
  60430. this.pass = null;
  60431. this.highlights = null;
  60432. this.blurX = null;
  60433. this.blurY = null;
  60434. this.copyBack = null;
  60435. this.imageProcessing = null;
  60436. this.fxaa = null;
  60437. this.finalMerge = null;
  60438. };
  60439. // Dispose
  60440. DefaultRenderingPipeline.prototype.dispose = function () {
  60441. this._disposePostProcesses();
  60442. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60443. _super.prototype.dispose.call(this);
  60444. };
  60445. // Serialize rendering pipeline
  60446. DefaultRenderingPipeline.prototype.serialize = function () {
  60447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60448. serializationObject.customType = "DefaultRenderingPipeline";
  60449. return serializationObject;
  60450. };
  60451. // Parse serialized pipeline
  60452. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60453. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  60454. };
  60455. __decorate([
  60456. BABYLON.serialize()
  60457. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  60458. __decorate([
  60459. BABYLON.serialize()
  60460. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  60461. __decorate([
  60462. BABYLON.serialize()
  60463. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  60464. __decorate([
  60465. BABYLON.serialize()
  60466. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  60467. __decorate([
  60468. BABYLON.serialize()
  60469. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  60470. __decorate([
  60471. BABYLON.serialize()
  60472. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  60473. __decorate([
  60474. BABYLON.serialize()
  60475. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  60476. __decorate([
  60477. BABYLON.serialize()
  60478. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60479. return DefaultRenderingPipeline;
  60480. }(BABYLON.PostProcessRenderPipeline));
  60481. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60482. })(BABYLON || (BABYLON = {}));
  60483. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60484. var BABYLON;
  60485. (function (BABYLON) {
  60486. var GeometryBufferRenderer = /** @class */ (function () {
  60487. function GeometryBufferRenderer(scene, ratio) {
  60488. if (ratio === void 0) { ratio = 1; }
  60489. this._enablePosition = false;
  60490. this._scene = scene;
  60491. this._ratio = ratio;
  60492. // Render target
  60493. this._createRenderTargets();
  60494. }
  60495. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60496. set: function (meshes) {
  60497. this._multiRenderTarget.renderList = meshes;
  60498. },
  60499. enumerable: true,
  60500. configurable: true
  60501. });
  60502. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60503. get: function () {
  60504. return this._multiRenderTarget.isSupported;
  60505. },
  60506. enumerable: true,
  60507. configurable: true
  60508. });
  60509. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60510. get: function () {
  60511. return this._enablePosition;
  60512. },
  60513. set: function (enable) {
  60514. this._enablePosition = enable;
  60515. this.dispose();
  60516. this._createRenderTargets();
  60517. },
  60518. enumerable: true,
  60519. configurable: true
  60520. });
  60521. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60522. var material = subMesh.getMaterial();
  60523. if (material && material.disableDepthWrite) {
  60524. return false;
  60525. }
  60526. var defines = [];
  60527. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60528. var mesh = subMesh.getMesh();
  60529. // Alpha test
  60530. if (material && material.needAlphaTesting()) {
  60531. defines.push("#define ALPHATEST");
  60532. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60533. attribs.push(BABYLON.VertexBuffer.UVKind);
  60534. defines.push("#define UV1");
  60535. }
  60536. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60537. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60538. defines.push("#define UV2");
  60539. }
  60540. }
  60541. // Buffers
  60542. if (this._enablePosition) {
  60543. defines.push("#define POSITION");
  60544. }
  60545. // Bones
  60546. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60547. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60548. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60549. if (mesh.numBoneInfluencers > 4) {
  60550. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60551. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60552. }
  60553. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60554. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60555. }
  60556. else {
  60557. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60558. }
  60559. // Instances
  60560. if (useInstances) {
  60561. defines.push("#define INSTANCES");
  60562. attribs.push("world0");
  60563. attribs.push("world1");
  60564. attribs.push("world2");
  60565. attribs.push("world3");
  60566. }
  60567. // Get correct effect
  60568. var join = defines.join("\n");
  60569. if (this._cachedDefines !== join) {
  60570. this._cachedDefines = join;
  60571. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60572. }
  60573. return this._effect.isReady();
  60574. };
  60575. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60576. return this._multiRenderTarget;
  60577. };
  60578. // Methods
  60579. GeometryBufferRenderer.prototype.dispose = function () {
  60580. this.getGBuffer().dispose();
  60581. };
  60582. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60583. var _this = this;
  60584. var engine = this._scene.getEngine();
  60585. var count = this._enablePosition ? 3 : 2;
  60586. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60587. if (!this.isSupported) {
  60588. return;
  60589. }
  60590. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60591. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60592. this._multiRenderTarget.refreshRate = 1;
  60593. this._multiRenderTarget.renderParticles = false;
  60594. this._multiRenderTarget.renderList = null;
  60595. // set default depth value to 1.0 (far away)
  60596. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60597. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60598. });
  60599. // Custom render function
  60600. var renderSubMesh = function (subMesh) {
  60601. var mesh = subMesh.getRenderingMesh();
  60602. var scene = _this._scene;
  60603. var engine = scene.getEngine();
  60604. var material = subMesh.getMaterial();
  60605. if (!material) {
  60606. return;
  60607. }
  60608. // Culling
  60609. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  60610. // Managing instances
  60611. var batch = mesh._getInstancesRenderList(subMesh._id);
  60612. if (batch.mustReturn) {
  60613. return;
  60614. }
  60615. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60616. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60617. engine.enableEffect(_this._effect);
  60618. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60619. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60620. _this._effect.setMatrix("view", scene.getViewMatrix());
  60621. // Alpha test
  60622. if (material && material.needAlphaTesting()) {
  60623. var alphaTexture = material.getAlphaTestTexture();
  60624. if (alphaTexture) {
  60625. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60626. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60627. }
  60628. }
  60629. // Bones
  60630. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60631. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60632. }
  60633. // Draw
  60634. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60635. }
  60636. };
  60637. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60638. var index;
  60639. if (depthOnlySubMeshes.length) {
  60640. engine.setColorWrite(false);
  60641. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60642. renderSubMesh(depthOnlySubMeshes.data[index]);
  60643. }
  60644. engine.setColorWrite(true);
  60645. }
  60646. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60647. renderSubMesh(opaqueSubMeshes.data[index]);
  60648. }
  60649. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60650. renderSubMesh(alphaTestSubMeshes.data[index]);
  60651. }
  60652. };
  60653. };
  60654. return GeometryBufferRenderer;
  60655. }());
  60656. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60657. })(BABYLON || (BABYLON = {}));
  60658. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60659. var BABYLON;
  60660. (function (BABYLON) {
  60661. var RefractionPostProcess = /** @class */ (function (_super) {
  60662. __extends(RefractionPostProcess, _super);
  60663. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60664. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60665. _this.color = color;
  60666. _this.depth = depth;
  60667. _this.colorLevel = colorLevel;
  60668. _this.onActivateObservable.add(function (cam) {
  60669. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60670. });
  60671. _this.onApplyObservable.add(function (effect) {
  60672. effect.setColor3("baseColor", _this.color);
  60673. effect.setFloat("depth", _this.depth);
  60674. effect.setFloat("colorLevel", _this.colorLevel);
  60675. effect.setTexture("refractionSampler", _this._refRexture);
  60676. });
  60677. return _this;
  60678. }
  60679. // Methods
  60680. RefractionPostProcess.prototype.dispose = function (camera) {
  60681. if (this._refRexture) {
  60682. this._refRexture.dispose();
  60683. }
  60684. _super.prototype.dispose.call(this, camera);
  60685. };
  60686. return RefractionPostProcess;
  60687. }(BABYLON.PostProcess));
  60688. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60689. })(BABYLON || (BABYLON = {}));
  60690. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60691. var BABYLON;
  60692. (function (BABYLON) {
  60693. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60694. __extends(BlackAndWhitePostProcess, _super);
  60695. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60696. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60697. _this.degree = 1;
  60698. _this.onApplyObservable.add(function (effect) {
  60699. effect.setFloat("degree", _this.degree);
  60700. });
  60701. return _this;
  60702. }
  60703. return BlackAndWhitePostProcess;
  60704. }(BABYLON.PostProcess));
  60705. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60706. })(BABYLON || (BABYLON = {}));
  60707. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60708. var BABYLON;
  60709. (function (BABYLON) {
  60710. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60711. __extends(ConvolutionPostProcess, _super);
  60712. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60713. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60714. _this.kernel = kernel;
  60715. _this.onApply = function (effect) {
  60716. effect.setFloat2("screenSize", _this.width, _this.height);
  60717. effect.setArray("kernel", _this.kernel);
  60718. };
  60719. return _this;
  60720. }
  60721. // Statics
  60722. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60723. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60724. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60725. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60726. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60727. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60728. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60729. return ConvolutionPostProcess;
  60730. }(BABYLON.PostProcess));
  60731. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60732. })(BABYLON || (BABYLON = {}));
  60733. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60734. var BABYLON;
  60735. (function (BABYLON) {
  60736. var FilterPostProcess = /** @class */ (function (_super) {
  60737. __extends(FilterPostProcess, _super);
  60738. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60739. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60740. _this.kernelMatrix = kernelMatrix;
  60741. _this.onApply = function (effect) {
  60742. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60743. };
  60744. return _this;
  60745. }
  60746. return FilterPostProcess;
  60747. }(BABYLON.PostProcess));
  60748. BABYLON.FilterPostProcess = FilterPostProcess;
  60749. })(BABYLON || (BABYLON = {}));
  60750. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60751. var BABYLON;
  60752. (function (BABYLON) {
  60753. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60754. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60755. __extends(VolumetricLightScatteringPostProcess, _super);
  60756. /**
  60757. * @constructor
  60758. * @param {string} name - The post-process name
  60759. * @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)
  60760. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60761. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60762. * @param {number} samples - The post-process quality, default 100
  60763. * @param {number} samplingMode - The post-process filtering mode
  60764. * @param {BABYLON.Engine} engine - The babylon engine
  60765. * @param {boolean} reusable - If the post-process is reusable
  60766. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60767. */
  60768. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60769. if (samples === void 0) { samples = 100; }
  60770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60771. 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;
  60772. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60773. /**
  60774. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60775. * @type {Vector3}
  60776. */
  60777. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60778. /**
  60779. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60780. * @type {boolean}
  60781. */
  60782. _this.useCustomMeshPosition = false;
  60783. /**
  60784. * If the post-process should inverse the light scattering direction
  60785. * @type {boolean}
  60786. */
  60787. _this.invert = true;
  60788. /**
  60789. * Array containing the excluded meshes not rendered in the internal pass
  60790. */
  60791. _this.excludedMeshes = new Array();
  60792. /**
  60793. * Controls the overall intensity of the post-process
  60794. * @type {number}
  60795. */
  60796. _this.exposure = 0.3;
  60797. /**
  60798. * Dissipates each sample's contribution in range [0, 1]
  60799. * @type {number}
  60800. */
  60801. _this.decay = 0.96815;
  60802. /**
  60803. * Controls the overall intensity of each sample
  60804. * @type {number}
  60805. */
  60806. _this.weight = 0.58767;
  60807. /**
  60808. * Controls the density of each sample
  60809. * @type {number}
  60810. */
  60811. _this.density = 0.926;
  60812. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60813. engine = scene.getEngine();
  60814. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60815. // Configure mesh
  60816. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60817. // Configure
  60818. _this._createPass(scene, ratio.passRatio || ratio);
  60819. _this.onActivate = function (camera) {
  60820. if (!_this.isSupported) {
  60821. _this.dispose(camera);
  60822. }
  60823. _this.onActivate = null;
  60824. };
  60825. _this.onApplyObservable.add(function (effect) {
  60826. _this._updateMeshScreenCoordinates(scene);
  60827. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60828. effect.setFloat("exposure", _this.exposure);
  60829. effect.setFloat("decay", _this.decay);
  60830. effect.setFloat("weight", _this.weight);
  60831. effect.setFloat("density", _this.density);
  60832. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60833. });
  60834. return _this;
  60835. }
  60836. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60837. get: function () {
  60838. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60839. return false;
  60840. },
  60841. set: function (useDiffuseColor) {
  60842. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60843. },
  60844. enumerable: true,
  60845. configurable: true
  60846. });
  60847. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60848. return "VolumetricLightScatteringPostProcess";
  60849. };
  60850. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60851. var mesh = subMesh.getMesh();
  60852. // Render this.mesh as default
  60853. if (mesh === this.mesh && mesh.material) {
  60854. return mesh.material.isReady(mesh);
  60855. }
  60856. var defines = [];
  60857. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60858. var material = subMesh.getMaterial();
  60859. // Alpha test
  60860. if (material) {
  60861. if (material.needAlphaTesting()) {
  60862. defines.push("#define ALPHATEST");
  60863. }
  60864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60865. attribs.push(BABYLON.VertexBuffer.UVKind);
  60866. defines.push("#define UV1");
  60867. }
  60868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60869. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60870. defines.push("#define UV2");
  60871. }
  60872. }
  60873. // Bones
  60874. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60877. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60878. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60879. }
  60880. else {
  60881. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60882. }
  60883. // Instances
  60884. if (useInstances) {
  60885. defines.push("#define INSTANCES");
  60886. attribs.push("world0");
  60887. attribs.push("world1");
  60888. attribs.push("world2");
  60889. attribs.push("world3");
  60890. }
  60891. // Get correct effect
  60892. var join = defines.join("\n");
  60893. if (this._cachedDefines !== join) {
  60894. this._cachedDefines = join;
  60895. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60896. }
  60897. return this._volumetricLightScatteringPass.isReady();
  60898. };
  60899. /**
  60900. * Sets the new light position for light scattering effect
  60901. * @param {BABYLON.Vector3} The new custom light position
  60902. */
  60903. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60904. this.customMeshPosition = position;
  60905. };
  60906. /**
  60907. * Returns the light position for light scattering effect
  60908. * @return {BABYLON.Vector3} The custom light position
  60909. */
  60910. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60911. return this.customMeshPosition;
  60912. };
  60913. /**
  60914. * Disposes the internal assets and detaches the post-process from the camera
  60915. */
  60916. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60917. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60918. if (rttIndex !== -1) {
  60919. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60920. }
  60921. this._volumetricLightScatteringRTT.dispose();
  60922. _super.prototype.dispose.call(this, camera);
  60923. };
  60924. /**
  60925. * Returns the render target texture used by the post-process
  60926. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60927. */
  60928. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60929. return this._volumetricLightScatteringRTT;
  60930. };
  60931. // Private methods
  60932. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60933. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60934. return true;
  60935. }
  60936. return false;
  60937. };
  60938. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60939. var _this = this;
  60940. var engine = scene.getEngine();
  60941. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60942. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60943. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60944. this._volumetricLightScatteringRTT.renderList = null;
  60945. this._volumetricLightScatteringRTT.renderParticles = false;
  60946. var camera = this.getCamera();
  60947. if (camera) {
  60948. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60949. }
  60950. else {
  60951. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60952. }
  60953. // Custom render function for submeshes
  60954. var renderSubMesh = function (subMesh) {
  60955. var mesh = subMesh.getRenderingMesh();
  60956. if (_this._meshExcluded(mesh)) {
  60957. return;
  60958. }
  60959. var material = subMesh.getMaterial();
  60960. if (!material) {
  60961. return;
  60962. }
  60963. var scene = mesh.getScene();
  60964. var engine = scene.getEngine();
  60965. // Culling
  60966. engine.setState(material.backFaceCulling);
  60967. // Managing instances
  60968. var batch = mesh._getInstancesRenderList(subMesh._id);
  60969. if (batch.mustReturn) {
  60970. return;
  60971. }
  60972. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60973. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60974. var effect = _this._volumetricLightScatteringPass;
  60975. if (mesh === _this.mesh) {
  60976. if (subMesh.effect) {
  60977. effect = subMesh.effect;
  60978. }
  60979. else {
  60980. effect = material.getEffect();
  60981. }
  60982. }
  60983. engine.enableEffect(effect);
  60984. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60985. if (mesh === _this.mesh) {
  60986. material.bind(mesh.getWorldMatrix(), mesh);
  60987. }
  60988. else {
  60989. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60990. // Alpha test
  60991. if (material && material.needAlphaTesting()) {
  60992. var alphaTexture = material.getAlphaTestTexture();
  60993. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60994. if (alphaTexture) {
  60995. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60996. }
  60997. }
  60998. // Bones
  60999. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61000. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61001. }
  61002. }
  61003. // Draw
  61004. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  61005. }
  61006. };
  61007. // Render target texture callbacks
  61008. var savedSceneClearColor;
  61009. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  61010. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  61011. savedSceneClearColor = scene.clearColor;
  61012. scene.clearColor = sceneClearColor;
  61013. });
  61014. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  61015. scene.clearColor = savedSceneClearColor;
  61016. });
  61017. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61018. var engine = scene.getEngine();
  61019. var index;
  61020. if (depthOnlySubMeshes.length) {
  61021. engine.setColorWrite(false);
  61022. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61023. renderSubMesh(depthOnlySubMeshes.data[index]);
  61024. }
  61025. engine.setColorWrite(true);
  61026. }
  61027. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61028. renderSubMesh(opaqueSubMeshes.data[index]);
  61029. }
  61030. engine.setAlphaTesting(true);
  61031. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61032. renderSubMesh(alphaTestSubMeshes.data[index]);
  61033. }
  61034. engine.setAlphaTesting(false);
  61035. if (transparentSubMeshes.length) {
  61036. // Sort sub meshes
  61037. for (index = 0; index < transparentSubMeshes.length; index++) {
  61038. var submesh = transparentSubMeshes.data[index];
  61039. var boundingInfo = submesh.getBoundingInfo();
  61040. if (boundingInfo && scene.activeCamera) {
  61041. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  61042. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  61043. }
  61044. }
  61045. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  61046. sortedArray.sort(function (a, b) {
  61047. // Alpha index first
  61048. if (a._alphaIndex > b._alphaIndex) {
  61049. return 1;
  61050. }
  61051. if (a._alphaIndex < b._alphaIndex) {
  61052. return -1;
  61053. }
  61054. // Then distance to camera
  61055. if (a._distanceToCamera < b._distanceToCamera) {
  61056. return 1;
  61057. }
  61058. if (a._distanceToCamera > b._distanceToCamera) {
  61059. return -1;
  61060. }
  61061. return 0;
  61062. });
  61063. // Render sub meshes
  61064. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61065. for (index = 0; index < sortedArray.length; index++) {
  61066. renderSubMesh(sortedArray[index]);
  61067. }
  61068. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61069. }
  61070. };
  61071. };
  61072. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  61073. var transform = scene.getTransformMatrix();
  61074. var meshPosition;
  61075. if (this.useCustomMeshPosition) {
  61076. meshPosition = this.customMeshPosition;
  61077. }
  61078. else if (this.attachedNode) {
  61079. meshPosition = this.attachedNode.position;
  61080. }
  61081. else {
  61082. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  61083. }
  61084. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  61085. this._screenCoordinates.x = pos.x / this._viewPort.width;
  61086. this._screenCoordinates.y = pos.y / this._viewPort.height;
  61087. if (this.invert)
  61088. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  61089. };
  61090. // Static methods
  61091. /**
  61092. * Creates a default mesh for the Volumeric Light Scattering post-process
  61093. * @param {string} The mesh name
  61094. * @param {BABYLON.Scene} The scene where to create the mesh
  61095. * @return {BABYLON.Mesh} the default mesh
  61096. */
  61097. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  61098. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  61099. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  61100. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  61101. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  61102. mesh.material = material;
  61103. return mesh;
  61104. };
  61105. __decorate([
  61106. BABYLON.serializeAsVector3()
  61107. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  61108. __decorate([
  61109. BABYLON.serialize()
  61110. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  61111. __decorate([
  61112. BABYLON.serialize()
  61113. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  61114. __decorate([
  61115. BABYLON.serializeAsMeshReference()
  61116. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  61117. __decorate([
  61118. BABYLON.serialize()
  61119. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  61120. __decorate([
  61121. BABYLON.serialize()
  61122. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  61123. __decorate([
  61124. BABYLON.serialize()
  61125. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  61126. __decorate([
  61127. BABYLON.serialize()
  61128. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  61129. __decorate([
  61130. BABYLON.serialize()
  61131. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  61132. return VolumetricLightScatteringPostProcess;
  61133. }(BABYLON.PostProcess));
  61134. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  61135. })(BABYLON || (BABYLON = {}));
  61136. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  61137. //
  61138. // This post-process allows the modification of rendered colors by using
  61139. // a 'look-up table' (LUT). This effect is also called Color Grading.
  61140. //
  61141. // The object needs to be provided an url to a texture containing the color
  61142. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  61143. // Use an image editing software to tweak the LUT to match your needs.
  61144. //
  61145. // For an example of a color LUT, see here:
  61146. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  61147. // For explanations on color grading, see here:
  61148. // http://udn.epicgames.com/Three/ColorGrading.html
  61149. //
  61150. var BABYLON;
  61151. (function (BABYLON) {
  61152. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  61153. __extends(ColorCorrectionPostProcess, _super);
  61154. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  61155. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  61156. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61157. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  61158. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61159. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61160. _this.onApply = function (effect) {
  61161. effect.setTexture("colorTable", _this._colorTableTexture);
  61162. };
  61163. return _this;
  61164. }
  61165. return ColorCorrectionPostProcess;
  61166. }(BABYLON.PostProcess));
  61167. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  61168. })(BABYLON || (BABYLON = {}));
  61169. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  61170. var BABYLON;
  61171. (function (BABYLON) {
  61172. var TonemappingOperator;
  61173. (function (TonemappingOperator) {
  61174. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  61175. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  61176. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  61177. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  61178. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  61179. ;
  61180. var TonemapPostProcess = /** @class */ (function (_super) {
  61181. __extends(TonemapPostProcess, _super);
  61182. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  61183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61184. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61185. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  61186. _this._operator = _operator;
  61187. _this.exposureAdjustment = exposureAdjustment;
  61188. var defines = "#define ";
  61189. if (_this._operator === TonemappingOperator.Hable)
  61190. defines += "HABLE_TONEMAPPING";
  61191. else if (_this._operator === TonemappingOperator.Reinhard)
  61192. defines += "REINHARD_TONEMAPPING";
  61193. else if (_this._operator === TonemappingOperator.HejiDawson)
  61194. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  61195. else if (_this._operator === TonemappingOperator.Photographic)
  61196. defines += "PHOTOGRAPHIC_TONEMAPPING";
  61197. //sadly a second call to create the effect.
  61198. _this.updateEffect(defines);
  61199. _this.onApply = function (effect) {
  61200. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  61201. };
  61202. return _this;
  61203. }
  61204. return TonemapPostProcess;
  61205. }(BABYLON.PostProcess));
  61206. BABYLON.TonemapPostProcess = TonemapPostProcess;
  61207. })(BABYLON || (BABYLON = {}));
  61208. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  61209. var BABYLON;
  61210. (function (BABYLON) {
  61211. var DisplayPassPostProcess = /** @class */ (function (_super) {
  61212. __extends(DisplayPassPostProcess, _super);
  61213. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  61214. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  61215. }
  61216. return DisplayPassPostProcess;
  61217. }(BABYLON.PostProcess));
  61218. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  61219. })(BABYLON || (BABYLON = {}));
  61220. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  61221. var BABYLON;
  61222. (function (BABYLON) {
  61223. var HighlightsPostProcess = /** @class */ (function (_super) {
  61224. __extends(HighlightsPostProcess, _super);
  61225. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61226. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61227. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  61228. }
  61229. return HighlightsPostProcess;
  61230. }(BABYLON.PostProcess));
  61231. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  61232. })(BABYLON || (BABYLON = {}));
  61233. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  61234. var BABYLON;
  61235. (function (BABYLON) {
  61236. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  61237. __extends(ImageProcessingPostProcess, _super);
  61238. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  61239. if (camera === void 0) { camera = null; }
  61240. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61241. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  61242. _this._fromLinearSpace = true;
  61243. /**
  61244. * Defines cache preventing GC.
  61245. */
  61246. _this._defines = {
  61247. IMAGEPROCESSING: false,
  61248. VIGNETTE: false,
  61249. VIGNETTEBLENDMODEMULTIPLY: false,
  61250. VIGNETTEBLENDMODEOPAQUE: false,
  61251. TONEMAPPING: false,
  61252. CONTRAST: false,
  61253. COLORCURVES: false,
  61254. COLORGRADING: false,
  61255. COLORGRADING3D: false,
  61256. FROMLINEARSPACE: false,
  61257. SAMPLER3DGREENDEPTH: false,
  61258. SAMPLER3DBGRMAP: false,
  61259. IMAGEPROCESSINGPOSTPROCESS: false,
  61260. EXPOSURE: false,
  61261. };
  61262. // Setup the configuration as forced by the constructor. This would then not force the
  61263. // scene materials output in linear space and let untouched the default forward pass.
  61264. if (imageProcessingConfiguration) {
  61265. imageProcessingConfiguration.applyByPostProcess = true;
  61266. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  61267. // This will cause the shader to be compiled
  61268. _this.fromLinearSpace = false;
  61269. }
  61270. else {
  61271. _this._attachImageProcessingConfiguration(null, true);
  61272. _this.imageProcessingConfiguration.applyByPostProcess = true;
  61273. }
  61274. _this.onApply = function (effect) {
  61275. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  61276. };
  61277. return _this;
  61278. }
  61279. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  61280. /**
  61281. * Gets the image processing configuration used either in this material.
  61282. */
  61283. get: function () {
  61284. return this._imageProcessingConfiguration;
  61285. },
  61286. /**
  61287. * Sets the Default image processing configuration used either in the this material.
  61288. *
  61289. * If sets to null, the scene one is in use.
  61290. */
  61291. set: function (value) {
  61292. this._attachImageProcessingConfiguration(value);
  61293. },
  61294. enumerable: true,
  61295. configurable: true
  61296. });
  61297. /**
  61298. * Attaches a new image processing configuration to the PBR Material.
  61299. * @param configuration
  61300. */
  61301. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  61302. var _this = this;
  61303. if (doNotBuild === void 0) { doNotBuild = false; }
  61304. if (configuration === this._imageProcessingConfiguration) {
  61305. return;
  61306. }
  61307. // Detaches observer.
  61308. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61309. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61310. }
  61311. // Pick the scene configuration if needed.
  61312. if (!configuration) {
  61313. var scene = null;
  61314. var engine = this.getEngine();
  61315. var camera = this.getCamera();
  61316. if (camera) {
  61317. scene = camera.getScene();
  61318. }
  61319. else if (engine && engine.scenes) {
  61320. var scenes = engine.scenes;
  61321. scene = scenes[scenes.length - 1];
  61322. }
  61323. else {
  61324. scene = BABYLON.Engine.LastCreatedScene;
  61325. }
  61326. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  61327. }
  61328. else {
  61329. this._imageProcessingConfiguration = configuration;
  61330. }
  61331. // Attaches observer.
  61332. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  61333. _this._updateParameters();
  61334. });
  61335. // Ensure the effect will be rebuilt.
  61336. if (!doNotBuild) {
  61337. this._updateParameters();
  61338. }
  61339. };
  61340. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  61341. /**
  61342. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61343. */
  61344. get: function () {
  61345. return this.imageProcessingConfiguration.colorCurves;
  61346. },
  61347. /**
  61348. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61349. */
  61350. set: function (value) {
  61351. this.imageProcessingConfiguration.colorCurves = value;
  61352. },
  61353. enumerable: true,
  61354. configurable: true
  61355. });
  61356. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  61357. /**
  61358. * Gets wether the color curves effect is enabled.
  61359. */
  61360. get: function () {
  61361. return this.imageProcessingConfiguration.colorCurvesEnabled;
  61362. },
  61363. /**
  61364. * Sets wether the color curves effect is enabled.
  61365. */
  61366. set: function (value) {
  61367. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  61368. },
  61369. enumerable: true,
  61370. configurable: true
  61371. });
  61372. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  61373. /**
  61374. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61375. */
  61376. get: function () {
  61377. return this.imageProcessingConfiguration.colorGradingTexture;
  61378. },
  61379. /**
  61380. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61381. */
  61382. set: function (value) {
  61383. this.imageProcessingConfiguration.colorGradingTexture = value;
  61384. },
  61385. enumerable: true,
  61386. configurable: true
  61387. });
  61388. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  61389. /**
  61390. * Gets wether the color grading effect is enabled.
  61391. */
  61392. get: function () {
  61393. return this.imageProcessingConfiguration.colorGradingEnabled;
  61394. },
  61395. /**
  61396. * Gets wether the color grading effect is enabled.
  61397. */
  61398. set: function (value) {
  61399. this.imageProcessingConfiguration.colorGradingEnabled = value;
  61400. },
  61401. enumerable: true,
  61402. configurable: true
  61403. });
  61404. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  61405. /**
  61406. * Gets exposure used in the effect.
  61407. */
  61408. get: function () {
  61409. return this.imageProcessingConfiguration.exposure;
  61410. },
  61411. /**
  61412. * Sets exposure used in the effect.
  61413. */
  61414. set: function (value) {
  61415. this.imageProcessingConfiguration.exposure = value;
  61416. },
  61417. enumerable: true,
  61418. configurable: true
  61419. });
  61420. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  61421. /**
  61422. * Gets wether tonemapping is enabled or not.
  61423. */
  61424. get: function () {
  61425. return this._imageProcessingConfiguration.toneMappingEnabled;
  61426. },
  61427. /**
  61428. * Sets wether tonemapping is enabled or not
  61429. */
  61430. set: function (value) {
  61431. this._imageProcessingConfiguration.toneMappingEnabled = value;
  61432. },
  61433. enumerable: true,
  61434. configurable: true
  61435. });
  61436. ;
  61437. ;
  61438. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  61439. /**
  61440. * Gets contrast used in the effect.
  61441. */
  61442. get: function () {
  61443. return this.imageProcessingConfiguration.contrast;
  61444. },
  61445. /**
  61446. * Sets contrast used in the effect.
  61447. */
  61448. set: function (value) {
  61449. this.imageProcessingConfiguration.contrast = value;
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  61455. /**
  61456. * Gets Vignette stretch size.
  61457. */
  61458. get: function () {
  61459. return this.imageProcessingConfiguration.vignetteStretch;
  61460. },
  61461. /**
  61462. * Sets Vignette stretch size.
  61463. */
  61464. set: function (value) {
  61465. this.imageProcessingConfiguration.vignetteStretch = value;
  61466. },
  61467. enumerable: true,
  61468. configurable: true
  61469. });
  61470. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  61471. /**
  61472. * Gets Vignette centre X Offset.
  61473. */
  61474. get: function () {
  61475. return this.imageProcessingConfiguration.vignetteCentreX;
  61476. },
  61477. /**
  61478. * Sets Vignette centre X Offset.
  61479. */
  61480. set: function (value) {
  61481. this.imageProcessingConfiguration.vignetteCentreX = value;
  61482. },
  61483. enumerable: true,
  61484. configurable: true
  61485. });
  61486. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61487. /**
  61488. * Gets Vignette centre Y Offset.
  61489. */
  61490. get: function () {
  61491. return this.imageProcessingConfiguration.vignetteCentreY;
  61492. },
  61493. /**
  61494. * Sets Vignette centre Y Offset.
  61495. */
  61496. set: function (value) {
  61497. this.imageProcessingConfiguration.vignetteCentreY = value;
  61498. },
  61499. enumerable: true,
  61500. configurable: true
  61501. });
  61502. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61503. /**
  61504. * Gets Vignette weight or intensity of the vignette effect.
  61505. */
  61506. get: function () {
  61507. return this.imageProcessingConfiguration.vignetteWeight;
  61508. },
  61509. /**
  61510. * Sets Vignette weight or intensity of the vignette effect.
  61511. */
  61512. set: function (value) {
  61513. this.imageProcessingConfiguration.vignetteWeight = value;
  61514. },
  61515. enumerable: true,
  61516. configurable: true
  61517. });
  61518. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61519. /**
  61520. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61521. * if vignetteEnabled is set to true.
  61522. */
  61523. get: function () {
  61524. return this.imageProcessingConfiguration.vignetteColor;
  61525. },
  61526. /**
  61527. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61528. * if vignetteEnabled is set to true.
  61529. */
  61530. set: function (value) {
  61531. this.imageProcessingConfiguration.vignetteColor = value;
  61532. },
  61533. enumerable: true,
  61534. configurable: true
  61535. });
  61536. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61537. /**
  61538. * Gets Camera field of view used by the Vignette effect.
  61539. */
  61540. get: function () {
  61541. return this.imageProcessingConfiguration.vignetteCameraFov;
  61542. },
  61543. /**
  61544. * Sets Camera field of view used by the Vignette effect.
  61545. */
  61546. set: function (value) {
  61547. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61548. },
  61549. enumerable: true,
  61550. configurable: true
  61551. });
  61552. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61553. /**
  61554. * Gets the vignette blend mode allowing different kind of effect.
  61555. */
  61556. get: function () {
  61557. return this.imageProcessingConfiguration.vignetteBlendMode;
  61558. },
  61559. /**
  61560. * Sets the vignette blend mode allowing different kind of effect.
  61561. */
  61562. set: function (value) {
  61563. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61564. },
  61565. enumerable: true,
  61566. configurable: true
  61567. });
  61568. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61569. /**
  61570. * Gets wether the vignette effect is enabled.
  61571. */
  61572. get: function () {
  61573. return this.imageProcessingConfiguration.vignetteEnabled;
  61574. },
  61575. /**
  61576. * Sets wether the vignette effect is enabled.
  61577. */
  61578. set: function (value) {
  61579. this.imageProcessingConfiguration.vignetteEnabled = value;
  61580. },
  61581. enumerable: true,
  61582. configurable: true
  61583. });
  61584. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61585. /**
  61586. * Gets wether the input of the processing is in Gamma or Linear Space.
  61587. */
  61588. get: function () {
  61589. return this._fromLinearSpace;
  61590. },
  61591. /**
  61592. * Sets wether the input of the processing is in Gamma or Linear Space.
  61593. */
  61594. set: function (value) {
  61595. if (this._fromLinearSpace === value) {
  61596. return;
  61597. }
  61598. this._fromLinearSpace = value;
  61599. this._updateParameters();
  61600. },
  61601. enumerable: true,
  61602. configurable: true
  61603. });
  61604. ImageProcessingPostProcess.prototype.getClassName = function () {
  61605. return "ImageProcessingPostProcess";
  61606. };
  61607. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61608. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61609. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61610. var defines = "";
  61611. for (var define in this._defines) {
  61612. if (this._defines[define]) {
  61613. defines += "#define " + define + ";\r\n";
  61614. }
  61615. }
  61616. var samplers = ["textureSampler"];
  61617. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61618. var uniforms = ["scale"];
  61619. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61620. this.updateEffect(defines, uniforms, samplers);
  61621. };
  61622. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61623. _super.prototype.dispose.call(this, camera);
  61624. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61625. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61626. }
  61627. this.imageProcessingConfiguration.applyByPostProcess = false;
  61628. };
  61629. __decorate([
  61630. BABYLON.serialize()
  61631. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61632. return ImageProcessingPostProcess;
  61633. }(BABYLON.PostProcess));
  61634. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61635. })(BABYLON || (BABYLON = {}));
  61636. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61637. var BABYLON;
  61638. (function (BABYLON) {
  61639. var BlurPostProcess = /** @class */ (function (_super) {
  61640. __extends(BlurPostProcess, _super);
  61641. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61642. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61643. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61644. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61645. _this.direction = direction;
  61646. _this._packedFloat = false;
  61647. _this.onApplyObservable.add(function (effect) {
  61648. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61649. });
  61650. _this.kernel = kernel;
  61651. return _this;
  61652. }
  61653. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61654. /**
  61655. * Gets the length in pixels of the blur sample region
  61656. */
  61657. get: function () {
  61658. return this._idealKernel;
  61659. },
  61660. /**
  61661. * Sets the length in pixels of the blur sample region
  61662. */
  61663. set: function (v) {
  61664. if (this._idealKernel === v) {
  61665. return;
  61666. }
  61667. v = Math.max(v, 1);
  61668. this._idealKernel = v;
  61669. this._kernel = this._nearestBestKernel(v);
  61670. this._updateParameters();
  61671. },
  61672. enumerable: true,
  61673. configurable: true
  61674. });
  61675. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61676. /**
  61677. * Gets wether or not the blur is unpacking/repacking floats
  61678. */
  61679. get: function () {
  61680. return this._packedFloat;
  61681. },
  61682. /**
  61683. * Sets wether or not the blur needs to unpack/repack floats
  61684. */
  61685. set: function (v) {
  61686. if (this._packedFloat === v) {
  61687. return;
  61688. }
  61689. this._packedFloat = v;
  61690. this._updateParameters();
  61691. },
  61692. enumerable: true,
  61693. configurable: true
  61694. });
  61695. BlurPostProcess.prototype._updateParameters = function () {
  61696. // Generate sampling offsets and weights
  61697. var N = this._kernel;
  61698. var centerIndex = (N - 1) / 2;
  61699. // Generate Gaussian sampling weights over kernel
  61700. var offsets = [];
  61701. var weights = [];
  61702. var totalWeight = 0;
  61703. for (var i = 0; i < N; i++) {
  61704. var u = i / (N - 1);
  61705. var w = this._gaussianWeight(u * 2.0 - 1);
  61706. offsets[i] = (i - centerIndex);
  61707. weights[i] = w;
  61708. totalWeight += w;
  61709. }
  61710. // Normalize weights
  61711. for (var i = 0; i < weights.length; i++) {
  61712. weights[i] /= totalWeight;
  61713. }
  61714. // Optimize: combine samples to take advantage of hardware linear sampling
  61715. // Walk from left to center, combining pairs (symmetrically)
  61716. var linearSamplingWeights = [];
  61717. var linearSamplingOffsets = [];
  61718. var linearSamplingMap = [];
  61719. for (var i = 0; i <= centerIndex; i += 2) {
  61720. var j = Math.min(i + 1, Math.floor(centerIndex));
  61721. var singleCenterSample = i === j;
  61722. if (singleCenterSample) {
  61723. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61724. }
  61725. else {
  61726. var sharedCell = j === centerIndex;
  61727. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61728. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61729. if (offsetLinear === 0) {
  61730. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61731. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61732. }
  61733. else {
  61734. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61735. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61736. }
  61737. }
  61738. }
  61739. for (var i = 0; i < linearSamplingMap.length; i++) {
  61740. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61741. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61742. }
  61743. // Replace with optimized
  61744. offsets = linearSamplingOffsets;
  61745. weights = linearSamplingWeights;
  61746. // Generate shaders
  61747. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61748. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61749. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61750. var defines = "";
  61751. for (var i = 0; i < varyingCount; i++) {
  61752. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61753. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61754. }
  61755. var depCount = 0;
  61756. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61757. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61758. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61759. depCount++;
  61760. }
  61761. if (this.packedFloat) {
  61762. defines += "#define PACKEDFLOAT 1";
  61763. }
  61764. this.updateEffect(defines, null, null, {
  61765. varyingCount: varyingCount,
  61766. depCount: depCount
  61767. });
  61768. };
  61769. /**
  61770. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61771. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61772. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61773. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61774. * The gaps between physical kernels are compensated for in the weighting of the samples
  61775. * @param idealKernel Ideal blur kernel.
  61776. * @return Nearest best kernel.
  61777. */
  61778. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61779. var v = Math.round(idealKernel);
  61780. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61781. var k = _a[_i];
  61782. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61783. return Math.max(k, 3);
  61784. }
  61785. }
  61786. return Math.max(v, 3);
  61787. };
  61788. /**
  61789. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61790. * @param x The point on the Gaussian distribution to sample.
  61791. * @return the value of the Gaussian function at x.
  61792. */
  61793. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61794. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61795. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61796. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61797. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61798. // truncated at around 1.3% of peak strength.
  61799. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61800. var sigma = (1 / 3);
  61801. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61802. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61803. var weight = (1.0 / denominator) * Math.exp(exponent);
  61804. return weight;
  61805. };
  61806. /**
  61807. * Generates a string that can be used as a floating point number in GLSL.
  61808. * @param x Value to print.
  61809. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61810. * @return GLSL float string.
  61811. */
  61812. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61813. if (decimalFigures === void 0) { decimalFigures = 8; }
  61814. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61815. };
  61816. return BlurPostProcess;
  61817. }(BABYLON.PostProcess));
  61818. BABYLON.BlurPostProcess = BlurPostProcess;
  61819. })(BABYLON || (BABYLON = {}));
  61820. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61821. var BABYLON;
  61822. (function (BABYLON) {
  61823. var Bone = /** @class */ (function (_super) {
  61824. __extends(Bone, _super);
  61825. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61826. if (parentBone === void 0) { parentBone = null; }
  61827. if (localMatrix === void 0) { localMatrix = null; }
  61828. if (restPose === void 0) { restPose = null; }
  61829. if (baseMatrix === void 0) { baseMatrix = null; }
  61830. if (index === void 0) { index = null; }
  61831. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61832. _this.name = name;
  61833. _this.children = new Array();
  61834. _this.animations = new Array();
  61835. // Set this value to map this bone to a different index in the transform matrices.
  61836. // Set this value to -1 to exclude the bone from the transform matrices.
  61837. _this._index = null;
  61838. _this._worldTransform = new BABYLON.Matrix();
  61839. _this._absoluteTransform = new BABYLON.Matrix();
  61840. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61841. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61842. _this._scaleVector = BABYLON.Vector3.One();
  61843. _this._negateScaleChildren = BABYLON.Vector3.One();
  61844. _this._scalingDeterminant = 1;
  61845. _this._skeleton = skeleton;
  61846. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61847. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61848. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61849. _this._index = index;
  61850. skeleton.bones.push(_this);
  61851. _this.setParent(parentBone, false);
  61852. _this._updateDifferenceMatrix();
  61853. return _this;
  61854. }
  61855. Object.defineProperty(Bone.prototype, "_matrix", {
  61856. get: function () {
  61857. return this._localMatrix;
  61858. },
  61859. set: function (val) {
  61860. if (this._localMatrix) {
  61861. this._localMatrix.copyFrom(val);
  61862. }
  61863. else {
  61864. this._localMatrix = val;
  61865. }
  61866. },
  61867. enumerable: true,
  61868. configurable: true
  61869. });
  61870. // Members
  61871. Bone.prototype.getSkeleton = function () {
  61872. return this._skeleton;
  61873. };
  61874. Bone.prototype.getParent = function () {
  61875. return this._parent;
  61876. };
  61877. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61878. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61879. if (this._parent === parent) {
  61880. return;
  61881. }
  61882. if (this._parent) {
  61883. var index = this._parent.children.indexOf(this);
  61884. if (index !== -1) {
  61885. this._parent.children.splice(index, 1);
  61886. }
  61887. }
  61888. this._parent = parent;
  61889. if (this._parent) {
  61890. this._parent.children.push(this);
  61891. }
  61892. if (updateDifferenceMatrix) {
  61893. this._updateDifferenceMatrix();
  61894. }
  61895. };
  61896. Bone.prototype.getLocalMatrix = function () {
  61897. return this._localMatrix;
  61898. };
  61899. Bone.prototype.getBaseMatrix = function () {
  61900. return this._baseMatrix;
  61901. };
  61902. Bone.prototype.getRestPose = function () {
  61903. return this._restPose;
  61904. };
  61905. Bone.prototype.returnToRest = function () {
  61906. this.updateMatrix(this._restPose.clone());
  61907. };
  61908. Bone.prototype.getWorldMatrix = function () {
  61909. return this._worldTransform;
  61910. };
  61911. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61912. return this._invertedAbsoluteTransform;
  61913. };
  61914. Bone.prototype.getAbsoluteTransform = function () {
  61915. return this._absoluteTransform;
  61916. };
  61917. Object.defineProperty(Bone.prototype, "position", {
  61918. // Properties (matches AbstractMesh properties)
  61919. get: function () {
  61920. return this.getPosition();
  61921. },
  61922. set: function (newPosition) {
  61923. this.setPosition(newPosition);
  61924. },
  61925. enumerable: true,
  61926. configurable: true
  61927. });
  61928. Object.defineProperty(Bone.prototype, "rotation", {
  61929. get: function () {
  61930. return this.getRotation();
  61931. },
  61932. set: function (newRotation) {
  61933. this.setRotation(newRotation);
  61934. },
  61935. enumerable: true,
  61936. configurable: true
  61937. });
  61938. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61939. get: function () {
  61940. return this.getRotationQuaternion();
  61941. },
  61942. set: function (newRotation) {
  61943. this.setRotationQuaternion(newRotation);
  61944. },
  61945. enumerable: true,
  61946. configurable: true
  61947. });
  61948. Object.defineProperty(Bone.prototype, "scaling", {
  61949. get: function () {
  61950. return this.getScale();
  61951. },
  61952. set: function (newScaling) {
  61953. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61954. },
  61955. enumerable: true,
  61956. configurable: true
  61957. });
  61958. // Methods
  61959. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61960. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61961. this._baseMatrix = matrix.clone();
  61962. this._localMatrix = matrix.clone();
  61963. this._skeleton._markAsDirty();
  61964. if (updateDifferenceMatrix) {
  61965. this._updateDifferenceMatrix();
  61966. }
  61967. };
  61968. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61969. if (!rootMatrix) {
  61970. rootMatrix = this._baseMatrix;
  61971. }
  61972. if (this._parent) {
  61973. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61974. }
  61975. else {
  61976. this._absoluteTransform.copyFrom(rootMatrix);
  61977. }
  61978. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61979. for (var index = 0; index < this.children.length; index++) {
  61980. this.children[index]._updateDifferenceMatrix();
  61981. }
  61982. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61983. };
  61984. Bone.prototype.markAsDirty = function () {
  61985. this._currentRenderId++;
  61986. this._skeleton._markAsDirty();
  61987. };
  61988. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61989. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61990. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61991. // all animation may be coming from a library skeleton, so may need to create animation
  61992. if (this.animations.length === 0) {
  61993. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61994. this.animations[0].setKeys([]);
  61995. }
  61996. // get animation info / verify there is such a range from the source bone
  61997. var sourceRange = source.animations[0].getRange(rangeName);
  61998. if (!sourceRange) {
  61999. return false;
  62000. }
  62001. var from = sourceRange.from;
  62002. var to = sourceRange.to;
  62003. var sourceKeys = source.animations[0].getKeys();
  62004. // rescaling prep
  62005. var sourceBoneLength = source.length;
  62006. var sourceParent = source.getParent();
  62007. var parent = this.getParent();
  62008. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  62009. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  62010. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  62011. var destKeys = this.animations[0].getKeys();
  62012. // loop vars declaration
  62013. var orig;
  62014. var origTranslation;
  62015. var mat;
  62016. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  62017. orig = sourceKeys[key];
  62018. if (orig.frame >= from && orig.frame <= to) {
  62019. if (rescaleAsRequired) {
  62020. mat = orig.value.clone();
  62021. // scale based on parent ratio, when bone has parent
  62022. if (parentScalingReqd) {
  62023. origTranslation = mat.getTranslation();
  62024. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  62025. // scale based on skeleton dimension ratio when root bone, and value is passed
  62026. }
  62027. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  62028. origTranslation = mat.getTranslation();
  62029. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  62030. // use original when root bone, and no data for skelDimensionsRatio
  62031. }
  62032. else {
  62033. mat = orig.value;
  62034. }
  62035. }
  62036. else {
  62037. mat = orig.value;
  62038. }
  62039. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  62040. }
  62041. }
  62042. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  62043. return true;
  62044. };
  62045. /**
  62046. * Translate the bone in local or world space.
  62047. * @param vec The amount to translate the bone.
  62048. * @param space The space that the translation is in.
  62049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62050. */
  62051. Bone.prototype.translate = function (vec, space, mesh) {
  62052. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62053. var lm = this.getLocalMatrix();
  62054. if (space == BABYLON.Space.LOCAL) {
  62055. lm.m[12] += vec.x;
  62056. lm.m[13] += vec.y;
  62057. lm.m[14] += vec.z;
  62058. }
  62059. else {
  62060. var wm = null;
  62061. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62062. if (mesh) {
  62063. wm = mesh.getWorldMatrix();
  62064. }
  62065. this._skeleton.computeAbsoluteTransforms();
  62066. var tmat = Bone._tmpMats[0];
  62067. var tvec = Bone._tmpVecs[0];
  62068. if (this._parent) {
  62069. if (mesh && wm) {
  62070. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62071. tmat.multiplyToRef(wm, tmat);
  62072. }
  62073. else {
  62074. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62075. }
  62076. }
  62077. tmat.m[12] = 0;
  62078. tmat.m[13] = 0;
  62079. tmat.m[14] = 0;
  62080. tmat.invert();
  62081. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  62082. lm.m[12] += tvec.x;
  62083. lm.m[13] += tvec.y;
  62084. lm.m[14] += tvec.z;
  62085. }
  62086. this.markAsDirty();
  62087. };
  62088. /**
  62089. * Set the postion of the bone in local or world space.
  62090. * @param position The position to set the bone.
  62091. * @param space The space that the position is in.
  62092. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62093. */
  62094. Bone.prototype.setPosition = function (position, space, mesh) {
  62095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62096. var lm = this.getLocalMatrix();
  62097. if (space == BABYLON.Space.LOCAL) {
  62098. lm.m[12] = position.x;
  62099. lm.m[13] = position.y;
  62100. lm.m[14] = position.z;
  62101. }
  62102. else {
  62103. var wm = null;
  62104. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62105. if (mesh) {
  62106. wm = mesh.getWorldMatrix();
  62107. }
  62108. this._skeleton.computeAbsoluteTransforms();
  62109. var tmat = Bone._tmpMats[0];
  62110. var vec = Bone._tmpVecs[0];
  62111. if (this._parent) {
  62112. if (mesh && wm) {
  62113. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62114. tmat.multiplyToRef(wm, tmat);
  62115. }
  62116. else {
  62117. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62118. }
  62119. }
  62120. tmat.invert();
  62121. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  62122. lm.m[12] = vec.x;
  62123. lm.m[13] = vec.y;
  62124. lm.m[14] = vec.z;
  62125. }
  62126. this.markAsDirty();
  62127. };
  62128. /**
  62129. * Set the absolute postion of the bone (world space).
  62130. * @param position The position to set the bone.
  62131. * @param mesh The mesh that this bone is attached to.
  62132. */
  62133. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  62134. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  62135. };
  62136. /**
  62137. * Set the scale of the bone on the x, y and z axes.
  62138. * @param x The scale of the bone on the x axis.
  62139. * @param x The scale of the bone on the y axis.
  62140. * @param z The scale of the bone on the z axis.
  62141. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62142. */
  62143. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  62144. if (scaleChildren === void 0) { scaleChildren = false; }
  62145. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  62146. if (!scaleChildren) {
  62147. this._negateScaleChildren.x = 1 / x;
  62148. this._negateScaleChildren.y = 1 / y;
  62149. this._negateScaleChildren.z = 1 / z;
  62150. }
  62151. this._syncScaleVector();
  62152. }
  62153. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  62154. };
  62155. /**
  62156. * Scale the bone on the x, y and z axes.
  62157. * @param x The amount to scale the bone on the x axis.
  62158. * @param x The amount to scale the bone on the y axis.
  62159. * @param z The amount to scale the bone on the z axis.
  62160. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62161. */
  62162. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  62163. if (scaleChildren === void 0) { scaleChildren = false; }
  62164. var locMat = this.getLocalMatrix();
  62165. var origLocMat = Bone._tmpMats[0];
  62166. origLocMat.copyFrom(locMat);
  62167. var origLocMatInv = Bone._tmpMats[1];
  62168. origLocMatInv.copyFrom(origLocMat);
  62169. origLocMatInv.invert();
  62170. var scaleMat = Bone._tmpMats[2];
  62171. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  62172. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  62173. this._scaleVector.x *= x;
  62174. this._scaleVector.y *= y;
  62175. this._scaleVector.z *= z;
  62176. locMat.multiplyToRef(origLocMatInv, locMat);
  62177. locMat.multiplyToRef(scaleMat, locMat);
  62178. locMat.multiplyToRef(origLocMat, locMat);
  62179. var parent = this.getParent();
  62180. if (parent) {
  62181. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  62182. }
  62183. else {
  62184. this.getAbsoluteTransform().copyFrom(locMat);
  62185. }
  62186. var len = this.children.length;
  62187. scaleMat.invert();
  62188. for (var i = 0; i < len; i++) {
  62189. var child = this.children[i];
  62190. var cm = child.getLocalMatrix();
  62191. cm.multiplyToRef(scaleMat, cm);
  62192. var lm = child.getLocalMatrix();
  62193. lm.m[12] *= x;
  62194. lm.m[13] *= y;
  62195. lm.m[14] *= z;
  62196. }
  62197. this.computeAbsoluteTransforms();
  62198. if (scaleChildren) {
  62199. for (var i = 0; i < len; i++) {
  62200. this.children[i].scale(x, y, z, scaleChildren);
  62201. }
  62202. }
  62203. this.markAsDirty();
  62204. };
  62205. /**
  62206. * Set the yaw, pitch, and roll of the bone in local or world space.
  62207. * @param yaw The rotation of the bone on the y axis.
  62208. * @param pitch The rotation of the bone on the x axis.
  62209. * @param roll The rotation of the bone on the z axis.
  62210. * @param space The space that the axes of rotation are in.
  62211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62212. */
  62213. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  62214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62215. var rotMat = Bone._tmpMats[0];
  62216. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  62217. var rotMatInv = Bone._tmpMats[1];
  62218. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62219. rotMatInv.multiplyToRef(rotMat, rotMat);
  62220. this._rotateWithMatrix(rotMat, space, mesh);
  62221. };
  62222. /**
  62223. * Rotate the bone on an axis in local or world space.
  62224. * @param axis The axis to rotate the bone on.
  62225. * @param amount The amount to rotate the bone.
  62226. * @param space The space that the axis is in.
  62227. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62228. */
  62229. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  62230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62231. var rmat = Bone._tmpMats[0];
  62232. rmat.m[12] = 0;
  62233. rmat.m[13] = 0;
  62234. rmat.m[14] = 0;
  62235. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  62236. this._rotateWithMatrix(rmat, space, mesh);
  62237. };
  62238. /**
  62239. * Set the rotation of the bone to a particular axis angle in local or world space.
  62240. * @param axis The axis to rotate the bone on.
  62241. * @param angle The angle that the bone should be rotated to.
  62242. * @param space The space that the axis is in.
  62243. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62244. */
  62245. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  62246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62247. var rotMat = Bone._tmpMats[0];
  62248. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  62249. var rotMatInv = Bone._tmpMats[1];
  62250. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62251. rotMatInv.multiplyToRef(rotMat, rotMat);
  62252. this._rotateWithMatrix(rotMat, space, mesh);
  62253. };
  62254. /**
  62255. * Set the euler rotation of the bone in local of world space.
  62256. * @param rotation The euler rotation that the bone should be set to.
  62257. * @param space The space that the rotation is in.
  62258. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62259. */
  62260. Bone.prototype.setRotation = function (rotation, space, mesh) {
  62261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62262. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  62263. };
  62264. /**
  62265. * Set the quaternion rotation of the bone in local of world space.
  62266. * @param quat The quaternion rotation that the bone should be set to.
  62267. * @param space The space that the rotation is in.
  62268. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62269. */
  62270. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  62271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62272. var rotMatInv = Bone._tmpMats[0];
  62273. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62274. var rotMat = Bone._tmpMats[1];
  62275. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  62276. rotMatInv.multiplyToRef(rotMat, rotMat);
  62277. this._rotateWithMatrix(rotMat, space, mesh);
  62278. };
  62279. /**
  62280. * Set the rotation matrix of the bone in local of world space.
  62281. * @param rotMat The rotation matrix that the bone should be set to.
  62282. * @param space The space that the rotation is in.
  62283. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62284. */
  62285. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  62286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62287. var rotMatInv = Bone._tmpMats[0];
  62288. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62289. var rotMat2 = Bone._tmpMats[1];
  62290. rotMat2.copyFrom(rotMat);
  62291. rotMatInv.multiplyToRef(rotMat, rotMat2);
  62292. this._rotateWithMatrix(rotMat2, space, mesh);
  62293. };
  62294. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  62295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62296. var lmat = this.getLocalMatrix();
  62297. var lx = lmat.m[12];
  62298. var ly = lmat.m[13];
  62299. var lz = lmat.m[14];
  62300. var parent = this.getParent();
  62301. var parentScale = Bone._tmpMats[3];
  62302. var parentScaleInv = Bone._tmpMats[4];
  62303. if (parent) {
  62304. if (space == BABYLON.Space.WORLD) {
  62305. if (mesh) {
  62306. parentScale.copyFrom(mesh.getWorldMatrix());
  62307. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  62308. }
  62309. else {
  62310. parentScale.copyFrom(parent.getAbsoluteTransform());
  62311. }
  62312. }
  62313. else {
  62314. parentScale = parent._scaleMatrix;
  62315. }
  62316. parentScaleInv.copyFrom(parentScale);
  62317. parentScaleInv.invert();
  62318. lmat.multiplyToRef(parentScale, lmat);
  62319. lmat.multiplyToRef(rmat, lmat);
  62320. lmat.multiplyToRef(parentScaleInv, lmat);
  62321. }
  62322. else {
  62323. if (space == BABYLON.Space.WORLD && mesh) {
  62324. parentScale.copyFrom(mesh.getWorldMatrix());
  62325. parentScaleInv.copyFrom(parentScale);
  62326. parentScaleInv.invert();
  62327. lmat.multiplyToRef(parentScale, lmat);
  62328. lmat.multiplyToRef(rmat, lmat);
  62329. lmat.multiplyToRef(parentScaleInv, lmat);
  62330. }
  62331. else {
  62332. lmat.multiplyToRef(rmat, lmat);
  62333. }
  62334. }
  62335. lmat.m[12] = lx;
  62336. lmat.m[13] = ly;
  62337. lmat.m[14] = lz;
  62338. this.computeAbsoluteTransforms();
  62339. this.markAsDirty();
  62340. };
  62341. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  62342. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62343. if (space == BABYLON.Space.WORLD) {
  62344. var scaleMatrix = Bone._tmpMats[2];
  62345. scaleMatrix.copyFrom(this._scaleMatrix);
  62346. rotMatInv.copyFrom(this.getAbsoluteTransform());
  62347. if (mesh) {
  62348. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  62349. var meshScale = Bone._tmpMats[3];
  62350. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  62351. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  62352. }
  62353. rotMatInv.invert();
  62354. scaleMatrix.m[0] *= this._scalingDeterminant;
  62355. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62356. }
  62357. else {
  62358. rotMatInv.copyFrom(this.getLocalMatrix());
  62359. rotMatInv.invert();
  62360. var scaleMatrix = Bone._tmpMats[2];
  62361. scaleMatrix.copyFrom(this._scaleMatrix);
  62362. if (this._parent) {
  62363. var pscaleMatrix = Bone._tmpMats[3];
  62364. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  62365. pscaleMatrix.invert();
  62366. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  62367. }
  62368. else {
  62369. scaleMatrix.m[0] *= this._scalingDeterminant;
  62370. }
  62371. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62372. }
  62373. };
  62374. /**
  62375. * Get the scale of the bone
  62376. * @returns the scale of the bone
  62377. */
  62378. Bone.prototype.getScale = function () {
  62379. return this._scaleVector.clone();
  62380. };
  62381. /**
  62382. * Copy the scale of the bone to a vector3.
  62383. * @param result The vector3 to copy the scale to
  62384. */
  62385. Bone.prototype.getScaleToRef = function (result) {
  62386. result.copyFrom(this._scaleVector);
  62387. };
  62388. /**
  62389. * Get the position of the bone in local or world space.
  62390. * @param space The space that the returned position is in.
  62391. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62392. * @returns The position of the bone
  62393. */
  62394. Bone.prototype.getPosition = function (space, mesh) {
  62395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62396. if (mesh === void 0) { mesh = null; }
  62397. var pos = BABYLON.Vector3.Zero();
  62398. this.getPositionToRef(space, mesh, pos);
  62399. return pos;
  62400. };
  62401. /**
  62402. * Copy the position of the bone to a vector3 in local or world space.
  62403. * @param space The space that the returned position is in.
  62404. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62405. * @param result The vector3 to copy the position to.
  62406. */
  62407. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  62408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62409. if (space == BABYLON.Space.LOCAL) {
  62410. var lm = this.getLocalMatrix();
  62411. result.x = lm.m[12];
  62412. result.y = lm.m[13];
  62413. result.z = lm.m[14];
  62414. }
  62415. else {
  62416. var wm = null;
  62417. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62418. if (mesh) {
  62419. wm = mesh.getWorldMatrix();
  62420. }
  62421. this._skeleton.computeAbsoluteTransforms();
  62422. var tmat = Bone._tmpMats[0];
  62423. if (mesh && wm) {
  62424. tmat.copyFrom(this.getAbsoluteTransform());
  62425. tmat.multiplyToRef(wm, tmat);
  62426. }
  62427. else {
  62428. tmat = this.getAbsoluteTransform();
  62429. }
  62430. result.x = tmat.m[12];
  62431. result.y = tmat.m[13];
  62432. result.z = tmat.m[14];
  62433. }
  62434. };
  62435. /**
  62436. * Get the absolute position of the bone (world space).
  62437. * @param mesh The mesh that this bone is attached to.
  62438. * @returns The absolute position of the bone
  62439. */
  62440. Bone.prototype.getAbsolutePosition = function (mesh) {
  62441. if (mesh === void 0) { mesh = null; }
  62442. var pos = BABYLON.Vector3.Zero();
  62443. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  62444. return pos;
  62445. };
  62446. /**
  62447. * Copy the absolute position of the bone (world space) to the result param.
  62448. * @param mesh The mesh that this bone is attached to.
  62449. * @param result The vector3 to copy the absolute position to.
  62450. */
  62451. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  62452. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  62453. };
  62454. /**
  62455. * Compute the absolute transforms of this bone and its children.
  62456. */
  62457. Bone.prototype.computeAbsoluteTransforms = function () {
  62458. if (this._parent) {
  62459. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62460. }
  62461. else {
  62462. this._absoluteTransform.copyFrom(this._localMatrix);
  62463. var poseMatrix = this._skeleton.getPoseMatrix();
  62464. if (poseMatrix) {
  62465. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  62466. }
  62467. }
  62468. var children = this.children;
  62469. var len = children.length;
  62470. for (var i = 0; i < len; i++) {
  62471. children[i].computeAbsoluteTransforms();
  62472. }
  62473. };
  62474. Bone.prototype._syncScaleVector = function () {
  62475. var lm = this.getLocalMatrix();
  62476. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  62477. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62478. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62479. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62480. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62481. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62482. this._scaleVector.x = xs * Math.sqrt(xsq);
  62483. this._scaleVector.y = ys * Math.sqrt(ysq);
  62484. this._scaleVector.z = zs * Math.sqrt(zsq);
  62485. if (this._parent) {
  62486. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62487. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62488. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62489. }
  62490. 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);
  62491. };
  62492. /**
  62493. * Get the world direction from an axis that is in the local space of the bone.
  62494. * @param localAxis The local direction that is used to compute the world direction.
  62495. * @param mesh The mesh that this bone is attached to.
  62496. * @returns The world direction
  62497. */
  62498. Bone.prototype.getDirection = function (localAxis, mesh) {
  62499. if (mesh === void 0) { mesh = null; }
  62500. var result = BABYLON.Vector3.Zero();
  62501. this.getDirectionToRef(localAxis, mesh, result);
  62502. return result;
  62503. };
  62504. /**
  62505. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62506. * @param localAxis The local direction that is used to compute the world direction.
  62507. * @param mesh The mesh that this bone is attached to.
  62508. * @param result The vector3 that the world direction will be copied to.
  62509. */
  62510. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62511. if (mesh === void 0) { mesh = null; }
  62512. var wm = null;
  62513. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62514. if (mesh) {
  62515. wm = mesh.getWorldMatrix();
  62516. }
  62517. this._skeleton.computeAbsoluteTransforms();
  62518. var mat = Bone._tmpMats[0];
  62519. mat.copyFrom(this.getAbsoluteTransform());
  62520. if (mesh && wm) {
  62521. mat.multiplyToRef(wm, mat);
  62522. }
  62523. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62524. result.normalize();
  62525. };
  62526. /**
  62527. * Get the euler rotation of the bone in local or world space.
  62528. * @param space The space that the rotation should be in.
  62529. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62530. * @returns The euler rotation
  62531. */
  62532. Bone.prototype.getRotation = function (space, mesh) {
  62533. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62534. if (mesh === void 0) { mesh = null; }
  62535. var result = BABYLON.Vector3.Zero();
  62536. this.getRotationToRef(space, mesh, result);
  62537. return result;
  62538. };
  62539. /**
  62540. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62541. * @param space The space that the rotation should be in.
  62542. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62543. * @param result The vector3 that the rotation should be copied to.
  62544. */
  62545. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62546. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62547. if (mesh === void 0) { mesh = null; }
  62548. var quat = Bone._tmpQuat;
  62549. this.getRotationQuaternionToRef(space, mesh, quat);
  62550. quat.toEulerAnglesToRef(result);
  62551. };
  62552. /**
  62553. * Get the quaternion rotation of the bone in either local or world space.
  62554. * @param space The space that the rotation should be in.
  62555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62556. * @returns The quaternion rotation
  62557. */
  62558. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62560. if (mesh === void 0) { mesh = null; }
  62561. var result = BABYLON.Quaternion.Identity();
  62562. this.getRotationQuaternionToRef(space, mesh, result);
  62563. return result;
  62564. };
  62565. /**
  62566. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62567. * @param space The space that the rotation should be in.
  62568. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62569. * @param result The quaternion that the rotation should be copied to.
  62570. */
  62571. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62572. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62573. if (mesh === void 0) { mesh = null; }
  62574. if (space == BABYLON.Space.LOCAL) {
  62575. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62576. }
  62577. else {
  62578. var mat = Bone._tmpMats[0];
  62579. var amat = this.getAbsoluteTransform();
  62580. if (mesh) {
  62581. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62582. }
  62583. else {
  62584. mat.copyFrom(amat);
  62585. }
  62586. mat.m[0] *= this._scalingDeterminant;
  62587. mat.m[1] *= this._scalingDeterminant;
  62588. mat.m[2] *= this._scalingDeterminant;
  62589. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62590. }
  62591. };
  62592. /**
  62593. * Get the rotation matrix of the bone in local or world space.
  62594. * @param space The space that the rotation should be in.
  62595. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62596. * @returns The rotation matrix
  62597. */
  62598. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62599. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62600. var result = BABYLON.Matrix.Identity();
  62601. this.getRotationMatrixToRef(space, mesh, result);
  62602. return result;
  62603. };
  62604. /**
  62605. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62606. * @param space The space that the rotation should be in.
  62607. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62608. * @param result The quaternion that the rotation should be copied to.
  62609. */
  62610. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62611. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62612. if (space == BABYLON.Space.LOCAL) {
  62613. this.getLocalMatrix().getRotationMatrixToRef(result);
  62614. }
  62615. else {
  62616. var mat = Bone._tmpMats[0];
  62617. var amat = this.getAbsoluteTransform();
  62618. if (mesh) {
  62619. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62620. }
  62621. else {
  62622. mat.copyFrom(amat);
  62623. }
  62624. mat.m[0] *= this._scalingDeterminant;
  62625. mat.m[1] *= this._scalingDeterminant;
  62626. mat.m[2] *= this._scalingDeterminant;
  62627. mat.getRotationMatrixToRef(result);
  62628. }
  62629. };
  62630. /**
  62631. * Get the world position of a point that is in the local space of the bone.
  62632. * @param position The local position
  62633. * @param mesh The mesh that this bone is attached to.
  62634. * @returns The world position
  62635. */
  62636. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62637. if (mesh === void 0) { mesh = null; }
  62638. var result = BABYLON.Vector3.Zero();
  62639. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62640. return result;
  62641. };
  62642. /**
  62643. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62644. * @param position The local position
  62645. * @param mesh The mesh that this bone is attached to.
  62646. * @param result The vector3 that the world position should be copied to.
  62647. */
  62648. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62649. if (mesh === void 0) { mesh = null; }
  62650. var wm = null;
  62651. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62652. if (mesh) {
  62653. wm = mesh.getWorldMatrix();
  62654. }
  62655. this._skeleton.computeAbsoluteTransforms();
  62656. var tmat = Bone._tmpMats[0];
  62657. if (mesh && wm) {
  62658. tmat.copyFrom(this.getAbsoluteTransform());
  62659. tmat.multiplyToRef(wm, tmat);
  62660. }
  62661. else {
  62662. tmat = this.getAbsoluteTransform();
  62663. }
  62664. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62665. };
  62666. /**
  62667. * Get the local position of a point that is in world space.
  62668. * @param position The world position
  62669. * @param mesh The mesh that this bone is attached to.
  62670. * @returns The local position
  62671. */
  62672. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62673. if (mesh === void 0) { mesh = null; }
  62674. var result = BABYLON.Vector3.Zero();
  62675. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62676. return result;
  62677. };
  62678. /**
  62679. * Get the local position of a point that is in world space and copy it to the result param.
  62680. * @param position The world position
  62681. * @param mesh The mesh that this bone is attached to.
  62682. * @param result The vector3 that the local position should be copied to.
  62683. */
  62684. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62685. if (mesh === void 0) { mesh = null; }
  62686. var wm = null;
  62687. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62688. if (mesh) {
  62689. wm = mesh.getWorldMatrix();
  62690. }
  62691. this._skeleton.computeAbsoluteTransforms();
  62692. var tmat = Bone._tmpMats[0];
  62693. tmat.copyFrom(this.getAbsoluteTransform());
  62694. if (mesh && wm) {
  62695. tmat.multiplyToRef(wm, tmat);
  62696. }
  62697. tmat.invert();
  62698. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62699. };
  62700. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62701. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62702. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62703. return Bone;
  62704. }(BABYLON.Node));
  62705. BABYLON.Bone = Bone;
  62706. })(BABYLON || (BABYLON = {}));
  62707. //# sourceMappingURL=babylon.bone.js.map
  62708. var BABYLON;
  62709. (function (BABYLON) {
  62710. var BoneIKController = /** @class */ (function () {
  62711. function BoneIKController(mesh, bone, options) {
  62712. this.targetPosition = BABYLON.Vector3.Zero();
  62713. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62714. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62715. this.poleAngle = 0;
  62716. this.slerpAmount = 1;
  62717. this._bone1Quat = BABYLON.Quaternion.Identity();
  62718. this._bone1Mat = BABYLON.Matrix.Identity();
  62719. this._bone2Ang = Math.PI;
  62720. this._maxAngle = Math.PI;
  62721. this._rightHandedSystem = false;
  62722. this._bendAxis = BABYLON.Vector3.Right();
  62723. this._slerping = false;
  62724. this._adjustRoll = 0;
  62725. this._bone2 = bone;
  62726. this._bone1 = bone.getParent();
  62727. if (!this._bone1) {
  62728. return;
  62729. }
  62730. this.mesh = mesh;
  62731. var bonePos = bone.getPosition();
  62732. if (bone.getAbsoluteTransform().determinant() > 0) {
  62733. this._rightHandedSystem = true;
  62734. this._bendAxis.x = 0;
  62735. this._bendAxis.y = 0;
  62736. this._bendAxis.z = -1;
  62737. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62738. this._adjustRoll = Math.PI * .5;
  62739. this._bendAxis.z = 1;
  62740. }
  62741. }
  62742. if (this._bone1.length) {
  62743. var boneScale1 = this._bone1.getScale();
  62744. var boneScale2 = this._bone2.getScale();
  62745. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62746. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62747. }
  62748. else if (this._bone1.children[0]) {
  62749. mesh.computeWorldMatrix(true);
  62750. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62751. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62752. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62753. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62754. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62755. }
  62756. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62757. this.maxAngle = Math.PI;
  62758. if (options) {
  62759. if (options.targetMesh) {
  62760. this.targetMesh = options.targetMesh;
  62761. this.targetMesh.computeWorldMatrix(true);
  62762. }
  62763. if (options.poleTargetMesh) {
  62764. this.poleTargetMesh = options.poleTargetMesh;
  62765. this.poleTargetMesh.computeWorldMatrix(true);
  62766. }
  62767. else if (options.poleTargetBone) {
  62768. this.poleTargetBone = options.poleTargetBone;
  62769. }
  62770. else if (this._bone1.getParent()) {
  62771. this.poleTargetBone = this._bone1.getParent();
  62772. }
  62773. if (options.poleTargetLocalOffset) {
  62774. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62775. }
  62776. if (options.poleAngle) {
  62777. this.poleAngle = options.poleAngle;
  62778. }
  62779. if (options.bendAxis) {
  62780. this._bendAxis.copyFrom(options.bendAxis);
  62781. }
  62782. if (options.maxAngle) {
  62783. this.maxAngle = options.maxAngle;
  62784. }
  62785. if (options.slerpAmount) {
  62786. this.slerpAmount = options.slerpAmount;
  62787. }
  62788. }
  62789. }
  62790. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62791. get: function () {
  62792. return this._maxAngle;
  62793. },
  62794. set: function (value) {
  62795. this._setMaxAngle(value);
  62796. },
  62797. enumerable: true,
  62798. configurable: true
  62799. });
  62800. BoneIKController.prototype._setMaxAngle = function (ang) {
  62801. if (ang < 0) {
  62802. ang = 0;
  62803. }
  62804. if (ang > Math.PI || ang == undefined) {
  62805. ang = Math.PI;
  62806. }
  62807. this._maxAngle = ang;
  62808. var a = this._bone1Length;
  62809. var b = this._bone2Length;
  62810. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62811. };
  62812. BoneIKController.prototype.update = function () {
  62813. var bone1 = this._bone1;
  62814. if (!bone1) {
  62815. return;
  62816. }
  62817. var target = this.targetPosition;
  62818. var poleTarget = this.poleTargetPosition;
  62819. var mat1 = BoneIKController._tmpMats[0];
  62820. var mat2 = BoneIKController._tmpMats[1];
  62821. if (this.targetMesh) {
  62822. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62823. }
  62824. if (this.poleTargetBone) {
  62825. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62826. }
  62827. else if (this.poleTargetMesh) {
  62828. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62829. }
  62830. var bonePos = BoneIKController._tmpVecs[0];
  62831. var zaxis = BoneIKController._tmpVecs[1];
  62832. var xaxis = BoneIKController._tmpVecs[2];
  62833. var yaxis = BoneIKController._tmpVecs[3];
  62834. var upAxis = BoneIKController._tmpVecs[4];
  62835. var _tmpQuat = BoneIKController._tmpQuat;
  62836. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62837. poleTarget.subtractToRef(bonePos, upAxis);
  62838. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62839. upAxis.y = 1;
  62840. }
  62841. else {
  62842. upAxis.normalize();
  62843. }
  62844. target.subtractToRef(bonePos, yaxis);
  62845. yaxis.normalize();
  62846. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62847. zaxis.normalize();
  62848. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62849. xaxis.normalize();
  62850. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62851. var a = this._bone1Length;
  62852. var b = this._bone2Length;
  62853. var c = BABYLON.Vector3.Distance(bonePos, target);
  62854. if (this._maxReach > 0) {
  62855. c = Math.min(this._maxReach, c);
  62856. }
  62857. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62858. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62859. if (acosa > 1) {
  62860. acosa = 1;
  62861. }
  62862. if (acosb > 1) {
  62863. acosb = 1;
  62864. }
  62865. if (acosa < -1) {
  62866. acosa = -1;
  62867. }
  62868. if (acosb < -1) {
  62869. acosb = -1;
  62870. }
  62871. var angA = Math.acos(acosa);
  62872. var angB = Math.acos(acosb);
  62873. var angC = -angA - angB;
  62874. if (this._rightHandedSystem) {
  62875. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62876. mat2.multiplyToRef(mat1, mat1);
  62877. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62878. mat2.multiplyToRef(mat1, mat1);
  62879. }
  62880. else {
  62881. var _tmpVec = BoneIKController._tmpVecs[5];
  62882. _tmpVec.copyFrom(this._bendAxis);
  62883. _tmpVec.x *= -1;
  62884. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62885. mat2.multiplyToRef(mat1, mat1);
  62886. }
  62887. if (this.poleAngle) {
  62888. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62889. mat1.multiplyToRef(mat2, mat1);
  62890. }
  62891. if (this._bone1) {
  62892. if (this.slerpAmount < 1) {
  62893. if (!this._slerping) {
  62894. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62895. }
  62896. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62897. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62898. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62899. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62900. this._slerping = true;
  62901. }
  62902. else {
  62903. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62904. this._bone1Mat.copyFrom(mat1);
  62905. this._slerping = false;
  62906. }
  62907. }
  62908. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62909. this._bone2Ang = angC;
  62910. };
  62911. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62912. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62913. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62914. return BoneIKController;
  62915. }());
  62916. BABYLON.BoneIKController = BoneIKController;
  62917. })(BABYLON || (BABYLON = {}));
  62918. //# sourceMappingURL=babylon.boneIKController.js.map
  62919. var BABYLON;
  62920. (function (BABYLON) {
  62921. var BoneLookController = /** @class */ (function () {
  62922. /**
  62923. * Create a BoneLookController
  62924. * @param mesh the mesh that the bone belongs to
  62925. * @param bone the bone that will be looking to the target
  62926. * @param target the target Vector3 to look at
  62927. * @param settings optional settings:
  62928. * - maxYaw: the maximum angle the bone will yaw to
  62929. * - minYaw: the minimum angle the bone will yaw to
  62930. * - maxPitch: the maximum angle the bone will pitch to
  62931. * - minPitch: the minimum angle the bone will yaw to
  62932. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62933. * - upAxis: the up axis of the coordinate system
  62934. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62935. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62936. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62937. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62938. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62939. * - adjustRoll: used to make an adjustment to the roll of the bone
  62940. **/
  62941. function BoneLookController(mesh, bone, target, options) {
  62942. /**
  62943. * The up axis of the coordinate system that is used when the bone is rotated.
  62944. */
  62945. this.upAxis = BABYLON.Vector3.Up();
  62946. /**
  62947. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62948. */
  62949. this.upAxisSpace = BABYLON.Space.LOCAL;
  62950. /**
  62951. * Used to make an adjustment to the yaw of the bone.
  62952. */
  62953. this.adjustYaw = 0;
  62954. /**
  62955. * Used to make an adjustment to the pitch of the bone.
  62956. */
  62957. this.adjustPitch = 0;
  62958. /**
  62959. * Used to make an adjustment to the roll of the bone.
  62960. */
  62961. this.adjustRoll = 0;
  62962. /**
  62963. * 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).
  62964. */
  62965. this.slerpAmount = 1;
  62966. this._boneQuat = BABYLON.Quaternion.Identity();
  62967. this._slerping = false;
  62968. this._firstFrameSkipped = false;
  62969. this._fowardAxis = BABYLON.Vector3.Forward();
  62970. this.mesh = mesh;
  62971. this.bone = bone;
  62972. this.target = target;
  62973. if (options) {
  62974. if (options.adjustYaw) {
  62975. this.adjustYaw = options.adjustYaw;
  62976. }
  62977. if (options.adjustPitch) {
  62978. this.adjustPitch = options.adjustPitch;
  62979. }
  62980. if (options.adjustRoll) {
  62981. this.adjustRoll = options.adjustRoll;
  62982. }
  62983. if (options.maxYaw != null) {
  62984. this.maxYaw = options.maxYaw;
  62985. }
  62986. else {
  62987. this.maxYaw = Math.PI;
  62988. }
  62989. if (options.minYaw != null) {
  62990. this.minYaw = options.minYaw;
  62991. }
  62992. else {
  62993. this.minYaw = -Math.PI;
  62994. }
  62995. if (options.maxPitch != null) {
  62996. this.maxPitch = options.maxPitch;
  62997. }
  62998. else {
  62999. this.maxPitch = Math.PI;
  63000. }
  63001. if (options.minPitch != null) {
  63002. this.minPitch = options.minPitch;
  63003. }
  63004. else {
  63005. this.minPitch = -Math.PI;
  63006. }
  63007. if (options.slerpAmount != null) {
  63008. this.slerpAmount = options.slerpAmount;
  63009. }
  63010. if (options.upAxis != null) {
  63011. this.upAxis = options.upAxis;
  63012. }
  63013. if (options.upAxisSpace != null) {
  63014. this.upAxisSpace = options.upAxisSpace;
  63015. }
  63016. if (options.yawAxis != null || options.pitchAxis != null) {
  63017. var newYawAxis = BABYLON.Axis.Y;
  63018. var newPitchAxis = BABYLON.Axis.X;
  63019. if (options.yawAxis != null) {
  63020. newYawAxis = options.yawAxis.clone();
  63021. newYawAxis.normalize();
  63022. }
  63023. if (options.pitchAxis != null) {
  63024. newPitchAxis = options.pitchAxis.clone();
  63025. newPitchAxis.normalize();
  63026. }
  63027. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  63028. this._transformYawPitch = BABYLON.Matrix.Identity();
  63029. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  63030. this._transformYawPitchInv = this._transformYawPitch.clone();
  63031. this._transformYawPitch.invert();
  63032. }
  63033. }
  63034. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  63035. this.upAxisSpace = BABYLON.Space.LOCAL;
  63036. }
  63037. }
  63038. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  63039. /**
  63040. * Get/set the minimum yaw angle that the bone can look to.
  63041. */
  63042. get: function () {
  63043. return this._minYaw;
  63044. },
  63045. set: function (value) {
  63046. this._minYaw = value;
  63047. this._minYawSin = Math.sin(value);
  63048. this._minYawCos = Math.cos(value);
  63049. if (this._maxYaw != null) {
  63050. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63051. this._yawRange = this._maxYaw - this._minYaw;
  63052. }
  63053. },
  63054. enumerable: true,
  63055. configurable: true
  63056. });
  63057. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  63058. /**
  63059. * Get/set the maximum yaw angle that the bone can look to.
  63060. */
  63061. get: function () {
  63062. return this._maxYaw;
  63063. },
  63064. set: function (value) {
  63065. this._maxYaw = value;
  63066. this._maxYawSin = Math.sin(value);
  63067. this._maxYawCos = Math.cos(value);
  63068. if (this._minYaw != null) {
  63069. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63070. this._yawRange = this._maxYaw - this._minYaw;
  63071. }
  63072. },
  63073. enumerable: true,
  63074. configurable: true
  63075. });
  63076. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  63077. /**
  63078. * Get/set the minimum pitch angle that the bone can look to.
  63079. */
  63080. get: function () {
  63081. return this._minPitch;
  63082. },
  63083. set: function (value) {
  63084. this._minPitch = value;
  63085. this._minPitchTan = Math.tan(value);
  63086. },
  63087. enumerable: true,
  63088. configurable: true
  63089. });
  63090. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  63091. /**
  63092. * Get/set the maximum pitch angle that the bone can look to.
  63093. */
  63094. get: function () {
  63095. return this._maxPitch;
  63096. },
  63097. set: function (value) {
  63098. this._maxPitch = value;
  63099. this._maxPitchTan = Math.tan(value);
  63100. },
  63101. enumerable: true,
  63102. configurable: true
  63103. });
  63104. /**
  63105. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  63106. */
  63107. BoneLookController.prototype.update = function () {
  63108. //skip the first frame when slerping so that the mesh rotation is correct
  63109. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  63110. this._firstFrameSkipped = true;
  63111. return;
  63112. }
  63113. var bone = this.bone;
  63114. var bonePos = BoneLookController._tmpVecs[0];
  63115. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  63116. var target = this.target;
  63117. var _tmpMat1 = BoneLookController._tmpMats[0];
  63118. var _tmpMat2 = BoneLookController._tmpMats[1];
  63119. var mesh = this.mesh;
  63120. var parentBone = bone.getParent();
  63121. var upAxis = BoneLookController._tmpVecs[1];
  63122. upAxis.copyFrom(this.upAxis);
  63123. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  63124. if (this._transformYawPitch) {
  63125. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  63126. }
  63127. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  63128. }
  63129. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  63130. mesh.getDirectionToRef(upAxis, upAxis);
  63131. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  63132. upAxis.normalize();
  63133. }
  63134. }
  63135. var checkYaw = false;
  63136. var checkPitch = false;
  63137. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  63138. checkYaw = true;
  63139. }
  63140. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  63141. checkPitch = true;
  63142. }
  63143. if (checkYaw || checkPitch) {
  63144. var spaceMat = BoneLookController._tmpMats[2];
  63145. var spaceMatInv = BoneLookController._tmpMats[3];
  63146. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  63147. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  63148. }
  63149. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  63150. spaceMat.copyFrom(mesh.getWorldMatrix());
  63151. }
  63152. else {
  63153. var forwardAxis = BoneLookController._tmpVecs[2];
  63154. forwardAxis.copyFrom(this._fowardAxis);
  63155. if (this._transformYawPitch) {
  63156. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  63157. }
  63158. if (parentBone) {
  63159. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  63160. }
  63161. else {
  63162. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  63163. }
  63164. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  63165. rightAxis.normalize();
  63166. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  63167. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  63168. }
  63169. spaceMat.invertToRef(spaceMatInv);
  63170. var xzlen = null;
  63171. if (checkPitch) {
  63172. var localTarget = BoneLookController._tmpVecs[3];
  63173. target.subtractToRef(bonePos, localTarget);
  63174. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63175. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63176. var pitch = Math.atan2(localTarget.y, xzlen);
  63177. var newPitch = pitch;
  63178. if (pitch > this._maxPitch) {
  63179. localTarget.y = this._maxPitchTan * xzlen;
  63180. newPitch = this._maxPitch;
  63181. }
  63182. else if (pitch < this._minPitch) {
  63183. localTarget.y = this._minPitchTan * xzlen;
  63184. newPitch = this._minPitch;
  63185. }
  63186. if (pitch != newPitch) {
  63187. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63188. localTarget.addInPlace(bonePos);
  63189. target = localTarget;
  63190. }
  63191. }
  63192. if (checkYaw) {
  63193. var localTarget = BoneLookController._tmpVecs[4];
  63194. target.subtractToRef(bonePos, localTarget);
  63195. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63196. var yaw = Math.atan2(localTarget.x, localTarget.z);
  63197. var newYaw = yaw;
  63198. if (yaw > this._maxYaw || yaw < this._minYaw) {
  63199. if (xzlen == null) {
  63200. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63201. }
  63202. if (this._yawRange > Math.PI) {
  63203. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  63204. localTarget.z = this._maxYawCos * xzlen;
  63205. localTarget.x = this._maxYawSin * xzlen;
  63206. newYaw = this._maxYaw;
  63207. }
  63208. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  63209. localTarget.z = this._minYawCos * xzlen;
  63210. localTarget.x = this._minYawSin * xzlen;
  63211. newYaw = this._minYaw;
  63212. }
  63213. }
  63214. else {
  63215. if (yaw > this._maxYaw) {
  63216. localTarget.z = this._maxYawCos * xzlen;
  63217. localTarget.x = this._maxYawSin * xzlen;
  63218. newYaw = this._maxYaw;
  63219. }
  63220. else if (yaw < this._minYaw) {
  63221. localTarget.z = this._minYawCos * xzlen;
  63222. localTarget.x = this._minYawSin * xzlen;
  63223. newYaw = this._minYaw;
  63224. }
  63225. }
  63226. }
  63227. if (this._slerping && this._yawRange > Math.PI) {
  63228. //are we going to be crossing into the min/max region?
  63229. var boneFwd = BoneLookController._tmpVecs[8];
  63230. boneFwd.copyFrom(BABYLON.Axis.Z);
  63231. if (this._transformYawPitch) {
  63232. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  63233. }
  63234. var boneRotMat = BoneLookController._tmpMats[4];
  63235. this._boneQuat.toRotationMatrix(boneRotMat);
  63236. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  63237. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  63238. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  63239. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  63240. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  63241. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  63242. if (angBtwTar > angBtwMidYaw) {
  63243. if (xzlen == null) {
  63244. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63245. }
  63246. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  63247. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  63248. if (angBtwMin < angBtwMax) {
  63249. newYaw = boneYaw + Math.PI * .75;
  63250. localTarget.z = Math.cos(newYaw) * xzlen;
  63251. localTarget.x = Math.sin(newYaw) * xzlen;
  63252. }
  63253. else {
  63254. newYaw = boneYaw - Math.PI * .75;
  63255. localTarget.z = Math.cos(newYaw) * xzlen;
  63256. localTarget.x = Math.sin(newYaw) * xzlen;
  63257. }
  63258. }
  63259. }
  63260. if (yaw != newYaw) {
  63261. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63262. localTarget.addInPlace(bonePos);
  63263. target = localTarget;
  63264. }
  63265. }
  63266. }
  63267. var zaxis = BoneLookController._tmpVecs[5];
  63268. var xaxis = BoneLookController._tmpVecs[6];
  63269. var yaxis = BoneLookController._tmpVecs[7];
  63270. var _tmpQuat = BoneLookController._tmpQuat;
  63271. target.subtractToRef(bonePos, zaxis);
  63272. zaxis.normalize();
  63273. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  63274. xaxis.normalize();
  63275. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  63276. yaxis.normalize();
  63277. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  63278. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  63279. return;
  63280. }
  63281. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  63282. return;
  63283. }
  63284. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  63285. return;
  63286. }
  63287. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  63288. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  63289. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  63290. }
  63291. if (this.slerpAmount < 1) {
  63292. if (!this._slerping) {
  63293. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  63294. }
  63295. if (this._transformYawPitch) {
  63296. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63297. }
  63298. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  63299. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  63300. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  63301. this._slerping = true;
  63302. }
  63303. else {
  63304. if (this._transformYawPitch) {
  63305. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63306. }
  63307. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  63308. this._slerping = false;
  63309. }
  63310. };
  63311. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  63312. var angDiff = ang2 - ang1;
  63313. angDiff %= Math.PI * 2;
  63314. if (angDiff > Math.PI) {
  63315. angDiff -= Math.PI * 2;
  63316. }
  63317. else if (angDiff < -Math.PI) {
  63318. angDiff += Math.PI * 2;
  63319. }
  63320. return angDiff;
  63321. };
  63322. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  63323. ang1 %= (2 * Math.PI);
  63324. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63325. ang2 %= (2 * Math.PI);
  63326. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63327. var ab = 0;
  63328. if (ang1 < ang2) {
  63329. ab = ang2 - ang1;
  63330. }
  63331. else {
  63332. ab = ang1 - ang2;
  63333. }
  63334. if (ab > Math.PI) {
  63335. ab = Math.PI * 2 - ab;
  63336. }
  63337. return ab;
  63338. };
  63339. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  63340. ang %= (2 * Math.PI);
  63341. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  63342. ang1 %= (2 * Math.PI);
  63343. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63344. ang2 %= (2 * Math.PI);
  63345. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63346. if (ang1 < ang2) {
  63347. if (ang > ang1 && ang < ang2) {
  63348. return true;
  63349. }
  63350. }
  63351. else {
  63352. if (ang > ang2 && ang < ang1) {
  63353. return true;
  63354. }
  63355. }
  63356. return false;
  63357. };
  63358. 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()];
  63359. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  63360. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63361. return BoneLookController;
  63362. }());
  63363. BABYLON.BoneLookController = BoneLookController;
  63364. })(BABYLON || (BABYLON = {}));
  63365. //# sourceMappingURL=babylon.boneLookController.js.map
  63366. var BABYLON;
  63367. (function (BABYLON) {
  63368. var Skeleton = /** @class */ (function () {
  63369. function Skeleton(name, id, scene) {
  63370. this.name = name;
  63371. this.id = id;
  63372. this.bones = new Array();
  63373. this.needInitialSkinMatrix = false;
  63374. this._isDirty = true;
  63375. this._meshesWithPoseMatrix = new Array();
  63376. this._identity = BABYLON.Matrix.Identity();
  63377. this._ranges = {};
  63378. this._lastAbsoluteTransformsUpdateId = -1;
  63379. // Events
  63380. /**
  63381. * An event triggered before computing the skeleton's matrices
  63382. * @type {BABYLON.Observable}
  63383. */
  63384. this.onBeforeComputeObservable = new BABYLON.Observable();
  63385. this.bones = [];
  63386. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63387. scene.skeletons.push(this);
  63388. //make sure it will recalculate the matrix next time prepare is called.
  63389. this._isDirty = true;
  63390. }
  63391. // Members
  63392. Skeleton.prototype.getTransformMatrices = function (mesh) {
  63393. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  63394. return mesh._bonesTransformMatrices;
  63395. }
  63396. if (!this._transformMatrices) {
  63397. this.prepare();
  63398. }
  63399. return this._transformMatrices;
  63400. };
  63401. Skeleton.prototype.getScene = function () {
  63402. return this._scene;
  63403. };
  63404. // Methods
  63405. /**
  63406. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  63407. */
  63408. Skeleton.prototype.toString = function (fullDetails) {
  63409. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  63410. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  63411. if (fullDetails) {
  63412. ret += ", Ranges: {";
  63413. var first = true;
  63414. for (var name_1 in this._ranges) {
  63415. if (first) {
  63416. ret += ", ";
  63417. first = false;
  63418. }
  63419. ret += name_1;
  63420. }
  63421. ret += "}";
  63422. }
  63423. return ret;
  63424. };
  63425. /**
  63426. * Get bone's index searching by name
  63427. * @param {string} name is bone's name to search for
  63428. * @return {number} Indice of the bone. Returns -1 if not found
  63429. */
  63430. Skeleton.prototype.getBoneIndexByName = function (name) {
  63431. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  63432. if (this.bones[boneIndex].name === name) {
  63433. return boneIndex;
  63434. }
  63435. }
  63436. return -1;
  63437. };
  63438. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  63439. // check name not already in use
  63440. if (!this._ranges[name]) {
  63441. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  63442. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63443. if (this.bones[i].animations[0]) {
  63444. this.bones[i].animations[0].createRange(name, from, to);
  63445. }
  63446. }
  63447. }
  63448. };
  63449. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  63450. if (deleteFrames === void 0) { deleteFrames = true; }
  63451. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63452. if (this.bones[i].animations[0]) {
  63453. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  63454. }
  63455. }
  63456. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  63457. };
  63458. Skeleton.prototype.getAnimationRange = function (name) {
  63459. return this._ranges[name];
  63460. };
  63461. /**
  63462. * Returns as an Array, all AnimationRanges defined on this skeleton
  63463. */
  63464. Skeleton.prototype.getAnimationRanges = function () {
  63465. var animationRanges = [];
  63466. var name;
  63467. var i = 0;
  63468. for (name in this._ranges) {
  63469. animationRanges[i] = this._ranges[name];
  63470. i++;
  63471. }
  63472. return animationRanges;
  63473. };
  63474. /**
  63475. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  63476. */
  63477. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63478. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63479. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63480. return false;
  63481. }
  63482. var ret = true;
  63483. var frameOffset = this._getHighestAnimationFrame() + 1;
  63484. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63485. var boneDict = {};
  63486. var sourceBones = source.bones;
  63487. var nBones;
  63488. var i;
  63489. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63490. boneDict[sourceBones[i].name] = sourceBones[i];
  63491. }
  63492. if (this.bones.length !== sourceBones.length) {
  63493. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63494. ret = false;
  63495. }
  63496. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63497. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63498. var boneName = this.bones[i].name;
  63499. var sourceBone = boneDict[boneName];
  63500. if (sourceBone) {
  63501. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63502. }
  63503. else {
  63504. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63505. ret = false;
  63506. }
  63507. }
  63508. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63509. var range = source.getAnimationRange(name);
  63510. if (range) {
  63511. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63512. }
  63513. return ret;
  63514. };
  63515. Skeleton.prototype.returnToRest = function () {
  63516. for (var index = 0; index < this.bones.length; index++) {
  63517. this.bones[index].returnToRest();
  63518. }
  63519. };
  63520. Skeleton.prototype._getHighestAnimationFrame = function () {
  63521. var ret = 0;
  63522. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63523. if (this.bones[i].animations[0]) {
  63524. var highest = this.bones[i].animations[0].getHighestFrame();
  63525. if (ret < highest) {
  63526. ret = highest;
  63527. }
  63528. }
  63529. }
  63530. return ret;
  63531. };
  63532. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63533. var range = this.getAnimationRange(name);
  63534. if (!range) {
  63535. return null;
  63536. }
  63537. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63538. };
  63539. Skeleton.prototype._markAsDirty = function () {
  63540. this._isDirty = true;
  63541. };
  63542. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63543. this._meshesWithPoseMatrix.push(mesh);
  63544. };
  63545. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63546. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63547. if (index > -1) {
  63548. this._meshesWithPoseMatrix.splice(index, 1);
  63549. }
  63550. };
  63551. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63552. this.onBeforeComputeObservable.notifyObservers(this);
  63553. for (var index = 0; index < this.bones.length; index++) {
  63554. var bone = this.bones[index];
  63555. var parentBone = bone.getParent();
  63556. if (parentBone) {
  63557. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63558. }
  63559. else {
  63560. if (initialSkinMatrix) {
  63561. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63562. }
  63563. else {
  63564. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63565. }
  63566. }
  63567. if (bone._index !== -1) {
  63568. var mappedIndex = bone._index === null ? index : bone._index;
  63569. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63570. }
  63571. }
  63572. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63573. };
  63574. Skeleton.prototype.prepare = function () {
  63575. if (!this._isDirty) {
  63576. return;
  63577. }
  63578. if (this.needInitialSkinMatrix) {
  63579. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63580. var mesh = this._meshesWithPoseMatrix[index];
  63581. var poseMatrix = mesh.getPoseMatrix();
  63582. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63583. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63584. }
  63585. if (this._synchronizedWithMesh !== mesh) {
  63586. this._synchronizedWithMesh = mesh;
  63587. // Prepare bones
  63588. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63589. var bone = this.bones[boneIndex];
  63590. if (!bone.getParent()) {
  63591. var matrix = bone.getBaseMatrix();
  63592. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63593. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63594. }
  63595. }
  63596. }
  63597. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63598. }
  63599. }
  63600. else {
  63601. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63602. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63603. }
  63604. this._computeTransformMatrices(this._transformMatrices, null);
  63605. }
  63606. this._isDirty = false;
  63607. this._scene._activeBones.addCount(this.bones.length, false);
  63608. };
  63609. Skeleton.prototype.getAnimatables = function () {
  63610. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63611. this._animatables = [];
  63612. for (var index = 0; index < this.bones.length; index++) {
  63613. this._animatables.push(this.bones[index]);
  63614. }
  63615. }
  63616. return this._animatables;
  63617. };
  63618. Skeleton.prototype.clone = function (name, id) {
  63619. var result = new Skeleton(name, id || name, this._scene);
  63620. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63621. for (var index = 0; index < this.bones.length; index++) {
  63622. var source = this.bones[index];
  63623. var parentBone = null;
  63624. var parent_1 = source.getParent();
  63625. if (parent_1) {
  63626. var parentIndex = this.bones.indexOf(parent_1);
  63627. parentBone = result.bones[parentIndex];
  63628. }
  63629. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63630. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63631. }
  63632. if (this._ranges) {
  63633. result._ranges = {};
  63634. for (var rangeName in this._ranges) {
  63635. var range = this._ranges[rangeName];
  63636. if (range) {
  63637. result._ranges[rangeName] = range.clone();
  63638. }
  63639. }
  63640. }
  63641. this._isDirty = true;
  63642. return result;
  63643. };
  63644. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63645. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63646. this.bones.forEach(function (bone) {
  63647. bone.animations.forEach(function (animation) {
  63648. animation.enableBlending = true;
  63649. animation.blendingSpeed = blendingSpeed;
  63650. });
  63651. });
  63652. };
  63653. Skeleton.prototype.dispose = function () {
  63654. this._meshesWithPoseMatrix = [];
  63655. // Animations
  63656. this.getScene().stopAnimation(this);
  63657. // Remove from scene
  63658. this.getScene().removeSkeleton(this);
  63659. };
  63660. Skeleton.prototype.serialize = function () {
  63661. var serializationObject = {};
  63662. serializationObject.name = this.name;
  63663. serializationObject.id = this.id;
  63664. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63665. serializationObject.bones = [];
  63666. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63667. for (var index = 0; index < this.bones.length; index++) {
  63668. var bone = this.bones[index];
  63669. var parent_2 = bone.getParent();
  63670. var serializedBone = {
  63671. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63672. name: bone.name,
  63673. matrix: bone.getBaseMatrix().toArray(),
  63674. rest: bone.getRestPose().toArray()
  63675. };
  63676. serializationObject.bones.push(serializedBone);
  63677. if (bone.length) {
  63678. serializedBone.length = bone.length;
  63679. }
  63680. if (bone.animations && bone.animations.length > 0) {
  63681. serializedBone.animation = bone.animations[0].serialize();
  63682. }
  63683. serializationObject.ranges = [];
  63684. for (var name in this._ranges) {
  63685. var source = this._ranges[name];
  63686. if (!source) {
  63687. continue;
  63688. }
  63689. var range = {};
  63690. range.name = name;
  63691. range.from = source.from;
  63692. range.to = source.to;
  63693. serializationObject.ranges.push(range);
  63694. }
  63695. }
  63696. return serializationObject;
  63697. };
  63698. Skeleton.Parse = function (parsedSkeleton, scene) {
  63699. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63700. if (parsedSkeleton.dimensionsAtRest) {
  63701. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63702. }
  63703. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63704. var index;
  63705. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63706. var parsedBone = parsedSkeleton.bones[index];
  63707. var parentBone = null;
  63708. if (parsedBone.parentBoneIndex > -1) {
  63709. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63710. }
  63711. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63712. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63713. if (parsedBone.length) {
  63714. bone.length = parsedBone.length;
  63715. }
  63716. if (parsedBone.animation) {
  63717. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63718. }
  63719. }
  63720. // placed after bones, so createAnimationRange can cascade down
  63721. if (parsedSkeleton.ranges) {
  63722. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63723. var data = parsedSkeleton.ranges[index];
  63724. skeleton.createAnimationRange(data.name, data.from, data.to);
  63725. }
  63726. }
  63727. return skeleton;
  63728. };
  63729. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63730. if (forceUpdate === void 0) { forceUpdate = false; }
  63731. var renderId = this._scene.getRenderId();
  63732. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63733. this.bones[0].computeAbsoluteTransforms();
  63734. this._lastAbsoluteTransformsUpdateId = renderId;
  63735. }
  63736. };
  63737. Skeleton.prototype.getPoseMatrix = function () {
  63738. var poseMatrix = null;
  63739. if (this._meshesWithPoseMatrix.length > 0) {
  63740. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63741. }
  63742. return poseMatrix;
  63743. };
  63744. Skeleton.prototype.sortBones = function () {
  63745. var bones = new Array();
  63746. var visited = new Array(this.bones.length);
  63747. for (var index = 0; index < this.bones.length; index++) {
  63748. this._sortBones(index, bones, visited);
  63749. }
  63750. this.bones = bones;
  63751. };
  63752. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63753. if (visited[index]) {
  63754. return;
  63755. }
  63756. visited[index] = true;
  63757. var bone = this.bones[index];
  63758. if (bone._index === undefined) {
  63759. bone._index = index;
  63760. }
  63761. var parentBone = bone.getParent();
  63762. if (parentBone) {
  63763. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63764. }
  63765. bones.push(bone);
  63766. };
  63767. return Skeleton;
  63768. }());
  63769. BABYLON.Skeleton = Skeleton;
  63770. })(BABYLON || (BABYLON = {}));
  63771. //# sourceMappingURL=babylon.skeleton.js.map
  63772. var BABYLON;
  63773. (function (BABYLON) {
  63774. var SphericalPolynomial = /** @class */ (function () {
  63775. function SphericalPolynomial() {
  63776. this.x = BABYLON.Vector3.Zero();
  63777. this.y = BABYLON.Vector3.Zero();
  63778. this.z = BABYLON.Vector3.Zero();
  63779. this.xx = BABYLON.Vector3.Zero();
  63780. this.yy = BABYLON.Vector3.Zero();
  63781. this.zz = BABYLON.Vector3.Zero();
  63782. this.xy = BABYLON.Vector3.Zero();
  63783. this.yz = BABYLON.Vector3.Zero();
  63784. this.zx = BABYLON.Vector3.Zero();
  63785. }
  63786. SphericalPolynomial.prototype.addAmbient = function (color) {
  63787. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63788. this.xx = this.xx.add(colorVector);
  63789. this.yy = this.yy.add(colorVector);
  63790. this.zz = this.zz.add(colorVector);
  63791. };
  63792. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63793. var result = new SphericalPolynomial();
  63794. result.x = harmonics.L11.scale(1.02333);
  63795. result.y = harmonics.L1_1.scale(1.02333);
  63796. result.z = harmonics.L10.scale(1.02333);
  63797. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63798. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63799. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63800. result.yz = harmonics.L2_1.scale(0.858086);
  63801. result.zx = harmonics.L21.scale(0.858086);
  63802. result.xy = harmonics.L2_2.scale(0.858086);
  63803. result.scale(1.0 / Math.PI);
  63804. return result;
  63805. };
  63806. SphericalPolynomial.prototype.scale = function (scale) {
  63807. this.x = this.x.scale(scale);
  63808. this.y = this.y.scale(scale);
  63809. this.z = this.z.scale(scale);
  63810. this.xx = this.xx.scale(scale);
  63811. this.yy = this.yy.scale(scale);
  63812. this.zz = this.zz.scale(scale);
  63813. this.yz = this.yz.scale(scale);
  63814. this.zx = this.zx.scale(scale);
  63815. this.xy = this.xy.scale(scale);
  63816. };
  63817. return SphericalPolynomial;
  63818. }());
  63819. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63820. var SphericalHarmonics = /** @class */ (function () {
  63821. function SphericalHarmonics() {
  63822. this.L00 = BABYLON.Vector3.Zero();
  63823. this.L1_1 = BABYLON.Vector3.Zero();
  63824. this.L10 = BABYLON.Vector3.Zero();
  63825. this.L11 = BABYLON.Vector3.Zero();
  63826. this.L2_2 = BABYLON.Vector3.Zero();
  63827. this.L2_1 = BABYLON.Vector3.Zero();
  63828. this.L20 = BABYLON.Vector3.Zero();
  63829. this.L21 = BABYLON.Vector3.Zero();
  63830. this.L22 = BABYLON.Vector3.Zero();
  63831. }
  63832. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63833. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63834. var c = colorVector.scale(deltaSolidAngle);
  63835. this.L00 = this.L00.add(c.scale(0.282095));
  63836. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63837. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63838. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63839. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63840. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63841. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63842. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63843. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63844. };
  63845. SphericalHarmonics.prototype.scale = function (scale) {
  63846. this.L00 = this.L00.scale(scale);
  63847. this.L1_1 = this.L1_1.scale(scale);
  63848. this.L10 = this.L10.scale(scale);
  63849. this.L11 = this.L11.scale(scale);
  63850. this.L2_2 = this.L2_2.scale(scale);
  63851. this.L2_1 = this.L2_1.scale(scale);
  63852. this.L20 = this.L20.scale(scale);
  63853. this.L21 = this.L21.scale(scale);
  63854. this.L22 = this.L22.scale(scale);
  63855. };
  63856. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63857. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63858. //
  63859. // E_lm = A_l * L_lm
  63860. //
  63861. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63862. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63863. // the scaling factors are given in equation 9.
  63864. // Constant (Band 0)
  63865. this.L00 = this.L00.scale(3.141593);
  63866. // Linear (Band 1)
  63867. this.L1_1 = this.L1_1.scale(2.094395);
  63868. this.L10 = this.L10.scale(2.094395);
  63869. this.L11 = this.L11.scale(2.094395);
  63870. // Quadratic (Band 2)
  63871. this.L2_2 = this.L2_2.scale(0.785398);
  63872. this.L2_1 = this.L2_1.scale(0.785398);
  63873. this.L20 = this.L20.scale(0.785398);
  63874. this.L21 = this.L21.scale(0.785398);
  63875. this.L22 = this.L22.scale(0.785398);
  63876. };
  63877. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63878. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63879. // L = (1/pi) * E * rho
  63880. //
  63881. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63882. this.scale(1.0 / Math.PI);
  63883. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63884. // (The pixel shader must apply albedo after texture fetches, etc).
  63885. };
  63886. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63887. var result = new SphericalHarmonics();
  63888. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63889. result.L1_1 = polynomial.y.scale(0.977204);
  63890. result.L10 = polynomial.z.scale(0.977204);
  63891. result.L11 = polynomial.x.scale(0.977204);
  63892. result.L2_2 = polynomial.xy.scale(1.16538);
  63893. result.L2_1 = polynomial.yz.scale(1.16538);
  63894. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63895. result.L21 = polynomial.zx.scale(1.16538);
  63896. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63897. result.scale(Math.PI);
  63898. return result;
  63899. };
  63900. return SphericalHarmonics;
  63901. }());
  63902. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63903. })(BABYLON || (BABYLON = {}));
  63904. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63905. var BABYLON;
  63906. (function (BABYLON) {
  63907. var Internals;
  63908. (function (Internals) {
  63909. var FileFaceOrientation = /** @class */ (function () {
  63910. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63911. this.name = name;
  63912. this.worldAxisForNormal = worldAxisForNormal;
  63913. this.worldAxisForFileX = worldAxisForFileX;
  63914. this.worldAxisForFileY = worldAxisForFileY;
  63915. }
  63916. return FileFaceOrientation;
  63917. }());
  63918. ;
  63919. /**
  63920. * Helper class dealing with the extraction of spherical polynomial dataArray
  63921. * from a cube map.
  63922. */
  63923. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63924. function CubeMapToSphericalPolynomialTools() {
  63925. }
  63926. /**
  63927. * Converts a texture to the according Spherical Polynomial data.
  63928. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63929. *
  63930. * @param texture The texture to extract the information from.
  63931. * @return The Spherical Polynomial data.
  63932. */
  63933. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63934. if (!texture.isCube) {
  63935. // Only supports cube Textures currently.
  63936. return null;
  63937. }
  63938. var size = texture.getSize().width;
  63939. var right = texture.readPixels(0);
  63940. var left = texture.readPixels(1);
  63941. var up;
  63942. var down;
  63943. if (texture.isRenderTarget) {
  63944. up = texture.readPixels(3);
  63945. down = texture.readPixels(2);
  63946. }
  63947. else {
  63948. up = texture.readPixels(2);
  63949. down = texture.readPixels(3);
  63950. }
  63951. var front = texture.readPixels(4);
  63952. var back = texture.readPixels(5);
  63953. var gammaSpace = texture.gammaSpace;
  63954. // Always read as RGBA.
  63955. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63956. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63957. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63958. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63959. }
  63960. var cubeInfo = {
  63961. size: size,
  63962. right: right,
  63963. left: left,
  63964. up: up,
  63965. down: down,
  63966. front: front,
  63967. back: back,
  63968. format: format,
  63969. type: type,
  63970. gammaSpace: gammaSpace,
  63971. };
  63972. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63973. };
  63974. /**
  63975. * Converts a cubemap to the according Spherical Polynomial data.
  63976. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63977. *
  63978. * @param cubeInfo The Cube map to extract the information from.
  63979. * @return The Spherical Polynomial data.
  63980. */
  63981. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63982. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63983. var totalSolidAngle = 0.0;
  63984. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63985. var du = 2.0 / cubeInfo.size;
  63986. var dv = du;
  63987. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63988. var minUV = du * 0.5 - 1.0;
  63989. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63990. var fileFace = this.FileFaces[faceIndex];
  63991. var dataArray = cubeInfo[fileFace.name];
  63992. var v = minUV;
  63993. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63994. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63995. // Because SP is still linear, so summation is fine in that basis.
  63996. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63997. for (var y = 0; y < cubeInfo.size; y++) {
  63998. var u = minUV;
  63999. for (var x = 0; x < cubeInfo.size; x++) {
  64000. // World direction (not normalised)
  64001. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  64002. worldDirection.normalize();
  64003. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  64004. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  64005. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  64006. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  64007. // Handle Integer types.
  64008. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64009. r /= 255;
  64010. g /= 255;
  64011. b /= 255;
  64012. }
  64013. // Handle Gamma space textures.
  64014. if (cubeInfo.gammaSpace) {
  64015. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  64016. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  64017. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  64018. }
  64019. var color = new BABYLON.Color3(r, g, b);
  64020. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  64021. totalSolidAngle += deltaSolidAngle;
  64022. u += du;
  64023. }
  64024. v += dv;
  64025. }
  64026. }
  64027. // Solid angle for entire sphere is 4*pi
  64028. var sphereSolidAngle = 4.0 * Math.PI;
  64029. // Adjust the solid angle to allow for how many faces we processed.
  64030. var facesProcessed = 6.0;
  64031. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  64032. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  64033. // This is needed because the numerical integration over the cube uses a
  64034. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  64035. // and also to compensate for accumulative error due to float precision in the summation.
  64036. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  64037. sphericalHarmonics.scale(correctionFactor);
  64038. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  64039. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  64040. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  64041. };
  64042. CubeMapToSphericalPolynomialTools.FileFaces = [
  64043. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  64044. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  64045. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  64046. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  64047. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  64048. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  64049. ];
  64050. return CubeMapToSphericalPolynomialTools;
  64051. }());
  64052. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  64053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64054. })(BABYLON || (BABYLON = {}));
  64055. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  64056. var BABYLON;
  64057. (function (BABYLON) {
  64058. var Internals;
  64059. (function (Internals) {
  64060. /**
  64061. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  64062. */
  64063. var PanoramaToCubeMapTools = /** @class */ (function () {
  64064. function PanoramaToCubeMapTools() {
  64065. }
  64066. /**
  64067. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  64068. *
  64069. * @param float32Array The source data.
  64070. * @param inputWidth The width of the input panorama.
  64071. * @param inputhHeight The height of the input panorama.
  64072. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  64073. * @return The cubemap data
  64074. */
  64075. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  64076. if (!float32Array) {
  64077. throw "ConvertPanoramaToCubemap: input cannot be null";
  64078. }
  64079. if (float32Array.length != inputWidth * inputHeight * 3) {
  64080. throw "ConvertPanoramaToCubemap: input size is wrong";
  64081. }
  64082. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  64083. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  64084. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  64085. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  64086. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  64087. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  64088. return {
  64089. front: textureFront,
  64090. back: textureBack,
  64091. left: textureLeft,
  64092. right: textureRight,
  64093. up: textureUp,
  64094. down: textureDown,
  64095. size: size,
  64096. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  64097. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  64098. gammaSpace: false,
  64099. };
  64100. };
  64101. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  64102. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  64103. var textureArray = new Float32Array(buffer);
  64104. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  64105. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  64106. var dy = 1 / texSize;
  64107. var fy = 0;
  64108. for (var y = 0; y < texSize; y++) {
  64109. var xv1 = faceData[0];
  64110. var xv2 = faceData[2];
  64111. for (var x = 0; x < texSize; x++) {
  64112. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  64113. v.normalize();
  64114. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  64115. // 3 channels per pixels
  64116. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  64117. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  64118. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  64119. xv1 = xv1.add(rotDX1);
  64120. xv2 = xv2.add(rotDX2);
  64121. }
  64122. fy += dy;
  64123. }
  64124. return textureArray;
  64125. };
  64126. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  64127. var theta = Math.atan2(vDir.z, vDir.x);
  64128. var phi = Math.acos(vDir.y);
  64129. while (theta < -Math.PI)
  64130. theta += 2 * Math.PI;
  64131. while (theta > Math.PI)
  64132. theta -= 2 * Math.PI;
  64133. var dx = theta / Math.PI;
  64134. var dy = phi / Math.PI;
  64135. // recenter.
  64136. dx = dx * 0.5 + 0.5;
  64137. var px = Math.round(dx * inputWidth);
  64138. if (px < 0)
  64139. px = 0;
  64140. else if (px >= inputWidth)
  64141. px = inputWidth - 1;
  64142. var py = Math.round(dy * inputHeight);
  64143. if (py < 0)
  64144. py = 0;
  64145. else if (py >= inputHeight)
  64146. py = inputHeight - 1;
  64147. var inputY = (inputHeight - py - 1);
  64148. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  64149. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  64150. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  64151. return {
  64152. r: r,
  64153. g: g,
  64154. b: b
  64155. };
  64156. };
  64157. PanoramaToCubeMapTools.FACE_FRONT = [
  64158. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64159. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64160. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64161. new BABYLON.Vector3(1.0, 1.0, -1.0)
  64162. ];
  64163. PanoramaToCubeMapTools.FACE_BACK = [
  64164. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64165. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64166. new BABYLON.Vector3(1.0, 1.0, 1.0),
  64167. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  64168. ];
  64169. PanoramaToCubeMapTools.FACE_RIGHT = [
  64170. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64171. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64172. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64173. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64174. ];
  64175. PanoramaToCubeMapTools.FACE_LEFT = [
  64176. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64177. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64178. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64179. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  64180. ];
  64181. PanoramaToCubeMapTools.FACE_DOWN = [
  64182. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64183. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64184. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64185. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64186. ];
  64187. PanoramaToCubeMapTools.FACE_UP = [
  64188. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64189. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64190. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64191. new BABYLON.Vector3(1.0, -1.0, -1.0)
  64192. ];
  64193. return PanoramaToCubeMapTools;
  64194. }());
  64195. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  64196. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64197. })(BABYLON || (BABYLON = {}));
  64198. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  64199. var BABYLON;
  64200. (function (BABYLON) {
  64201. var Internals;
  64202. (function (Internals) {
  64203. ;
  64204. /**
  64205. * This groups tools to convert HDR texture to native colors array.
  64206. */
  64207. var HDRTools = /** @class */ (function () {
  64208. function HDRTools() {
  64209. }
  64210. HDRTools.Ldexp = function (mantissa, exponent) {
  64211. if (exponent > 1023) {
  64212. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  64213. }
  64214. if (exponent < -1074) {
  64215. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  64216. }
  64217. return mantissa * Math.pow(2, exponent);
  64218. };
  64219. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  64220. if (exponent > 0) {
  64221. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  64222. float32array[index + 0] = red * exponent;
  64223. float32array[index + 1] = green * exponent;
  64224. float32array[index + 2] = blue * exponent;
  64225. }
  64226. else {
  64227. float32array[index + 0] = 0;
  64228. float32array[index + 1] = 0;
  64229. float32array[index + 2] = 0;
  64230. }
  64231. };
  64232. HDRTools.readStringLine = function (uint8array, startIndex) {
  64233. var line = "";
  64234. var character = "";
  64235. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  64236. character = String.fromCharCode(uint8array[i]);
  64237. if (character == "\n") {
  64238. break;
  64239. }
  64240. line += character;
  64241. }
  64242. return line;
  64243. };
  64244. /**
  64245. * Reads header information from an RGBE texture stored in a native array.
  64246. * More information on this format are available here:
  64247. * https://en.wikipedia.org/wiki/RGBE_image_format
  64248. *
  64249. * @param uint8array The binary file stored in native array.
  64250. * @return The header information.
  64251. */
  64252. HDRTools.RGBE_ReadHeader = function (uint8array) {
  64253. var height = 0;
  64254. var width = 0;
  64255. var line = this.readStringLine(uint8array, 0);
  64256. if (line[0] != '#' || line[1] != '?') {
  64257. throw "Bad HDR Format.";
  64258. }
  64259. var endOfHeader = false;
  64260. var findFormat = false;
  64261. var lineIndex = 0;
  64262. do {
  64263. lineIndex += (line.length + 1);
  64264. line = this.readStringLine(uint8array, lineIndex);
  64265. if (line == "FORMAT=32-bit_rle_rgbe") {
  64266. findFormat = true;
  64267. }
  64268. else if (line.length == 0) {
  64269. endOfHeader = true;
  64270. }
  64271. } while (!endOfHeader);
  64272. if (!findFormat) {
  64273. throw "HDR Bad header format, unsupported FORMAT";
  64274. }
  64275. lineIndex += (line.length + 1);
  64276. line = this.readStringLine(uint8array, lineIndex);
  64277. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  64278. var match = sizeRegexp.exec(line);
  64279. // TODO. Support +Y and -X if needed.
  64280. if (!match || match.length < 3) {
  64281. throw "HDR Bad header format, no size";
  64282. }
  64283. width = parseInt(match[2]);
  64284. height = parseInt(match[1]);
  64285. if (width < 8 || width > 0x7fff) {
  64286. throw "HDR Bad header format, unsupported size";
  64287. }
  64288. lineIndex += (line.length + 1);
  64289. return {
  64290. height: height,
  64291. width: width,
  64292. dataPosition: lineIndex
  64293. };
  64294. };
  64295. /**
  64296. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  64297. * This RGBE texture needs to store the information as a panorama.
  64298. *
  64299. * More information on this format are available here:
  64300. * https://en.wikipedia.org/wiki/RGBE_image_format
  64301. *
  64302. * @param buffer The binary file stored in an array buffer.
  64303. * @param size The expected size of the extracted cubemap.
  64304. * @return The Cube Map information.
  64305. */
  64306. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  64307. var uint8array = new Uint8Array(buffer);
  64308. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  64309. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64310. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  64311. return cubeMapData;
  64312. };
  64313. /**
  64314. * Returns the pixels data extracted from an RGBE texture.
  64315. * This pixels will be stored left to right up to down in the R G B order in one array.
  64316. *
  64317. * More information on this format are available here:
  64318. * https://en.wikipedia.org/wiki/RGBE_image_format
  64319. *
  64320. * @param uint8array The binary file stored in an array buffer.
  64321. * @param hdrInfo The header information of the file.
  64322. * @return The pixels data in RGB right to left up to down order.
  64323. */
  64324. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  64325. // Keep for multi format supports.
  64326. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64327. };
  64328. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  64329. var num_scanlines = hdrInfo.height;
  64330. var scanline_width = hdrInfo.width;
  64331. var a, b, c, d, count;
  64332. var dataIndex = hdrInfo.dataPosition;
  64333. var index = 0, endIndex = 0, i = 0;
  64334. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  64335. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  64336. // 3 channels of 4 bytes per pixel in float.
  64337. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  64338. var resultArray = new Float32Array(resultBuffer);
  64339. // read in each successive scanline
  64340. while (num_scanlines > 0) {
  64341. a = uint8array[dataIndex++];
  64342. b = uint8array[dataIndex++];
  64343. c = uint8array[dataIndex++];
  64344. d = uint8array[dataIndex++];
  64345. if (a != 2 || b != 2 || (c & 0x80)) {
  64346. // this file is not run length encoded
  64347. throw "HDR Bad header format, not RLE";
  64348. }
  64349. if (((c << 8) | d) != scanline_width) {
  64350. throw "HDR Bad header format, wrong scan line width";
  64351. }
  64352. index = 0;
  64353. // read each of the four channels for the scanline into the buffer
  64354. for (i = 0; i < 4; i++) {
  64355. endIndex = (i + 1) * scanline_width;
  64356. while (index < endIndex) {
  64357. a = uint8array[dataIndex++];
  64358. b = uint8array[dataIndex++];
  64359. if (a > 128) {
  64360. // a run of the same value
  64361. count = a - 128;
  64362. if ((count == 0) || (count > endIndex - index)) {
  64363. throw "HDR Bad Format, bad scanline data (run)";
  64364. }
  64365. while (count-- > 0) {
  64366. scanLineArray[index++] = b;
  64367. }
  64368. }
  64369. else {
  64370. // a non-run
  64371. count = a;
  64372. if ((count == 0) || (count > endIndex - index)) {
  64373. throw "HDR Bad Format, bad scanline data (non-run)";
  64374. }
  64375. scanLineArray[index++] = b;
  64376. if (--count > 0) {
  64377. for (var j = 0; j < count; j++) {
  64378. scanLineArray[index++] = uint8array[dataIndex++];
  64379. }
  64380. }
  64381. }
  64382. }
  64383. }
  64384. // now convert data from buffer into floats
  64385. for (i = 0; i < scanline_width; i++) {
  64386. a = scanLineArray[i];
  64387. b = scanLineArray[i + scanline_width];
  64388. c = scanLineArray[i + 2 * scanline_width];
  64389. d = scanLineArray[i + 3 * scanline_width];
  64390. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  64391. }
  64392. num_scanlines--;
  64393. }
  64394. return resultArray;
  64395. };
  64396. return HDRTools;
  64397. }());
  64398. Internals.HDRTools = HDRTools;
  64399. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64400. })(BABYLON || (BABYLON = {}));
  64401. //# sourceMappingURL=babylon.hdr.js.map
  64402. var BABYLON;
  64403. (function (BABYLON) {
  64404. /**
  64405. * This represents a texture coming from an HDR input.
  64406. *
  64407. * The only supported format is currently panorama picture stored in RGBE format.
  64408. * Example of such files can be found on HDRLib: http://hdrlib.com/
  64409. */
  64410. var HDRCubeTexture = /** @class */ (function (_super) {
  64411. __extends(HDRCubeTexture, _super);
  64412. /**
  64413. * Instantiates an HDRTexture from the following parameters.
  64414. *
  64415. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  64416. * @param scene The scene the texture will be used in
  64417. * @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.
  64418. * @param noMipmap Forces to not generate the mipmap if true
  64419. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  64420. * @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)
  64421. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  64422. */
  64423. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  64424. if (noMipmap === void 0) { noMipmap = false; }
  64425. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64426. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64427. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64428. if (onLoad === void 0) { onLoad = null; }
  64429. if (onError === void 0) { onError = null; }
  64430. var _this = _super.call(this, scene) || this;
  64431. _this._useInGammaSpace = false;
  64432. _this._generateHarmonics = true;
  64433. _this._isBABYLONPreprocessed = false;
  64434. _this._onLoad = null;
  64435. _this._onError = null;
  64436. /**
  64437. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  64438. */
  64439. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64440. /**
  64441. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  64442. * This is usefull at run time to apply the good shader.
  64443. */
  64444. _this.isPMREM = false;
  64445. _this._isBlocking = true;
  64446. if (!url) {
  64447. return _this;
  64448. }
  64449. _this.name = url;
  64450. _this.url = url;
  64451. _this.hasAlpha = false;
  64452. _this.isCube = true;
  64453. _this._textureMatrix = BABYLON.Matrix.Identity();
  64454. _this._onLoad = onLoad;
  64455. _this._onError = onError;
  64456. _this.gammaSpace = false;
  64457. var caps = scene.getEngine().getCaps();
  64458. if (size) {
  64459. _this._isBABYLONPreprocessed = false;
  64460. _this._noMipmap = noMipmap;
  64461. _this._size = size;
  64462. _this._useInGammaSpace = useInGammaSpace;
  64463. _this._usePMREMGenerator = usePMREMGenerator &&
  64464. caps.textureLOD &&
  64465. caps.textureFloat &&
  64466. !_this._useInGammaSpace;
  64467. }
  64468. else {
  64469. _this._isBABYLONPreprocessed = true;
  64470. _this._noMipmap = false;
  64471. _this._useInGammaSpace = false;
  64472. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  64473. !_this._useInGammaSpace;
  64474. }
  64475. _this.isPMREM = _this._usePMREMGenerator;
  64476. _this._texture = _this._getFromCache(url, _this._noMipmap);
  64477. if (!_this._texture) {
  64478. if (!scene.useDelayedTextureLoading) {
  64479. _this.loadTexture();
  64480. }
  64481. else {
  64482. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64483. }
  64484. }
  64485. return _this;
  64486. }
  64487. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64488. /**
  64489. * Gets wether or not the texture is blocking during loading.
  64490. */
  64491. get: function () {
  64492. return this._isBlocking;
  64493. },
  64494. /**
  64495. * Sets wether or not the texture is blocking during loading.
  64496. */
  64497. set: function (value) {
  64498. this._isBlocking = value;
  64499. },
  64500. enumerable: true,
  64501. configurable: true
  64502. });
  64503. /**
  64504. * Occurs when the file is a preprocessed .babylon.hdr file.
  64505. */
  64506. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64507. var _this = this;
  64508. var mipLevels = 0;
  64509. var floatArrayView = null;
  64510. var scene = this.getScene();
  64511. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64512. var mips = new Array();
  64513. if (!floatArrayView) {
  64514. return mips;
  64515. }
  64516. var startIndex = 30;
  64517. for (var level = 0; level < mipLevels; level++) {
  64518. mips.push([]);
  64519. // Fill each pixel of the mip level.
  64520. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64521. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64522. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64523. mips[level].push(faceData);
  64524. startIndex += faceSize;
  64525. }
  64526. }
  64527. return mips;
  64528. } : null;
  64529. var callback = function (buffer) {
  64530. var scene = _this.getScene();
  64531. if (!scene) {
  64532. return null;
  64533. }
  64534. // Create Native Array Views
  64535. var intArrayView = new Int32Array(buffer);
  64536. floatArrayView = new Float32Array(buffer);
  64537. // Fill header.
  64538. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64539. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64540. // Update Texture Information.
  64541. if (!_this._texture) {
  64542. return null;
  64543. }
  64544. _this._texture.updateSize(_this._size, _this._size);
  64545. // Fill polynomial information.
  64546. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64547. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64548. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64549. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64550. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64551. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64552. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64553. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64554. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64555. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64556. _this.sphericalPolynomial = sphericalPolynomial;
  64557. // Fill pixel data.
  64558. mipLevels = intArrayView[29]; // Number of mip levels.
  64559. var startIndex = 30;
  64560. var data = [];
  64561. var faceSize = Math.pow(_this._size, 2) * 3;
  64562. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64563. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64564. startIndex += faceSize;
  64565. }
  64566. var results = [];
  64567. var byteArray = null;
  64568. // Push each faces.
  64569. for (var k = 0; k < 6; k++) {
  64570. var dataFace = null;
  64571. // To be deprecated.
  64572. if (version === 1) {
  64573. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64574. dataFace = data[j];
  64575. }
  64576. // If special cases.
  64577. if (!mipmapGenerator && dataFace) {
  64578. if (!scene.getEngine().getCaps().textureFloat) {
  64579. // 3 channels of 1 bytes per pixel in bytes.
  64580. var byteBuffer = new ArrayBuffer(faceSize);
  64581. byteArray = new Uint8Array(byteBuffer);
  64582. }
  64583. for (var i = 0; i < _this._size * _this._size; i++) {
  64584. // Put in gamma space if requested.
  64585. if (_this._useInGammaSpace) {
  64586. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64587. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64588. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64589. }
  64590. // Convert to int texture for fallback.
  64591. if (byteArray) {
  64592. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64593. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64594. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64595. // May use luminance instead if the result is not accurate.
  64596. var max = Math.max(Math.max(r, g), b);
  64597. if (max > 255) {
  64598. var scale = 255 / max;
  64599. r *= scale;
  64600. g *= scale;
  64601. b *= scale;
  64602. }
  64603. byteArray[(i * 3) + 0] = r;
  64604. byteArray[(i * 3) + 1] = g;
  64605. byteArray[(i * 3) + 2] = b;
  64606. }
  64607. }
  64608. }
  64609. // Fill the array accordingly.
  64610. if (byteArray) {
  64611. results.push(byteArray);
  64612. }
  64613. else {
  64614. results.push(dataFace);
  64615. }
  64616. }
  64617. return results;
  64618. };
  64619. if (scene) {
  64620. 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);
  64621. }
  64622. };
  64623. /**
  64624. * Occurs when the file is raw .hdr file.
  64625. */
  64626. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64627. var _this = this;
  64628. var callback = function (buffer) {
  64629. var scene = _this.getScene();
  64630. if (!scene) {
  64631. return null;
  64632. }
  64633. // Extract the raw linear data.
  64634. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64635. // Generate harmonics if needed.
  64636. if (_this._generateHarmonics) {
  64637. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64638. _this.sphericalPolynomial = sphericalPolynomial;
  64639. }
  64640. var results = [];
  64641. var byteArray = null;
  64642. // Push each faces.
  64643. for (var j = 0; j < 6; j++) {
  64644. // Create uintarray fallback.
  64645. if (!scene.getEngine().getCaps().textureFloat) {
  64646. // 3 channels of 1 bytes per pixel in bytes.
  64647. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64648. byteArray = new Uint8Array(byteBuffer);
  64649. }
  64650. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64651. // If special cases.
  64652. if (_this._useInGammaSpace || byteArray) {
  64653. for (var i = 0; i < _this._size * _this._size; i++) {
  64654. // Put in gamma space if requested.
  64655. if (_this._useInGammaSpace) {
  64656. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64657. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64658. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64659. }
  64660. // Convert to int texture for fallback.
  64661. if (byteArray) {
  64662. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64663. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64664. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64665. // May use luminance instead if the result is not accurate.
  64666. var max = Math.max(Math.max(r, g), b);
  64667. if (max > 255) {
  64668. var scale = 255 / max;
  64669. r *= scale;
  64670. g *= scale;
  64671. b *= scale;
  64672. }
  64673. byteArray[(i * 3) + 0] = r;
  64674. byteArray[(i * 3) + 1] = g;
  64675. byteArray[(i * 3) + 2] = b;
  64676. }
  64677. }
  64678. }
  64679. if (byteArray) {
  64680. results.push(byteArray);
  64681. }
  64682. else {
  64683. results.push(dataFace);
  64684. }
  64685. }
  64686. return results;
  64687. };
  64688. var mipmapGenerator = null;
  64689. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64690. // if (!this._noMipmap &&
  64691. // this._usePMREMGenerator) {
  64692. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64693. // // Custom setup of the generator matching with the PBR shader values.
  64694. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64695. // this._size,
  64696. // this._size,
  64697. // 0,
  64698. // 3,
  64699. // this.getScene().getEngine().getCaps().textureFloat,
  64700. // 2048,
  64701. // 0.25,
  64702. // false,
  64703. // true);
  64704. // return generator.filterCubeMap();
  64705. // };
  64706. // }
  64707. var scene = this.getScene();
  64708. if (scene) {
  64709. 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);
  64710. }
  64711. };
  64712. /**
  64713. * Starts the loading process of the texture.
  64714. */
  64715. HDRCubeTexture.prototype.loadTexture = function () {
  64716. if (this._isBABYLONPreprocessed) {
  64717. this.loadBabylonTexture();
  64718. }
  64719. else {
  64720. this.loadHDRTexture();
  64721. }
  64722. };
  64723. HDRCubeTexture.prototype.clone = function () {
  64724. var scene = this.getScene();
  64725. if (!scene) {
  64726. return this;
  64727. }
  64728. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64729. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64730. // Base texture
  64731. newTexture.level = this.level;
  64732. newTexture.wrapU = this.wrapU;
  64733. newTexture.wrapV = this.wrapV;
  64734. newTexture.coordinatesIndex = this.coordinatesIndex;
  64735. newTexture.coordinatesMode = this.coordinatesMode;
  64736. return newTexture;
  64737. };
  64738. // Methods
  64739. HDRCubeTexture.prototype.delayLoad = function () {
  64740. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64741. return;
  64742. }
  64743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64744. this._texture = this._getFromCache(this.url, this._noMipmap);
  64745. if (!this._texture) {
  64746. this.loadTexture();
  64747. }
  64748. };
  64749. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64750. return this._textureMatrix;
  64751. };
  64752. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64753. this._textureMatrix = value;
  64754. };
  64755. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64756. var texture = null;
  64757. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64758. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64759. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64760. texture.name = parsedTexture.name;
  64761. texture.hasAlpha = parsedTexture.hasAlpha;
  64762. texture.level = parsedTexture.level;
  64763. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64764. texture.isBlocking = parsedTexture.isBlocking;
  64765. }
  64766. return texture;
  64767. };
  64768. HDRCubeTexture.prototype.serialize = function () {
  64769. if (!this.name) {
  64770. return null;
  64771. }
  64772. var serializationObject = {};
  64773. serializationObject.name = this.name;
  64774. serializationObject.hasAlpha = this.hasAlpha;
  64775. serializationObject.isCube = true;
  64776. serializationObject.level = this.level;
  64777. serializationObject.size = this._size;
  64778. serializationObject.coordinatesMode = this.coordinatesMode;
  64779. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64780. serializationObject.generateHarmonics = this._generateHarmonics;
  64781. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64782. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64783. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64784. serializationObject.noMipmap = this._noMipmap;
  64785. serializationObject.isBlocking = this._isBlocking;
  64786. return serializationObject;
  64787. };
  64788. /**
  64789. * Saves as a file the data contained in the texture in a binary format.
  64790. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64791. * as the spherical used in the lighting.
  64792. * @param url The HDR file url.
  64793. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64794. * @param onError Method called if any error happens during download.
  64795. * @return The packed binary data.
  64796. */
  64797. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64798. if (onError === void 0) { onError = null; }
  64799. var callback = function (buffer) {
  64800. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64801. // Returns a URL you can use as a href.
  64802. var objUrl = window.URL.createObjectURL(data);
  64803. // Simulates a link to it and click to dowload.
  64804. var a = document.createElement("a");
  64805. document.body.appendChild(a);
  64806. a.style.display = "none";
  64807. a.href = objUrl;
  64808. a.download = "envmap.babylon.hdr";
  64809. a.click();
  64810. };
  64811. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64812. };
  64813. /**
  64814. * Serializes the data contained in the texture in a binary format.
  64815. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64816. * as the spherical used in the lighting.
  64817. * @param url The HDR file url.
  64818. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64819. * @param onError Method called if any error happens during download.
  64820. * @return The packed binary data.
  64821. */
  64822. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64823. if (onError === void 0) { onError = null; }
  64824. // Needs the url tho create the texture.
  64825. if (!url) {
  64826. return;
  64827. }
  64828. // Check Power of two size.
  64829. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64830. return;
  64831. }
  64832. // Coming Back in 3.x.
  64833. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  64834. };
  64835. HDRCubeTexture._facesMapping = [
  64836. "right",
  64837. "left",
  64838. "up",
  64839. "down",
  64840. "front",
  64841. "back"
  64842. ];
  64843. return HDRCubeTexture;
  64844. }(BABYLON.BaseTexture));
  64845. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64846. })(BABYLON || (BABYLON = {}));
  64847. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64848. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64849. // Huge respect for a such great lib.
  64850. // Earcut license:
  64851. // Copyright (c) 2016, Mapbox
  64852. //
  64853. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64854. // with or without fee is hereby granted, provided that the above copyright notice
  64855. // and this permission notice appear in all copies.
  64856. //
  64857. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64858. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64859. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64860. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64861. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64862. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64863. // THIS SOFTWARE.
  64864. var Earcut;
  64865. (function (Earcut) {
  64866. /**
  64867. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64868. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64869. * @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).
  64870. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64871. */
  64872. function earcut(data, holeIndices, dim) {
  64873. dim = dim || 2;
  64874. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64875. if (!outerNode)
  64876. return triangles;
  64877. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64878. if (hasHoles)
  64879. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64880. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64881. if (data.length > 80 * dim) {
  64882. minX = maxX = data[0];
  64883. minY = maxY = data[1];
  64884. for (var i = dim; i < outerLen; i += dim) {
  64885. x = data[i];
  64886. y = data[i + 1];
  64887. if (x < minX)
  64888. minX = x;
  64889. if (y < minY)
  64890. minY = y;
  64891. if (x > maxX)
  64892. maxX = x;
  64893. if (y > maxY)
  64894. maxY = y;
  64895. }
  64896. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64897. size = Math.max(maxX - minX, maxY - minY);
  64898. }
  64899. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64900. return triangles;
  64901. }
  64902. Earcut.earcut = earcut;
  64903. var Node = /** @class */ (function () {
  64904. function Node(i, x, y) {
  64905. this.i = i;
  64906. this.x = x;
  64907. this.y = y;
  64908. this.prev = null;
  64909. this.next = null;
  64910. this.z = null;
  64911. this.prevZ = null;
  64912. this.nextZ = null;
  64913. this.steiner = false;
  64914. }
  64915. return Node;
  64916. }());
  64917. // create a circular doubly linked list from polygon points in the specified winding order
  64918. function linkedList(data, start, end, dim, clockwise) {
  64919. var i, last = null;
  64920. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64921. for (i = start; i < end; i += dim)
  64922. last = insertNode(i, data[i], data[i + 1], last);
  64923. }
  64924. else {
  64925. for (i = end - dim; i >= start; i -= dim)
  64926. last = insertNode(i, data[i], data[i + 1], last);
  64927. }
  64928. if (last && equals(last, last.next)) {
  64929. removeNode(last);
  64930. last = last.next;
  64931. }
  64932. return last;
  64933. }
  64934. // eliminate colinear or duplicate points
  64935. function filterPoints(start, end) {
  64936. if (!start)
  64937. return start;
  64938. if (!end)
  64939. end = start;
  64940. var p = start, again;
  64941. do {
  64942. again = false;
  64943. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64944. removeNode(p);
  64945. p = end = p.prev;
  64946. if (p === p.next)
  64947. return undefined;
  64948. again = true;
  64949. }
  64950. else {
  64951. p = p.next;
  64952. }
  64953. } while (again || p !== end);
  64954. return end;
  64955. }
  64956. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64957. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64958. if (!ear)
  64959. return;
  64960. // interlink polygon nodes in z-order
  64961. if (!pass && size)
  64962. indexCurve(ear, minX, minY, size);
  64963. var stop = ear, prev, next;
  64964. // iterate through ears, slicing them one by one
  64965. while (ear.prev !== ear.next) {
  64966. prev = ear.prev;
  64967. next = ear.next;
  64968. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64969. // cut off the triangle
  64970. triangles.push(prev.i / dim);
  64971. triangles.push(ear.i / dim);
  64972. triangles.push(next.i / dim);
  64973. removeNode(ear);
  64974. // skipping the next vertice leads to less sliver triangles
  64975. ear = next.next;
  64976. stop = next.next;
  64977. continue;
  64978. }
  64979. ear = next;
  64980. // if we looped through the whole remaining polygon and can't find any more ears
  64981. if (ear === stop) {
  64982. // try filtering points and slicing again
  64983. if (!pass) {
  64984. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64985. // if this didn't work, try curing all small self-intersections locally
  64986. }
  64987. else if (pass === 1) {
  64988. ear = cureLocalIntersections(ear, triangles, dim);
  64989. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64990. // as a last resort, try splitting the remaining polygon into two
  64991. }
  64992. else if (pass === 2) {
  64993. splitEarcut(ear, triangles, dim, minX, minY, size);
  64994. }
  64995. break;
  64996. }
  64997. }
  64998. }
  64999. // check whether a polygon node forms a valid ear with adjacent nodes
  65000. function isEar(ear) {
  65001. var a = ear.prev, b = ear, c = ear.next;
  65002. if (area(a, b, c) >= 0)
  65003. return false; // reflex, can't be an ear
  65004. // now make sure we don't have other points inside the potential ear
  65005. var p = ear.next.next;
  65006. while (p !== ear.prev) {
  65007. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65008. area(p.prev, p, p.next) >= 0)
  65009. return false;
  65010. p = p.next;
  65011. }
  65012. return true;
  65013. }
  65014. function isEarHashed(ear, minX, minY, size) {
  65015. var a = ear.prev, b = ear, c = ear.next;
  65016. if (area(a, b, c) >= 0)
  65017. return false; // reflex, can't be an ear
  65018. // triangle bbox; min & max are calculated like this for speed
  65019. 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);
  65020. // z-order range for the current triangle bbox;
  65021. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  65022. // first look for points inside the triangle in increasing z-order
  65023. var p = ear.nextZ;
  65024. while (p && p.z <= maxZ) {
  65025. if (p !== ear.prev &&
  65026. p !== ear.next &&
  65027. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65028. area(p.prev, p, p.next) >= 0)
  65029. return false;
  65030. p = p.nextZ;
  65031. }
  65032. // then look for points in decreasing z-order
  65033. p = ear.prevZ;
  65034. while (p && p.z >= minZ) {
  65035. if (p !== ear.prev &&
  65036. p !== ear.next &&
  65037. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65038. area(p.prev, p, p.next) >= 0)
  65039. return false;
  65040. p = p.prevZ;
  65041. }
  65042. return true;
  65043. }
  65044. // go through all polygon nodes and cure small local self-intersections
  65045. function cureLocalIntersections(start, triangles, dim) {
  65046. var p = start;
  65047. do {
  65048. var a = p.prev, b = p.next.next;
  65049. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  65050. triangles.push(a.i / dim);
  65051. triangles.push(p.i / dim);
  65052. triangles.push(b.i / dim);
  65053. // remove two nodes involved
  65054. removeNode(p);
  65055. removeNode(p.next);
  65056. p = start = b;
  65057. }
  65058. p = p.next;
  65059. } while (p !== start);
  65060. return p;
  65061. }
  65062. // try splitting polygon into two and triangulate them independently
  65063. function splitEarcut(start, triangles, dim, minX, minY, size) {
  65064. // look for a valid diagonal that divides the polygon into two
  65065. var a = start;
  65066. do {
  65067. var b = a.next.next;
  65068. while (b !== a.prev) {
  65069. if (a.i !== b.i && isValidDiagonal(a, b)) {
  65070. // split the polygon in two by the diagonal
  65071. var c = splitPolygon(a, b);
  65072. // filter colinear points around the cuts
  65073. a = filterPoints(a, a.next);
  65074. c = filterPoints(c, c.next);
  65075. // run earcut on each half
  65076. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  65077. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  65078. return;
  65079. }
  65080. b = b.next;
  65081. }
  65082. a = a.next;
  65083. } while (a !== start);
  65084. }
  65085. // link every hole into the outer loop, producing a single-ring polygon without holes
  65086. function eliminateHoles(data, holeIndices, outerNode, dim) {
  65087. var queue = [], i, len, start, end, list;
  65088. for (i = 0, len = holeIndices.length; i < len; i++) {
  65089. start = holeIndices[i] * dim;
  65090. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65091. list = linkedList(data, start, end, dim, false);
  65092. if (list === list.next)
  65093. list.steiner = true;
  65094. queue.push(getLeftmost(list));
  65095. }
  65096. queue.sort(compareX);
  65097. // process holes from left to right
  65098. for (i = 0; i < queue.length; i++) {
  65099. eliminateHole(queue[i], outerNode);
  65100. outerNode = filterPoints(outerNode, outerNode.next);
  65101. }
  65102. return outerNode;
  65103. }
  65104. function compareX(a, b) {
  65105. return a.x - b.x;
  65106. }
  65107. // find a bridge between vertices that connects hole with an outer ring and and link it
  65108. function eliminateHole(hole, outerNode) {
  65109. outerNode = findHoleBridge(hole, outerNode);
  65110. if (outerNode) {
  65111. var b = splitPolygon(outerNode, hole);
  65112. filterPoints(b, b.next);
  65113. }
  65114. }
  65115. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  65116. function findHoleBridge(hole, outerNode) {
  65117. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  65118. // find a segment intersected by a ray from the hole's leftmost point to the left;
  65119. // segment's endpoint with lesser x will be potential connection point
  65120. do {
  65121. if (hy <= p.y && hy >= p.next.y) {
  65122. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  65123. if (x <= hx && x > qx) {
  65124. qx = x;
  65125. if (x === hx) {
  65126. if (hy === p.y)
  65127. return p;
  65128. if (hy === p.next.y)
  65129. return p.next;
  65130. }
  65131. m = p.x < p.next.x ? p : p.next;
  65132. }
  65133. }
  65134. p = p.next;
  65135. } while (p !== outerNode);
  65136. if (!m)
  65137. return null;
  65138. if (hx === qx)
  65139. return m.prev; // hole touches outer segment; pick lower endpoint
  65140. // look for points inside the triangle of hole point, segment intersection and endpoint;
  65141. // if there are no points found, we have a valid connection;
  65142. // otherwise choose the point of the minimum angle with the ray as connection point
  65143. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  65144. p = m.next;
  65145. while (p !== stop) {
  65146. if (hx >= p.x &&
  65147. p.x >= mx &&
  65148. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  65149. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  65150. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  65151. m = p;
  65152. tanMin = tan;
  65153. }
  65154. }
  65155. p = p.next;
  65156. }
  65157. return m;
  65158. }
  65159. // interlink polygon nodes in z-order
  65160. function indexCurve(start, minX, minY, size) {
  65161. var p = start;
  65162. do {
  65163. if (p.z === null)
  65164. p.z = zOrder(p.x, p.y, minX, minY, size);
  65165. p.prevZ = p.prev;
  65166. p.nextZ = p.next;
  65167. p = p.next;
  65168. } while (p !== start);
  65169. p.prevZ.nextZ = null;
  65170. p.prevZ = null;
  65171. sortLinked(p);
  65172. }
  65173. // Simon Tatham's linked list merge sort algorithm
  65174. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  65175. function sortLinked(list) {
  65176. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  65177. do {
  65178. p = list;
  65179. list = null;
  65180. tail = null;
  65181. numMerges = 0;
  65182. while (p) {
  65183. numMerges++;
  65184. q = p;
  65185. pSize = 0;
  65186. for (i = 0; i < inSize; i++) {
  65187. pSize++;
  65188. q = q.nextZ;
  65189. if (!q)
  65190. break;
  65191. }
  65192. qSize = inSize;
  65193. while (pSize > 0 || (qSize > 0 && q)) {
  65194. if (pSize === 0) {
  65195. e = q;
  65196. q = q.nextZ;
  65197. qSize--;
  65198. }
  65199. else if (qSize === 0 || !q) {
  65200. e = p;
  65201. p = p.nextZ;
  65202. pSize--;
  65203. }
  65204. else if (p.z <= q.z) {
  65205. e = p;
  65206. p = p.nextZ;
  65207. pSize--;
  65208. }
  65209. else {
  65210. e = q;
  65211. q = q.nextZ;
  65212. qSize--;
  65213. }
  65214. if (tail)
  65215. tail.nextZ = e;
  65216. else
  65217. list = e;
  65218. e.prevZ = tail;
  65219. tail = e;
  65220. }
  65221. p = q;
  65222. }
  65223. tail.nextZ = null;
  65224. inSize *= 2;
  65225. } while (numMerges > 1);
  65226. return list;
  65227. }
  65228. // z-order of a point given coords and size of the data bounding box
  65229. function zOrder(x, y, minX, minY, size) {
  65230. // coords are transformed into non-negative 15-bit integer range
  65231. x = 32767 * (x - minX) / size;
  65232. y = 32767 * (y - minY) / size;
  65233. x = (x | (x << 8)) & 0x00FF00FF;
  65234. x = (x | (x << 4)) & 0x0F0F0F0F;
  65235. x = (x | (x << 2)) & 0x33333333;
  65236. x = (x | (x << 1)) & 0x55555555;
  65237. y = (y | (y << 8)) & 0x00FF00FF;
  65238. y = (y | (y << 4)) & 0x0F0F0F0F;
  65239. y = (y | (y << 2)) & 0x33333333;
  65240. y = (y | (y << 1)) & 0x55555555;
  65241. return x | (y << 1);
  65242. }
  65243. // find the leftmost node of a polygon ring
  65244. function getLeftmost(start) {
  65245. var p = start, leftmost = start;
  65246. do {
  65247. if (p.x < leftmost.x)
  65248. leftmost = p;
  65249. p = p.next;
  65250. } while (p !== start);
  65251. return leftmost;
  65252. }
  65253. // check if a point lies within a convex triangle
  65254. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  65255. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  65256. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  65257. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  65258. }
  65259. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  65260. function isValidDiagonal(a, b) {
  65261. return a.next.i !== b.i &&
  65262. a.prev.i !== b.i &&
  65263. !intersectsPolygon(a, b) &&
  65264. locallyInside(a, b) &&
  65265. locallyInside(b, a) &&
  65266. middleInside(a, b);
  65267. }
  65268. // signed area of a triangle
  65269. function area(p, q, r) {
  65270. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  65271. }
  65272. // check if two points are equal
  65273. function equals(p1, p2) {
  65274. return p1.x === p2.x && p1.y === p2.y;
  65275. }
  65276. // check if two segments intersect
  65277. function intersects(p1, q1, p2, q2) {
  65278. if ((equals(p1, q1) && equals(p2, q2)) ||
  65279. (equals(p1, q2) && equals(p2, q1)))
  65280. return true;
  65281. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  65282. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  65283. }
  65284. // check if a polygon diagonal intersects any polygon segments
  65285. function intersectsPolygon(a, b) {
  65286. var p = a;
  65287. do {
  65288. if (p.i !== a.i &&
  65289. p.next.i !== a.i &&
  65290. p.i !== b.i &&
  65291. p.next.i !== b.i &&
  65292. intersects(p, p.next, a, b))
  65293. return true;
  65294. p = p.next;
  65295. } while (p !== a);
  65296. return false;
  65297. }
  65298. // check if a polygon diagonal is locally inside the polygon
  65299. function locallyInside(a, b) {
  65300. return area(a.prev, a, a.next) < 0
  65301. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  65302. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  65303. }
  65304. // check if the middle point of a polygon diagonal is inside the polygon
  65305. function middleInside(a, b) {
  65306. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  65307. do {
  65308. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  65309. inside = !inside;
  65310. p = p.next;
  65311. } while (p !== a);
  65312. return inside;
  65313. }
  65314. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  65315. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  65316. function splitPolygon(a, b) {
  65317. 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;
  65318. a.next = b;
  65319. b.prev = a;
  65320. a2.next = an;
  65321. an.prev = a2;
  65322. b2.next = a2;
  65323. a2.prev = b2;
  65324. bp.next = b2;
  65325. b2.prev = bp;
  65326. return b2;
  65327. }
  65328. // create a node and optionally link it with previous one (in a circular doubly linked list)
  65329. function insertNode(i, x, y, last) {
  65330. var p = new Node(i, x, y);
  65331. if (!last) {
  65332. p.prev = p;
  65333. p.next = p;
  65334. }
  65335. else {
  65336. p.next = last.next;
  65337. p.prev = last;
  65338. last.next.prev = p;
  65339. last.next = p;
  65340. }
  65341. return p;
  65342. }
  65343. function removeNode(p) {
  65344. p.next.prev = p.prev;
  65345. p.prev.next = p.next;
  65346. if (p.prevZ)
  65347. p.prevZ.nextZ = p.nextZ;
  65348. if (p.nextZ)
  65349. p.nextZ.prevZ = p.prevZ;
  65350. }
  65351. /**
  65352. * return a percentage difference between the polygon area and its triangulation area;
  65353. * used to verify correctness of triangulation
  65354. */
  65355. function deviation(data, holeIndices, dim, triangles) {
  65356. var hasHoles = holeIndices && holeIndices.length;
  65357. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  65358. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  65359. if (hasHoles) {
  65360. for (var i = 0, len = holeIndices.length; i < len; i++) {
  65361. var start = holeIndices[i] * dim;
  65362. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65363. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  65364. }
  65365. }
  65366. var trianglesArea = 0;
  65367. for (i = 0; i < triangles.length; i += 3) {
  65368. var a = triangles[i] * dim;
  65369. var b = triangles[i + 1] * dim;
  65370. var c = triangles[i + 2] * dim;
  65371. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  65372. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  65373. }
  65374. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  65375. }
  65376. Earcut.deviation = deviation;
  65377. ;
  65378. function signedArea(data, start, end, dim) {
  65379. var sum = 0;
  65380. for (var i = start, j = end - dim; i < end; i += dim) {
  65381. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  65382. j = i;
  65383. }
  65384. return sum;
  65385. }
  65386. /**
  65387. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  65388. */
  65389. function flatten(data) {
  65390. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  65391. for (var i = 0; i < data.length; i++) {
  65392. for (var j = 0; j < data[i].length; j++) {
  65393. for (var d = 0; d < dim; d++)
  65394. result.vertices.push(data[i][j][d]);
  65395. }
  65396. if (i > 0) {
  65397. holeIndex += data[i - 1].length;
  65398. result.holes.push(holeIndex);
  65399. }
  65400. }
  65401. return result;
  65402. }
  65403. Earcut.flatten = flatten;
  65404. ;
  65405. })(Earcut || (Earcut = {}));
  65406. //# sourceMappingURL=babylon.earcut.js.map
  65407. var BABYLON;
  65408. (function (BABYLON) {
  65409. var IndexedVector2 = /** @class */ (function (_super) {
  65410. __extends(IndexedVector2, _super);
  65411. function IndexedVector2(original, index) {
  65412. var _this = _super.call(this, original.x, original.y) || this;
  65413. _this.index = index;
  65414. return _this;
  65415. }
  65416. return IndexedVector2;
  65417. }(BABYLON.Vector2));
  65418. var PolygonPoints = /** @class */ (function () {
  65419. function PolygonPoints() {
  65420. this.elements = new Array();
  65421. }
  65422. PolygonPoints.prototype.add = function (originalPoints) {
  65423. var _this = this;
  65424. var result = new Array();
  65425. originalPoints.forEach(function (point) {
  65426. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  65427. var newPoint = new IndexedVector2(point, _this.elements.length);
  65428. result.push(newPoint);
  65429. _this.elements.push(newPoint);
  65430. }
  65431. });
  65432. return result;
  65433. };
  65434. PolygonPoints.prototype.computeBounds = function () {
  65435. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65436. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65437. this.elements.forEach(function (point) {
  65438. // x
  65439. if (point.x < lmin.x) {
  65440. lmin.x = point.x;
  65441. }
  65442. else if (point.x > lmax.x) {
  65443. lmax.x = point.x;
  65444. }
  65445. // y
  65446. if (point.y < lmin.y) {
  65447. lmin.y = point.y;
  65448. }
  65449. else if (point.y > lmax.y) {
  65450. lmax.y = point.y;
  65451. }
  65452. });
  65453. return {
  65454. min: lmin,
  65455. max: lmax,
  65456. width: lmax.x - lmin.x,
  65457. height: lmax.y - lmin.y
  65458. };
  65459. };
  65460. return PolygonPoints;
  65461. }());
  65462. var Polygon = /** @class */ (function () {
  65463. function Polygon() {
  65464. }
  65465. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  65466. return [
  65467. new BABYLON.Vector2(xmin, ymin),
  65468. new BABYLON.Vector2(xmax, ymin),
  65469. new BABYLON.Vector2(xmax, ymax),
  65470. new BABYLON.Vector2(xmin, ymax)
  65471. ];
  65472. };
  65473. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  65474. if (cx === void 0) { cx = 0; }
  65475. if (cy === void 0) { cy = 0; }
  65476. if (numberOfSides === void 0) { numberOfSides = 32; }
  65477. var result = new Array();
  65478. var angle = 0;
  65479. var increment = (Math.PI * 2) / numberOfSides;
  65480. for (var i = 0; i < numberOfSides; i++) {
  65481. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65482. angle -= increment;
  65483. }
  65484. return result;
  65485. };
  65486. Polygon.Parse = function (input) {
  65487. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65488. var i, result = [];
  65489. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65490. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65491. }
  65492. return result;
  65493. };
  65494. Polygon.StartingAt = function (x, y) {
  65495. return BABYLON.Path2.StartingAt(x, y);
  65496. };
  65497. return Polygon;
  65498. }());
  65499. BABYLON.Polygon = Polygon;
  65500. var PolygonMeshBuilder = /** @class */ (function () {
  65501. function PolygonMeshBuilder(name, contours, scene) {
  65502. this._points = new PolygonPoints();
  65503. this._outlinepoints = new PolygonPoints();
  65504. this._holes = new Array();
  65505. this._epoints = new Array();
  65506. this._eholes = new Array();
  65507. this._name = name;
  65508. this._scene = scene;
  65509. var points;
  65510. if (contours instanceof BABYLON.Path2) {
  65511. points = contours.getPoints();
  65512. }
  65513. else {
  65514. points = contours;
  65515. }
  65516. this._addToepoint(points);
  65517. this._points.add(points);
  65518. this._outlinepoints.add(points);
  65519. }
  65520. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65521. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65522. var p = points_1[_i];
  65523. this._epoints.push(p.x, p.y);
  65524. }
  65525. };
  65526. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65527. this._points.add(hole);
  65528. var holepoints = new PolygonPoints();
  65529. holepoints.add(hole);
  65530. this._holes.push(holepoints);
  65531. this._eholes.push(this._epoints.length / 2);
  65532. this._addToepoint(hole);
  65533. return this;
  65534. };
  65535. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65536. var _this = this;
  65537. if (updatable === void 0) { updatable = false; }
  65538. if (depth === void 0) { depth = 0; }
  65539. var result = new BABYLON.Mesh(this._name, this._scene);
  65540. var normals = new Array();
  65541. var positions = new Array();
  65542. var uvs = new Array();
  65543. var bounds = this._points.computeBounds();
  65544. this._points.elements.forEach(function (p) {
  65545. normals.push(0, 1.0, 0);
  65546. positions.push(p.x, 0, p.y);
  65547. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65548. });
  65549. var indices = new Array();
  65550. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65551. for (var i = 0; i < res.length; i++) {
  65552. indices.push(res[i]);
  65553. }
  65554. if (depth > 0) {
  65555. var positionscount = (positions.length / 3); //get the current pointcount
  65556. this._points.elements.forEach(function (p) {
  65557. normals.push(0, -1.0, 0);
  65558. positions.push(p.x, -depth, p.y);
  65559. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65560. });
  65561. var totalCount = indices.length;
  65562. for (var i = 0; i < totalCount; i += 3) {
  65563. var i0 = indices[i + 0];
  65564. var i1 = indices[i + 1];
  65565. var i2 = indices[i + 2];
  65566. indices.push(i2 + positionscount);
  65567. indices.push(i1 + positionscount);
  65568. indices.push(i0 + positionscount);
  65569. }
  65570. //Add the sides
  65571. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65572. this._holes.forEach(function (hole) {
  65573. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65574. });
  65575. }
  65576. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65577. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65578. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65579. result.setIndices(indices);
  65580. return result;
  65581. };
  65582. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65583. var StartIndex = positions.length / 3;
  65584. var ulength = 0;
  65585. for (var i = 0; i < points.elements.length; i++) {
  65586. var p = points.elements[i];
  65587. var p1;
  65588. if ((i + 1) > points.elements.length - 1) {
  65589. p1 = points.elements[0];
  65590. }
  65591. else {
  65592. p1 = points.elements[i + 1];
  65593. }
  65594. positions.push(p.x, 0, p.y);
  65595. positions.push(p.x, -depth, p.y);
  65596. positions.push(p1.x, 0, p1.y);
  65597. positions.push(p1.x, -depth, p1.y);
  65598. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65599. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65600. var v3 = v2.subtract(v1);
  65601. var v4 = new BABYLON.Vector3(0, 1, 0);
  65602. var vn = BABYLON.Vector3.Cross(v3, v4);
  65603. vn = vn.normalize();
  65604. uvs.push(ulength / bounds.width, 0);
  65605. uvs.push(ulength / bounds.width, 1);
  65606. ulength += v3.length();
  65607. uvs.push((ulength / bounds.width), 0);
  65608. uvs.push((ulength / bounds.width), 1);
  65609. if (!flip) {
  65610. normals.push(-vn.x, -vn.y, -vn.z);
  65611. normals.push(-vn.x, -vn.y, -vn.z);
  65612. normals.push(-vn.x, -vn.y, -vn.z);
  65613. normals.push(-vn.x, -vn.y, -vn.z);
  65614. indices.push(StartIndex);
  65615. indices.push(StartIndex + 1);
  65616. indices.push(StartIndex + 2);
  65617. indices.push(StartIndex + 1);
  65618. indices.push(StartIndex + 3);
  65619. indices.push(StartIndex + 2);
  65620. }
  65621. else {
  65622. normals.push(vn.x, vn.y, vn.z);
  65623. normals.push(vn.x, vn.y, vn.z);
  65624. normals.push(vn.x, vn.y, vn.z);
  65625. normals.push(vn.x, vn.y, vn.z);
  65626. indices.push(StartIndex);
  65627. indices.push(StartIndex + 2);
  65628. indices.push(StartIndex + 1);
  65629. indices.push(StartIndex + 1);
  65630. indices.push(StartIndex + 2);
  65631. indices.push(StartIndex + 3);
  65632. }
  65633. StartIndex += 4;
  65634. }
  65635. ;
  65636. };
  65637. return PolygonMeshBuilder;
  65638. }());
  65639. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65640. })(BABYLON || (BABYLON = {}));
  65641. //# sourceMappingURL=babylon.polygonMesh.js.map
  65642. var BABYLON;
  65643. (function (BABYLON) {
  65644. // Unique ID when we import meshes from Babylon to CSG
  65645. var currentCSGMeshId = 0;
  65646. // # class Vertex
  65647. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65648. // one to provide additional features like texture coordinates and vertex
  65649. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65650. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65651. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65652. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65653. // is not used anywhere else.
  65654. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65655. var Vertex = /** @class */ (function () {
  65656. function Vertex(pos, normal, uv) {
  65657. this.pos = pos;
  65658. this.normal = normal;
  65659. this.uv = uv;
  65660. }
  65661. Vertex.prototype.clone = function () {
  65662. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65663. };
  65664. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65665. // orientation of a polygon is flipped.
  65666. Vertex.prototype.flip = function () {
  65667. this.normal = this.normal.scale(-1);
  65668. };
  65669. // Create a new vertex between this vertex and `other` by linearly
  65670. // interpolating all properties using a parameter of `t`. Subclasses should
  65671. // override this to interpolate additional properties.
  65672. Vertex.prototype.interpolate = function (other, t) {
  65673. 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));
  65674. };
  65675. return Vertex;
  65676. }());
  65677. // # class Plane
  65678. // Represents a plane in 3D space.
  65679. var Plane = /** @class */ (function () {
  65680. function Plane(normal, w) {
  65681. this.normal = normal;
  65682. this.w = w;
  65683. }
  65684. Plane.FromPoints = function (a, b, c) {
  65685. var v0 = c.subtract(a);
  65686. var v1 = b.subtract(a);
  65687. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65688. return null;
  65689. }
  65690. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65691. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65692. };
  65693. Plane.prototype.clone = function () {
  65694. return new Plane(this.normal.clone(), this.w);
  65695. };
  65696. Plane.prototype.flip = function () {
  65697. this.normal.scaleInPlace(-1);
  65698. this.w = -this.w;
  65699. };
  65700. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65701. // fragments in the appropriate lists. Coplanar polygons go into either
  65702. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65703. // respect to this plane. Polygons in front or in back of this plane go into
  65704. // either `front` or `back`.
  65705. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65706. var COPLANAR = 0;
  65707. var FRONT = 1;
  65708. var BACK = 2;
  65709. var SPANNING = 3;
  65710. // Classify each point as well as the entire polygon into one of the above
  65711. // four classes.
  65712. var polygonType = 0;
  65713. var types = [];
  65714. var i;
  65715. var t;
  65716. for (i = 0; i < polygon.vertices.length; i++) {
  65717. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65718. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65719. polygonType |= type;
  65720. types.push(type);
  65721. }
  65722. // Put the polygon in the correct list, splitting it when necessary.
  65723. switch (polygonType) {
  65724. case COPLANAR:
  65725. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65726. break;
  65727. case FRONT:
  65728. front.push(polygon);
  65729. break;
  65730. case BACK:
  65731. back.push(polygon);
  65732. break;
  65733. case SPANNING:
  65734. var f = [], b = [];
  65735. for (i = 0; i < polygon.vertices.length; i++) {
  65736. var j = (i + 1) % polygon.vertices.length;
  65737. var ti = types[i], tj = types[j];
  65738. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65739. if (ti !== BACK)
  65740. f.push(vi);
  65741. if (ti !== FRONT)
  65742. b.push(ti !== BACK ? vi.clone() : vi);
  65743. if ((ti | tj) === SPANNING) {
  65744. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65745. var v = vi.interpolate(vj, t);
  65746. f.push(v);
  65747. b.push(v.clone());
  65748. }
  65749. }
  65750. var poly;
  65751. if (f.length >= 3) {
  65752. poly = new Polygon(f, polygon.shared);
  65753. if (poly.plane)
  65754. front.push(poly);
  65755. }
  65756. if (b.length >= 3) {
  65757. poly = new Polygon(b, polygon.shared);
  65758. if (poly.plane)
  65759. back.push(poly);
  65760. }
  65761. break;
  65762. }
  65763. };
  65764. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65765. // point is on the plane.
  65766. Plane.EPSILON = 1e-5;
  65767. return Plane;
  65768. }());
  65769. // # class Polygon
  65770. // Represents a convex polygon. The vertices used to initialize a polygon must
  65771. // be coplanar and form a convex loop.
  65772. //
  65773. // Each convex polygon has a `shared` property, which is shared between all
  65774. // polygons that are clones of each other or were split from the same polygon.
  65775. // This can be used to define per-polygon properties (such as surface color).
  65776. var Polygon = /** @class */ (function () {
  65777. function Polygon(vertices, shared) {
  65778. this.vertices = vertices;
  65779. this.shared = shared;
  65780. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65781. }
  65782. Polygon.prototype.clone = function () {
  65783. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65784. return new Polygon(vertices, this.shared);
  65785. };
  65786. Polygon.prototype.flip = function () {
  65787. this.vertices.reverse().map(function (v) { v.flip(); });
  65788. this.plane.flip();
  65789. };
  65790. return Polygon;
  65791. }());
  65792. // # class Node
  65793. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65794. // by picking a polygon to split along. That polygon (and all other coplanar
  65795. // polygons) are added directly to that node and the other polygons are added to
  65796. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65797. // no distinction between internal and leaf nodes.
  65798. var Node = /** @class */ (function () {
  65799. function Node(polygons) {
  65800. this.plane = null;
  65801. this.front = null;
  65802. this.back = null;
  65803. this.polygons = new Array();
  65804. if (polygons) {
  65805. this.build(polygons);
  65806. }
  65807. }
  65808. Node.prototype.clone = function () {
  65809. var node = new Node();
  65810. node.plane = this.plane && this.plane.clone();
  65811. node.front = this.front && this.front.clone();
  65812. node.back = this.back && this.back.clone();
  65813. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65814. return node;
  65815. };
  65816. // Convert solid space to empty space and empty space to solid space.
  65817. Node.prototype.invert = function () {
  65818. for (var i = 0; i < this.polygons.length; i++) {
  65819. this.polygons[i].flip();
  65820. }
  65821. if (this.plane) {
  65822. this.plane.flip();
  65823. }
  65824. if (this.front) {
  65825. this.front.invert();
  65826. }
  65827. if (this.back) {
  65828. this.back.invert();
  65829. }
  65830. var temp = this.front;
  65831. this.front = this.back;
  65832. this.back = temp;
  65833. };
  65834. // Recursively remove all polygons in `polygons` that are inside this BSP
  65835. // tree.
  65836. Node.prototype.clipPolygons = function (polygons) {
  65837. if (!this.plane)
  65838. return polygons.slice();
  65839. var front = new Array(), back = new Array();
  65840. for (var i = 0; i < polygons.length; i++) {
  65841. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65842. }
  65843. if (this.front) {
  65844. front = this.front.clipPolygons(front);
  65845. }
  65846. if (this.back) {
  65847. back = this.back.clipPolygons(back);
  65848. }
  65849. else {
  65850. back = [];
  65851. }
  65852. return front.concat(back);
  65853. };
  65854. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65855. // `bsp`.
  65856. Node.prototype.clipTo = function (bsp) {
  65857. this.polygons = bsp.clipPolygons(this.polygons);
  65858. if (this.front)
  65859. this.front.clipTo(bsp);
  65860. if (this.back)
  65861. this.back.clipTo(bsp);
  65862. };
  65863. // Return a list of all polygons in this BSP tree.
  65864. Node.prototype.allPolygons = function () {
  65865. var polygons = this.polygons.slice();
  65866. if (this.front)
  65867. polygons = polygons.concat(this.front.allPolygons());
  65868. if (this.back)
  65869. polygons = polygons.concat(this.back.allPolygons());
  65870. return polygons;
  65871. };
  65872. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65873. // new polygons are filtered down to the bottom of the tree and become new
  65874. // nodes there. Each set of polygons is partitioned using the first polygon
  65875. // (no heuristic is used to pick a good split).
  65876. Node.prototype.build = function (polygons) {
  65877. if (!polygons.length)
  65878. return;
  65879. if (!this.plane)
  65880. this.plane = polygons[0].plane.clone();
  65881. var front = new Array(), back = new Array();
  65882. for (var i = 0; i < polygons.length; i++) {
  65883. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65884. }
  65885. if (front.length) {
  65886. if (!this.front)
  65887. this.front = new Node();
  65888. this.front.build(front);
  65889. }
  65890. if (back.length) {
  65891. if (!this.back)
  65892. this.back = new Node();
  65893. this.back.build(back);
  65894. }
  65895. };
  65896. return Node;
  65897. }());
  65898. var CSG = /** @class */ (function () {
  65899. function CSG() {
  65900. this.polygons = new Array();
  65901. }
  65902. // Convert BABYLON.Mesh to BABYLON.CSG
  65903. CSG.FromMesh = function (mesh) {
  65904. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65905. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65906. if (mesh instanceof BABYLON.Mesh) {
  65907. mesh.computeWorldMatrix(true);
  65908. matrix = mesh.getWorldMatrix();
  65909. meshPosition = mesh.position.clone();
  65910. meshRotation = mesh.rotation.clone();
  65911. if (mesh.rotationQuaternion) {
  65912. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65913. }
  65914. meshScaling = mesh.scaling.clone();
  65915. }
  65916. else {
  65917. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65918. }
  65919. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65920. var subMeshes = mesh.subMeshes;
  65921. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65922. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65923. vertices = [];
  65924. for (var j = 0; j < 3; j++) {
  65925. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65926. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65927. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65928. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65929. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65930. vertex = new Vertex(position, normal, uv);
  65931. vertices.push(vertex);
  65932. }
  65933. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65934. // To handle the case of degenerated triangle
  65935. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65936. if (polygon.plane)
  65937. polygons.push(polygon);
  65938. }
  65939. }
  65940. var csg = CSG.FromPolygons(polygons);
  65941. csg.matrix = matrix;
  65942. csg.position = meshPosition;
  65943. csg.rotation = meshRotation;
  65944. csg.scaling = meshScaling;
  65945. csg.rotationQuaternion = meshRotationQuaternion;
  65946. currentCSGMeshId++;
  65947. return csg;
  65948. };
  65949. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65950. CSG.FromPolygons = function (polygons) {
  65951. var csg = new CSG();
  65952. csg.polygons = polygons;
  65953. return csg;
  65954. };
  65955. CSG.prototype.clone = function () {
  65956. var csg = new CSG();
  65957. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65958. csg.copyTransformAttributes(this);
  65959. return csg;
  65960. };
  65961. CSG.prototype.union = function (csg) {
  65962. var a = new Node(this.clone().polygons);
  65963. var b = new Node(csg.clone().polygons);
  65964. a.clipTo(b);
  65965. b.clipTo(a);
  65966. b.invert();
  65967. b.clipTo(a);
  65968. b.invert();
  65969. a.build(b.allPolygons());
  65970. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65971. };
  65972. CSG.prototype.unionInPlace = function (csg) {
  65973. var a = new Node(this.polygons);
  65974. var b = new Node(csg.polygons);
  65975. a.clipTo(b);
  65976. b.clipTo(a);
  65977. b.invert();
  65978. b.clipTo(a);
  65979. b.invert();
  65980. a.build(b.allPolygons());
  65981. this.polygons = a.allPolygons();
  65982. };
  65983. CSG.prototype.subtract = function (csg) {
  65984. var a = new Node(this.clone().polygons);
  65985. var b = new Node(csg.clone().polygons);
  65986. a.invert();
  65987. a.clipTo(b);
  65988. b.clipTo(a);
  65989. b.invert();
  65990. b.clipTo(a);
  65991. b.invert();
  65992. a.build(b.allPolygons());
  65993. a.invert();
  65994. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65995. };
  65996. CSG.prototype.subtractInPlace = function (csg) {
  65997. var a = new Node(this.polygons);
  65998. var b = new Node(csg.polygons);
  65999. a.invert();
  66000. a.clipTo(b);
  66001. b.clipTo(a);
  66002. b.invert();
  66003. b.clipTo(a);
  66004. b.invert();
  66005. a.build(b.allPolygons());
  66006. a.invert();
  66007. this.polygons = a.allPolygons();
  66008. };
  66009. CSG.prototype.intersect = function (csg) {
  66010. var a = new Node(this.clone().polygons);
  66011. var b = new Node(csg.clone().polygons);
  66012. a.invert();
  66013. b.clipTo(a);
  66014. b.invert();
  66015. a.clipTo(b);
  66016. b.clipTo(a);
  66017. a.build(b.allPolygons());
  66018. a.invert();
  66019. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66020. };
  66021. CSG.prototype.intersectInPlace = function (csg) {
  66022. var a = new Node(this.polygons);
  66023. var b = new Node(csg.polygons);
  66024. a.invert();
  66025. b.clipTo(a);
  66026. b.invert();
  66027. a.clipTo(b);
  66028. b.clipTo(a);
  66029. a.build(b.allPolygons());
  66030. a.invert();
  66031. this.polygons = a.allPolygons();
  66032. };
  66033. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  66034. // not modified.
  66035. CSG.prototype.inverse = function () {
  66036. var csg = this.clone();
  66037. csg.inverseInPlace();
  66038. return csg;
  66039. };
  66040. CSG.prototype.inverseInPlace = function () {
  66041. this.polygons.map(function (p) { p.flip(); });
  66042. };
  66043. // This is used to keep meshes transformations so they can be restored
  66044. // when we build back a Babylon Mesh
  66045. // NB : All CSG operations are performed in world coordinates
  66046. CSG.prototype.copyTransformAttributes = function (csg) {
  66047. this.matrix = csg.matrix;
  66048. this.position = csg.position;
  66049. this.rotation = csg.rotation;
  66050. this.scaling = csg.scaling;
  66051. this.rotationQuaternion = csg.rotationQuaternion;
  66052. return this;
  66053. };
  66054. // Build Raw mesh from CSG
  66055. // Coordinates here are in world space
  66056. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  66057. var matrix = this.matrix.clone();
  66058. matrix.invert();
  66059. 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;
  66060. if (keepSubMeshes) {
  66061. // Sort Polygons, since subMeshes are indices range
  66062. polygons.sort(function (a, b) {
  66063. if (a.shared.meshId === b.shared.meshId) {
  66064. return a.shared.subMeshId - b.shared.subMeshId;
  66065. }
  66066. else {
  66067. return a.shared.meshId - b.shared.meshId;
  66068. }
  66069. });
  66070. }
  66071. for (var i = 0, il = polygons.length; i < il; i++) {
  66072. polygon = polygons[i];
  66073. // Building SubMeshes
  66074. if (!subMesh_dict[polygon.shared.meshId]) {
  66075. subMesh_dict[polygon.shared.meshId] = {};
  66076. }
  66077. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  66078. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  66079. indexStart: +Infinity,
  66080. indexEnd: -Infinity,
  66081. materialIndex: polygon.shared.materialIndex
  66082. };
  66083. }
  66084. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  66085. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  66086. polygonIndices[0] = 0;
  66087. polygonIndices[1] = j - 1;
  66088. polygonIndices[2] = j;
  66089. for (var k = 0; k < 3; k++) {
  66090. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  66091. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  66092. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  66093. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  66094. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  66095. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  66096. // Check if 2 points can be merged
  66097. if (!(typeof vertex_idx !== 'undefined' &&
  66098. normals[vertex_idx * 3] === localNormal.x &&
  66099. normals[vertex_idx * 3 + 1] === localNormal.y &&
  66100. normals[vertex_idx * 3 + 2] === localNormal.z &&
  66101. uvs[vertex_idx * 2] === uv.x &&
  66102. uvs[vertex_idx * 2 + 1] === uv.y)) {
  66103. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  66104. uvs.push(uv.x, uv.y);
  66105. normals.push(normal.x, normal.y, normal.z);
  66106. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  66107. }
  66108. indices.push(vertex_idx);
  66109. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  66110. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  66111. currentIndex++;
  66112. }
  66113. }
  66114. }
  66115. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  66116. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  66117. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  66118. mesh.setIndices(indices, null);
  66119. if (keepSubMeshes) {
  66120. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  66121. var materialIndexOffset = 0, materialMaxIndex;
  66122. mesh.subMeshes = new Array();
  66123. for (var m in subMesh_dict) {
  66124. materialMaxIndex = -1;
  66125. for (var sm in subMesh_dict[m]) {
  66126. subMesh_obj = subMesh_dict[m][sm];
  66127. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  66128. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  66129. }
  66130. materialIndexOffset += ++materialMaxIndex;
  66131. }
  66132. }
  66133. return mesh;
  66134. };
  66135. // Build Mesh from CSG taking material and transforms into account
  66136. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  66137. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  66138. mesh.material = material;
  66139. mesh.position.copyFrom(this.position);
  66140. mesh.rotation.copyFrom(this.rotation);
  66141. if (this.rotationQuaternion) {
  66142. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  66143. }
  66144. mesh.scaling.copyFrom(this.scaling);
  66145. mesh.computeWorldMatrix(true);
  66146. return mesh;
  66147. };
  66148. return CSG;
  66149. }());
  66150. BABYLON.CSG = CSG;
  66151. })(BABYLON || (BABYLON = {}));
  66152. //# sourceMappingURL=babylon.csg.js.map
  66153. var BABYLON;
  66154. (function (BABYLON) {
  66155. var LensFlare = /** @class */ (function () {
  66156. function LensFlare(size, position, color, imgUrl, system) {
  66157. this.size = size;
  66158. this.position = position;
  66159. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  66160. this.color = color || new BABYLON.Color3(1, 1, 1);
  66161. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  66162. this._system = system;
  66163. system.lensFlares.push(this);
  66164. }
  66165. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  66166. return new LensFlare(size, position, color, imgUrl, system);
  66167. };
  66168. LensFlare.prototype.dispose = function () {
  66169. if (this.texture) {
  66170. this.texture.dispose();
  66171. }
  66172. // Remove from scene
  66173. var index = this._system.lensFlares.indexOf(this);
  66174. this._system.lensFlares.splice(index, 1);
  66175. };
  66176. ;
  66177. return LensFlare;
  66178. }());
  66179. BABYLON.LensFlare = LensFlare;
  66180. })(BABYLON || (BABYLON = {}));
  66181. //# sourceMappingURL=babylon.lensFlare.js.map
  66182. var BABYLON;
  66183. (function (BABYLON) {
  66184. var LensFlareSystem = /** @class */ (function () {
  66185. function LensFlareSystem(name, emitter, scene) {
  66186. this.name = name;
  66187. this.lensFlares = new Array();
  66188. this.borderLimit = 300;
  66189. this.viewportBorder = 0;
  66190. this.layerMask = 0x0FFFFFFF;
  66191. this._vertexBuffers = {};
  66192. this._isEnabled = true;
  66193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66194. this._emitter = emitter;
  66195. this.id = name;
  66196. scene.lensFlareSystems.push(this);
  66197. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  66198. var engine = scene.getEngine();
  66199. // VBO
  66200. var vertices = [];
  66201. vertices.push(1, 1);
  66202. vertices.push(-1, 1);
  66203. vertices.push(-1, -1);
  66204. vertices.push(1, -1);
  66205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66206. // Indices
  66207. var indices = [];
  66208. indices.push(0);
  66209. indices.push(1);
  66210. indices.push(2);
  66211. indices.push(0);
  66212. indices.push(2);
  66213. indices.push(3);
  66214. this._indexBuffer = engine.createIndexBuffer(indices);
  66215. // Effects
  66216. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  66217. }
  66218. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  66219. get: function () {
  66220. return this._isEnabled;
  66221. },
  66222. set: function (value) {
  66223. this._isEnabled = value;
  66224. },
  66225. enumerable: true,
  66226. configurable: true
  66227. });
  66228. LensFlareSystem.prototype.getScene = function () {
  66229. return this._scene;
  66230. };
  66231. LensFlareSystem.prototype.getEmitter = function () {
  66232. return this._emitter;
  66233. };
  66234. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  66235. this._emitter = newEmitter;
  66236. };
  66237. LensFlareSystem.prototype.getEmitterPosition = function () {
  66238. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  66239. };
  66240. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  66241. var position = this.getEmitterPosition();
  66242. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  66243. this._positionX = position.x;
  66244. this._positionY = position.y;
  66245. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  66246. if (this.viewportBorder > 0) {
  66247. globalViewport.x -= this.viewportBorder;
  66248. globalViewport.y -= this.viewportBorder;
  66249. globalViewport.width += this.viewportBorder * 2;
  66250. globalViewport.height += this.viewportBorder * 2;
  66251. position.x += this.viewportBorder;
  66252. position.y += this.viewportBorder;
  66253. this._positionX += this.viewportBorder;
  66254. this._positionY += this.viewportBorder;
  66255. }
  66256. if (position.z > 0) {
  66257. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  66258. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  66259. return true;
  66260. }
  66261. return true;
  66262. }
  66263. return false;
  66264. };
  66265. LensFlareSystem.prototype._isVisible = function () {
  66266. if (!this._isEnabled || !this._scene.activeCamera) {
  66267. return false;
  66268. }
  66269. var emitterPosition = this.getEmitterPosition();
  66270. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  66271. var distance = direction.length();
  66272. direction.normalize();
  66273. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  66274. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  66275. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  66276. };
  66277. LensFlareSystem.prototype.render = function () {
  66278. if (!this._effect.isReady() || !this._scene.activeCamera)
  66279. return false;
  66280. var engine = this._scene.getEngine();
  66281. var viewport = this._scene.activeCamera.viewport;
  66282. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  66283. // Position
  66284. if (!this.computeEffectivePosition(globalViewport)) {
  66285. return false;
  66286. }
  66287. // Visibility
  66288. if (!this._isVisible()) {
  66289. return false;
  66290. }
  66291. // Intensity
  66292. var awayX;
  66293. var awayY;
  66294. if (this._positionX < this.borderLimit + globalViewport.x) {
  66295. awayX = this.borderLimit + globalViewport.x - this._positionX;
  66296. }
  66297. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  66298. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  66299. }
  66300. else {
  66301. awayX = 0;
  66302. }
  66303. if (this._positionY < this.borderLimit + globalViewport.y) {
  66304. awayY = this.borderLimit + globalViewport.y - this._positionY;
  66305. }
  66306. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  66307. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  66308. }
  66309. else {
  66310. awayY = 0;
  66311. }
  66312. var away = (awayX > awayY) ? awayX : awayY;
  66313. away -= this.viewportBorder;
  66314. if (away > this.borderLimit) {
  66315. away = this.borderLimit;
  66316. }
  66317. var intensity = 1.0 - (away / this.borderLimit);
  66318. if (intensity < 0) {
  66319. return false;
  66320. }
  66321. if (intensity > 1.0) {
  66322. intensity = 1.0;
  66323. }
  66324. if (this.viewportBorder > 0) {
  66325. globalViewport.x += this.viewportBorder;
  66326. globalViewport.y += this.viewportBorder;
  66327. globalViewport.width -= this.viewportBorder * 2;
  66328. globalViewport.height -= this.viewportBorder * 2;
  66329. this._positionX -= this.viewportBorder;
  66330. this._positionY -= this.viewportBorder;
  66331. }
  66332. // Position
  66333. var centerX = globalViewport.x + globalViewport.width / 2;
  66334. var centerY = globalViewport.y + globalViewport.height / 2;
  66335. var distX = centerX - this._positionX;
  66336. var distY = centerY - this._positionY;
  66337. // Effects
  66338. engine.enableEffect(this._effect);
  66339. engine.setState(false);
  66340. engine.setDepthBuffer(false);
  66341. // VBOs
  66342. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66343. // Flares
  66344. for (var index = 0; index < this.lensFlares.length; index++) {
  66345. var flare = this.lensFlares[index];
  66346. engine.setAlphaMode(flare.alphaMode);
  66347. var x = centerX - (distX * flare.position);
  66348. var y = centerY - (distY * flare.position);
  66349. var cw = flare.size;
  66350. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  66351. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  66352. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  66353. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  66354. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  66355. // Texture
  66356. this._effect.setTexture("textureSampler", flare.texture);
  66357. // Color
  66358. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  66359. // Draw order
  66360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66361. }
  66362. engine.setDepthBuffer(true);
  66363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66364. return true;
  66365. };
  66366. LensFlareSystem.prototype.dispose = function () {
  66367. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66368. if (vertexBuffer) {
  66369. vertexBuffer.dispose();
  66370. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66371. }
  66372. if (this._indexBuffer) {
  66373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66374. this._indexBuffer = null;
  66375. }
  66376. while (this.lensFlares.length) {
  66377. this.lensFlares[0].dispose();
  66378. }
  66379. // Remove from scene
  66380. var index = this._scene.lensFlareSystems.indexOf(this);
  66381. this._scene.lensFlareSystems.splice(index, 1);
  66382. };
  66383. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  66384. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  66385. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  66386. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  66387. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  66388. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  66389. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  66390. var parsedFlare = parsedLensFlareSystem.flares[index];
  66391. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  66392. }
  66393. return lensFlareSystem;
  66394. };
  66395. LensFlareSystem.prototype.serialize = function () {
  66396. var serializationObject = {};
  66397. serializationObject.id = this.id;
  66398. serializationObject.name = this.name;
  66399. serializationObject.emitterId = this.getEmitter().id;
  66400. serializationObject.borderLimit = this.borderLimit;
  66401. serializationObject.flares = [];
  66402. for (var index = 0; index < this.lensFlares.length; index++) {
  66403. var flare = this.lensFlares[index];
  66404. serializationObject.flares.push({
  66405. size: flare.size,
  66406. position: flare.position,
  66407. color: flare.color.asArray(),
  66408. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  66409. });
  66410. }
  66411. return serializationObject;
  66412. };
  66413. return LensFlareSystem;
  66414. }());
  66415. BABYLON.LensFlareSystem = LensFlareSystem;
  66416. })(BABYLON || (BABYLON = {}));
  66417. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  66418. var BABYLON;
  66419. (function (BABYLON) {
  66420. /**
  66421. * This is a holder class for the physics joint created by the physics plugin.
  66422. * It holds a set of functions to control the underlying joint.
  66423. */
  66424. var PhysicsJoint = /** @class */ (function () {
  66425. function PhysicsJoint(type, jointData) {
  66426. this.type = type;
  66427. this.jointData = jointData;
  66428. jointData.nativeParams = jointData.nativeParams || {};
  66429. }
  66430. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  66431. get: function () {
  66432. return this._physicsJoint;
  66433. },
  66434. set: function (newJoint) {
  66435. if (this._physicsJoint) {
  66436. //remove from the wolrd
  66437. }
  66438. this._physicsJoint = newJoint;
  66439. },
  66440. enumerable: true,
  66441. configurable: true
  66442. });
  66443. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  66444. set: function (physicsPlugin) {
  66445. this._physicsPlugin = physicsPlugin;
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. /**
  66451. * Execute a function that is physics-plugin specific.
  66452. * @param {Function} func the function that will be executed.
  66453. * It accepts two parameters: the physics world and the physics joint.
  66454. */
  66455. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  66456. func(this._physicsPlugin.world, this._physicsJoint);
  66457. };
  66458. //TODO check if the native joints are the same
  66459. //Joint Types
  66460. PhysicsJoint.DistanceJoint = 0;
  66461. PhysicsJoint.HingeJoint = 1;
  66462. PhysicsJoint.BallAndSocketJoint = 2;
  66463. PhysicsJoint.WheelJoint = 3;
  66464. PhysicsJoint.SliderJoint = 4;
  66465. //OIMO
  66466. PhysicsJoint.PrismaticJoint = 5;
  66467. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  66468. PhysicsJoint.UniversalJoint = 6;
  66469. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  66470. //Cannon
  66471. //Similar to a Ball-Joint. Different in params
  66472. PhysicsJoint.PointToPointJoint = 8;
  66473. //Cannon only at the moment
  66474. PhysicsJoint.SpringJoint = 9;
  66475. PhysicsJoint.LockJoint = 10;
  66476. return PhysicsJoint;
  66477. }());
  66478. BABYLON.PhysicsJoint = PhysicsJoint;
  66479. /**
  66480. * A class representing a physics distance joint.
  66481. */
  66482. var DistanceJoint = /** @class */ (function (_super) {
  66483. __extends(DistanceJoint, _super);
  66484. function DistanceJoint(jointData) {
  66485. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66486. }
  66487. /**
  66488. * Update the predefined distance.
  66489. */
  66490. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66491. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66492. };
  66493. return DistanceJoint;
  66494. }(PhysicsJoint));
  66495. BABYLON.DistanceJoint = DistanceJoint;
  66496. var MotorEnabledJoint = /** @class */ (function (_super) {
  66497. __extends(MotorEnabledJoint, _super);
  66498. function MotorEnabledJoint(type, jointData) {
  66499. return _super.call(this, type, jointData) || this;
  66500. }
  66501. /**
  66502. * Set the motor values.
  66503. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66504. * @param {number} force the force to apply
  66505. * @param {number} maxForce max force for this motor.
  66506. */
  66507. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66508. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66509. };
  66510. /**
  66511. * Set the motor's limits.
  66512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66513. */
  66514. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66515. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66516. };
  66517. return MotorEnabledJoint;
  66518. }(PhysicsJoint));
  66519. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66520. /**
  66521. * This class represents a single hinge physics joint
  66522. */
  66523. var HingeJoint = /** @class */ (function (_super) {
  66524. __extends(HingeJoint, _super);
  66525. function HingeJoint(jointData) {
  66526. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66527. }
  66528. /**
  66529. * Set the motor values.
  66530. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66531. * @param {number} force the force to apply
  66532. * @param {number} maxForce max force for this motor.
  66533. */
  66534. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66535. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66536. };
  66537. /**
  66538. * Set the motor's limits.
  66539. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66540. */
  66541. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66542. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66543. };
  66544. return HingeJoint;
  66545. }(MotorEnabledJoint));
  66546. BABYLON.HingeJoint = HingeJoint;
  66547. /**
  66548. * This class represents a dual hinge physics joint (same as wheel joint)
  66549. */
  66550. var Hinge2Joint = /** @class */ (function (_super) {
  66551. __extends(Hinge2Joint, _super);
  66552. function Hinge2Joint(jointData) {
  66553. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66554. }
  66555. /**
  66556. * Set the motor values.
  66557. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66558. * @param {number} force the force to apply
  66559. * @param {number} maxForce max force for this motor.
  66560. * @param {motorIndex} the motor's index, 0 or 1.
  66561. */
  66562. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66563. if (motorIndex === void 0) { motorIndex = 0; }
  66564. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66565. };
  66566. /**
  66567. * Set the motor limits.
  66568. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66569. * @param {number} upperLimit the upper limit
  66570. * @param {number} lowerLimit lower limit
  66571. * @param {motorIndex} the motor's index, 0 or 1.
  66572. */
  66573. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66574. if (motorIndex === void 0) { motorIndex = 0; }
  66575. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66576. };
  66577. return Hinge2Joint;
  66578. }(MotorEnabledJoint));
  66579. BABYLON.Hinge2Joint = Hinge2Joint;
  66580. })(BABYLON || (BABYLON = {}));
  66581. //# sourceMappingURL=babylon.physicsJoint.js.map
  66582. var BABYLON;
  66583. (function (BABYLON) {
  66584. var PhysicsImpostor = /** @class */ (function () {
  66585. function PhysicsImpostor(object, type, _options, _scene) {
  66586. if (_options === void 0) { _options = { mass: 0 }; }
  66587. var _this = this;
  66588. this.object = object;
  66589. this.type = type;
  66590. this._options = _options;
  66591. this._scene = _scene;
  66592. this._bodyUpdateRequired = false;
  66593. this._onBeforePhysicsStepCallbacks = new Array();
  66594. this._onAfterPhysicsStepCallbacks = new Array();
  66595. this._onPhysicsCollideCallbacks = [];
  66596. this._deltaPosition = BABYLON.Vector3.Zero();
  66597. this._isDisposed = false;
  66598. //temp variables for parent rotation calculations
  66599. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66600. this._tmpQuat = new BABYLON.Quaternion();
  66601. this._tmpQuat2 = new BABYLON.Quaternion();
  66602. /**
  66603. * this function is executed by the physics engine.
  66604. */
  66605. this.beforeStep = function () {
  66606. if (!_this._physicsEngine) {
  66607. return;
  66608. }
  66609. _this.object.translate(_this._deltaPosition, -1);
  66610. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66611. _this.object.computeWorldMatrix(false);
  66612. if (_this.object.parent && _this.object.rotationQuaternion) {
  66613. _this.getParentsRotation();
  66614. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66615. }
  66616. else {
  66617. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66618. }
  66619. if (!_this._options.disableBidirectionalTransformation) {
  66620. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66621. }
  66622. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66623. func(_this);
  66624. });
  66625. };
  66626. /**
  66627. * this function is executed by the physics engine.
  66628. */
  66629. this.afterStep = function () {
  66630. if (!_this._physicsEngine) {
  66631. return;
  66632. }
  66633. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66634. func(_this);
  66635. });
  66636. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66637. // object has now its world rotation. needs to be converted to local.
  66638. if (_this.object.parent && _this.object.rotationQuaternion) {
  66639. _this.getParentsRotation();
  66640. _this._tmpQuat.conjugateInPlace();
  66641. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66642. }
  66643. // take the position set and make it the absolute position of this object.
  66644. _this.object.setAbsolutePosition(_this.object.position);
  66645. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66646. _this.object.translate(_this._deltaPosition, 1);
  66647. };
  66648. /**
  66649. * Legacy collision detection event support
  66650. */
  66651. this.onCollideEvent = null;
  66652. //event and body object due to cannon's event-based architecture.
  66653. this.onCollide = function (e) {
  66654. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66655. return;
  66656. }
  66657. if (!_this._physicsEngine) {
  66658. return;
  66659. }
  66660. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66661. if (otherImpostor) {
  66662. // Legacy collision detection event support
  66663. if (_this.onCollideEvent) {
  66664. _this.onCollideEvent(_this, otherImpostor);
  66665. }
  66666. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66667. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66668. }).forEach(function (obj) {
  66669. obj.callback(_this, otherImpostor);
  66670. });
  66671. }
  66672. };
  66673. //sanity check!
  66674. if (!this.object) {
  66675. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66676. return;
  66677. }
  66678. //legacy support for old syntax.
  66679. if (!this._scene && object.getScene) {
  66680. this._scene = object.getScene();
  66681. }
  66682. if (!this._scene) {
  66683. return;
  66684. }
  66685. this._physicsEngine = this._scene.getPhysicsEngine();
  66686. if (!this._physicsEngine) {
  66687. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66688. }
  66689. else {
  66690. //set the object's quaternion, if not set
  66691. if (!this.object.rotationQuaternion) {
  66692. if (this.object.rotation) {
  66693. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66694. }
  66695. else {
  66696. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66697. }
  66698. }
  66699. //default options params
  66700. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66701. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66702. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66703. this._joints = [];
  66704. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66705. if (!this.object.parent || this._options.ignoreParent) {
  66706. this._init();
  66707. }
  66708. else if (this.object.parent.physicsImpostor) {
  66709. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66710. }
  66711. }
  66712. }
  66713. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66714. get: function () {
  66715. return this._isDisposed;
  66716. },
  66717. enumerable: true,
  66718. configurable: true
  66719. });
  66720. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66721. get: function () {
  66722. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66723. },
  66724. set: function (value) {
  66725. this.setMass(value);
  66726. },
  66727. enumerable: true,
  66728. configurable: true
  66729. });
  66730. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66731. get: function () {
  66732. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66733. },
  66734. set: function (value) {
  66735. if (!this._physicsEngine) {
  66736. return;
  66737. }
  66738. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66739. },
  66740. enumerable: true,
  66741. configurable: true
  66742. });
  66743. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66744. get: function () {
  66745. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66746. },
  66747. set: function (value) {
  66748. if (!this._physicsEngine) {
  66749. return;
  66750. }
  66751. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66752. },
  66753. enumerable: true,
  66754. configurable: true
  66755. });
  66756. /**
  66757. * This function will completly initialize this impostor.
  66758. * It will create a new body - but only if this mesh has no parent.
  66759. * If it has, this impostor will not be used other than to define the impostor
  66760. * of the child mesh.
  66761. */
  66762. PhysicsImpostor.prototype._init = function () {
  66763. if (!this._physicsEngine) {
  66764. return;
  66765. }
  66766. this._physicsEngine.removeImpostor(this);
  66767. this.physicsBody = null;
  66768. this._parent = this._parent || this._getPhysicsParent();
  66769. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66770. this._physicsEngine.addImpostor(this);
  66771. }
  66772. };
  66773. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66774. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66775. var parentMesh = this.object.parent;
  66776. return parentMesh.physicsImpostor;
  66777. }
  66778. return null;
  66779. };
  66780. /**
  66781. * Should a new body be generated.
  66782. */
  66783. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66784. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66785. };
  66786. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66787. this.forceUpdate();
  66788. };
  66789. /**
  66790. * Force a regeneration of this or the parent's impostor's body.
  66791. * Use under cautious - This will remove all joints already implemented.
  66792. */
  66793. PhysicsImpostor.prototype.forceUpdate = function () {
  66794. this._init();
  66795. if (this.parent && !this._options.ignoreParent) {
  66796. this.parent.forceUpdate();
  66797. }
  66798. };
  66799. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66800. /*public get mesh(): AbstractMesh {
  66801. return this._mesh;
  66802. }*/
  66803. /**
  66804. * Gets the body that holds this impostor. Either its own, or its parent.
  66805. */
  66806. get: function () {
  66807. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66808. },
  66809. /**
  66810. * Set the physics body. Used mainly by the physics engine/plugin
  66811. */
  66812. set: function (physicsBody) {
  66813. if (this._physicsBody && this._physicsEngine) {
  66814. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66815. }
  66816. this._physicsBody = physicsBody;
  66817. this.resetUpdateFlags();
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66823. get: function () {
  66824. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66825. },
  66826. set: function (value) {
  66827. this._parent = value;
  66828. },
  66829. enumerable: true,
  66830. configurable: true
  66831. });
  66832. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66833. this._bodyUpdateRequired = false;
  66834. };
  66835. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66836. if (this.object.getBoundingInfo) {
  66837. var q = this.object.rotationQuaternion;
  66838. //reset rotation
  66839. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66840. //calculate the world matrix with no rotation
  66841. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66842. var boundingInfo = this.object.getBoundingInfo();
  66843. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66844. //bring back the rotation
  66845. this.object.rotationQuaternion = q;
  66846. //calculate the world matrix with the new rotation
  66847. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66848. return size;
  66849. }
  66850. else {
  66851. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66852. }
  66853. };
  66854. PhysicsImpostor.prototype.getObjectCenter = function () {
  66855. if (this.object.getBoundingInfo) {
  66856. var boundingInfo = this.object.getBoundingInfo();
  66857. return boundingInfo.boundingBox.centerWorld;
  66858. }
  66859. else {
  66860. return this.object.position;
  66861. }
  66862. };
  66863. /**
  66864. * Get a specific parametes from the options parameter.
  66865. */
  66866. PhysicsImpostor.prototype.getParam = function (paramName) {
  66867. return this._options[paramName];
  66868. };
  66869. /**
  66870. * Sets a specific parameter in the options given to the physics plugin
  66871. */
  66872. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66873. this._options[paramName] = value;
  66874. this._bodyUpdateRequired = true;
  66875. };
  66876. /**
  66877. * Specifically change the body's mass option. Won't recreate the physics body object
  66878. */
  66879. PhysicsImpostor.prototype.setMass = function (mass) {
  66880. if (this.getParam("mass") !== mass) {
  66881. this.setParam("mass", mass);
  66882. }
  66883. if (this._physicsEngine) {
  66884. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66885. }
  66886. };
  66887. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66888. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66889. };
  66890. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66891. if (this._physicsEngine) {
  66892. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66893. }
  66894. };
  66895. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66896. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66897. };
  66898. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66899. if (this._physicsEngine) {
  66900. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66901. }
  66902. };
  66903. /**
  66904. * Execute a function with the physics plugin native code.
  66905. * Provide a function the will have two variables - the world object and the physics body object.
  66906. */
  66907. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66908. if (this._physicsEngine) {
  66909. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66910. }
  66911. };
  66912. /**
  66913. * Register a function that will be executed before the physics world is stepping forward.
  66914. */
  66915. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66916. this._onBeforePhysicsStepCallbacks.push(func);
  66917. };
  66918. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66919. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66920. if (index > -1) {
  66921. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66922. }
  66923. else {
  66924. BABYLON.Tools.Warn("Function to remove was not found");
  66925. }
  66926. };
  66927. /**
  66928. * Register a function that will be executed after the physics step
  66929. */
  66930. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66931. this._onAfterPhysicsStepCallbacks.push(func);
  66932. };
  66933. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66934. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66935. if (index > -1) {
  66936. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66937. }
  66938. else {
  66939. BABYLON.Tools.Warn("Function to remove was not found");
  66940. }
  66941. };
  66942. /**
  66943. * register a function that will be executed when this impostor collides against a different body.
  66944. */
  66945. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66946. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66947. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66948. };
  66949. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66950. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66951. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66952. if (index > -1) {
  66953. this._onPhysicsCollideCallbacks.splice(index, 1);
  66954. }
  66955. else {
  66956. BABYLON.Tools.Warn("Function to remove was not found");
  66957. }
  66958. };
  66959. PhysicsImpostor.prototype.getParentsRotation = function () {
  66960. var parent = this.object.parent;
  66961. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66962. while (parent) {
  66963. if (parent.rotationQuaternion) {
  66964. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66965. }
  66966. else {
  66967. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66968. }
  66969. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66970. parent = parent.parent;
  66971. }
  66972. return this._tmpQuat;
  66973. };
  66974. /**
  66975. * Apply a force
  66976. */
  66977. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66978. if (this._physicsEngine) {
  66979. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66980. }
  66981. return this;
  66982. };
  66983. /**
  66984. * Apply an impulse
  66985. */
  66986. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66987. if (this._physicsEngine) {
  66988. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66989. }
  66990. return this;
  66991. };
  66992. /**
  66993. * A help function to create a joint.
  66994. */
  66995. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66996. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66997. this.addJoint(otherImpostor, joint);
  66998. return this;
  66999. };
  67000. /**
  67001. * Add a joint to this impostor with a different impostor.
  67002. */
  67003. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  67004. this._joints.push({
  67005. otherImpostor: otherImpostor,
  67006. joint: joint
  67007. });
  67008. if (this._physicsEngine) {
  67009. this._physicsEngine.addJoint(this, otherImpostor, joint);
  67010. }
  67011. return this;
  67012. };
  67013. /**
  67014. * Will keep this body still, in a sleep mode.
  67015. */
  67016. PhysicsImpostor.prototype.sleep = function () {
  67017. if (this._physicsEngine) {
  67018. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  67019. }
  67020. return this;
  67021. };
  67022. /**
  67023. * Wake the body up.
  67024. */
  67025. PhysicsImpostor.prototype.wakeUp = function () {
  67026. if (this._physicsEngine) {
  67027. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  67028. }
  67029. return this;
  67030. };
  67031. PhysicsImpostor.prototype.clone = function (newObject) {
  67032. if (!newObject)
  67033. return null;
  67034. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  67035. };
  67036. PhysicsImpostor.prototype.dispose = function () {
  67037. var _this = this;
  67038. //no dispose if no physics engine is available.
  67039. if (!this._physicsEngine) {
  67040. return;
  67041. }
  67042. this._joints.forEach(function (j) {
  67043. if (_this._physicsEngine) {
  67044. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  67045. }
  67046. });
  67047. //dispose the physics body
  67048. this._physicsEngine.removeImpostor(this);
  67049. if (this.parent) {
  67050. this.parent.forceUpdate();
  67051. }
  67052. else {
  67053. /*this._object.getChildMeshes().forEach(function(mesh) {
  67054. if (mesh.physicsImpostor) {
  67055. if (disposeChildren) {
  67056. mesh.physicsImpostor.dispose();
  67057. mesh.physicsImpostor = null;
  67058. }
  67059. }
  67060. })*/
  67061. }
  67062. this._isDisposed = true;
  67063. };
  67064. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  67065. this._deltaPosition.copyFrom(position);
  67066. };
  67067. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  67068. if (!this._deltaRotation) {
  67069. this._deltaRotation = new BABYLON.Quaternion();
  67070. }
  67071. this._deltaRotation.copyFrom(rotation);
  67072. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  67073. };
  67074. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  67075. if (this._physicsEngine) {
  67076. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  67077. }
  67078. return this;
  67079. };
  67080. PhysicsImpostor.prototype.getRadius = function () {
  67081. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  67082. };
  67083. /**
  67084. * Sync a bone with this impostor
  67085. * @param bone The bone to sync to the impostor.
  67086. * @param boneMesh The mesh that the bone is influencing.
  67087. * @param jointPivot The pivot of the joint / bone in local space.
  67088. * @param distToJoint Optional distance from the impostor to the joint.
  67089. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67090. */
  67091. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  67092. var tempVec = PhysicsImpostor._tmpVecs[0];
  67093. var mesh = this.object;
  67094. if (mesh.rotationQuaternion) {
  67095. if (adjustRotation) {
  67096. var tempQuat = PhysicsImpostor._tmpQuat;
  67097. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  67098. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  67099. }
  67100. else {
  67101. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  67102. }
  67103. }
  67104. tempVec.x = 0;
  67105. tempVec.y = 0;
  67106. tempVec.z = 0;
  67107. if (jointPivot) {
  67108. tempVec.x = jointPivot.x;
  67109. tempVec.y = jointPivot.y;
  67110. tempVec.z = jointPivot.z;
  67111. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  67112. if (distToJoint === undefined || distToJoint === null) {
  67113. distToJoint = jointPivot.length();
  67114. }
  67115. tempVec.x *= distToJoint;
  67116. tempVec.y *= distToJoint;
  67117. tempVec.z *= distToJoint;
  67118. }
  67119. if (bone.getParent()) {
  67120. tempVec.addInPlace(mesh.getAbsolutePosition());
  67121. bone.setAbsolutePosition(tempVec, boneMesh);
  67122. }
  67123. else {
  67124. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  67125. boneMesh.position.x -= tempVec.x;
  67126. boneMesh.position.y -= tempVec.y;
  67127. boneMesh.position.z -= tempVec.z;
  67128. }
  67129. };
  67130. /**
  67131. * Sync impostor to a bone
  67132. * @param bone The bone that the impostor will be synced to.
  67133. * @param boneMesh The mesh that the bone is influencing.
  67134. * @param jointPivot The pivot of the joint / bone in local space.
  67135. * @param distToJoint Optional distance from the impostor to the joint.
  67136. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67137. * @param boneAxis Optional vector3 axis the bone is aligned with
  67138. */
  67139. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  67140. var mesh = this.object;
  67141. if (mesh.rotationQuaternion) {
  67142. if (adjustRotation) {
  67143. var tempQuat = PhysicsImpostor._tmpQuat;
  67144. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  67145. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  67146. }
  67147. else {
  67148. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  67149. }
  67150. }
  67151. var pos = PhysicsImpostor._tmpVecs[0];
  67152. var boneDir = PhysicsImpostor._tmpVecs[1];
  67153. if (!boneAxis) {
  67154. boneAxis = PhysicsImpostor._tmpVecs[2];
  67155. boneAxis.x = 0;
  67156. boneAxis.y = 1;
  67157. boneAxis.z = 0;
  67158. }
  67159. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  67160. bone.getAbsolutePositionToRef(boneMesh, pos);
  67161. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  67162. distToJoint = jointPivot.length();
  67163. }
  67164. if (distToJoint !== undefined && distToJoint !== null) {
  67165. pos.x += boneDir.x * distToJoint;
  67166. pos.y += boneDir.y * distToJoint;
  67167. pos.z += boneDir.z * distToJoint;
  67168. }
  67169. mesh.setAbsolutePosition(pos);
  67170. };
  67171. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  67172. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  67173. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67174. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  67175. //Impostor types
  67176. PhysicsImpostor.NoImpostor = 0;
  67177. PhysicsImpostor.SphereImpostor = 1;
  67178. PhysicsImpostor.BoxImpostor = 2;
  67179. PhysicsImpostor.PlaneImpostor = 3;
  67180. PhysicsImpostor.MeshImpostor = 4;
  67181. PhysicsImpostor.CylinderImpostor = 7;
  67182. PhysicsImpostor.ParticleImpostor = 8;
  67183. PhysicsImpostor.HeightmapImpostor = 9;
  67184. return PhysicsImpostor;
  67185. }());
  67186. BABYLON.PhysicsImpostor = PhysicsImpostor;
  67187. })(BABYLON || (BABYLON = {}));
  67188. //# sourceMappingURL=babylon.physicsImpostor.js.map
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. var PhysicsEngine = /** @class */ (function () {
  67192. function PhysicsEngine(gravity, _physicsPlugin) {
  67193. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  67194. this._physicsPlugin = _physicsPlugin;
  67195. //new methods and parameters
  67196. this._impostors = [];
  67197. this._joints = [];
  67198. if (!this._physicsPlugin.isSupported()) {
  67199. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  67200. + "Please make sure it is included.");
  67201. }
  67202. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  67203. this.setGravity(gravity);
  67204. this.setTimeStep();
  67205. }
  67206. PhysicsEngine.prototype.setGravity = function (gravity) {
  67207. this.gravity = gravity;
  67208. this._physicsPlugin.setGravity(this.gravity);
  67209. };
  67210. /**
  67211. * Set the time step of the physics engine.
  67212. * default is 1/60.
  67213. * To slow it down, enter 1/600 for example.
  67214. * To speed it up, 1/30
  67215. * @param {number} newTimeStep the new timestep to apply to this world.
  67216. */
  67217. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  67218. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  67219. this._physicsPlugin.setTimeStep(newTimeStep);
  67220. };
  67221. /**
  67222. * Get the time step of the physics engine.
  67223. */
  67224. PhysicsEngine.prototype.getTimeStep = function () {
  67225. return this._physicsPlugin.getTimeStep();
  67226. };
  67227. PhysicsEngine.prototype.dispose = function () {
  67228. this._impostors.forEach(function (impostor) {
  67229. impostor.dispose();
  67230. });
  67231. this._physicsPlugin.dispose();
  67232. };
  67233. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  67234. return this._physicsPlugin.name;
  67235. };
  67236. /**
  67237. * Adding a new impostor for the impostor tracking.
  67238. * This will be done by the impostor itself.
  67239. * @param {PhysicsImpostor} impostor the impostor to add
  67240. */
  67241. PhysicsEngine.prototype.addImpostor = function (impostor) {
  67242. impostor.uniqueId = this._impostors.push(impostor);
  67243. //if no parent, generate the body
  67244. if (!impostor.parent) {
  67245. this._physicsPlugin.generatePhysicsBody(impostor);
  67246. }
  67247. };
  67248. /**
  67249. * Remove an impostor from the engine.
  67250. * This impostor and its mesh will not longer be updated by the physics engine.
  67251. * @param {PhysicsImpostor} impostor the impostor to remove
  67252. */
  67253. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  67254. var index = this._impostors.indexOf(impostor);
  67255. if (index > -1) {
  67256. var removed = this._impostors.splice(index, 1);
  67257. //Is it needed?
  67258. if (removed.length) {
  67259. //this will also remove it from the world.
  67260. removed[0].physicsBody = null;
  67261. }
  67262. }
  67263. };
  67264. /**
  67265. * Add a joint to the physics engine
  67266. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  67267. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  67268. * @param {PhysicsJoint} the joint that will connect both impostors.
  67269. */
  67270. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  67271. var impostorJoint = {
  67272. mainImpostor: mainImpostor,
  67273. connectedImpostor: connectedImpostor,
  67274. joint: joint
  67275. };
  67276. joint.physicsPlugin = this._physicsPlugin;
  67277. this._joints.push(impostorJoint);
  67278. this._physicsPlugin.generateJoint(impostorJoint);
  67279. };
  67280. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  67281. var matchingJoints = this._joints.filter(function (impostorJoint) {
  67282. return (impostorJoint.connectedImpostor === connectedImpostor
  67283. && impostorJoint.joint === joint
  67284. && impostorJoint.mainImpostor === mainImpostor);
  67285. });
  67286. if (matchingJoints.length) {
  67287. this._physicsPlugin.removeJoint(matchingJoints[0]);
  67288. //TODO remove it from the list as well
  67289. }
  67290. };
  67291. /**
  67292. * Called by the scene. no need to call it.
  67293. */
  67294. PhysicsEngine.prototype._step = function (delta) {
  67295. var _this = this;
  67296. //check if any mesh has no body / requires an update
  67297. this._impostors.forEach(function (impostor) {
  67298. if (impostor.isBodyInitRequired()) {
  67299. _this._physicsPlugin.generatePhysicsBody(impostor);
  67300. }
  67301. });
  67302. if (delta > 0.1) {
  67303. delta = 0.1;
  67304. }
  67305. else if (delta <= 0) {
  67306. delta = 1.0 / 60.0;
  67307. }
  67308. this._physicsPlugin.executeStep(delta, this._impostors);
  67309. };
  67310. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  67311. return this._physicsPlugin;
  67312. };
  67313. PhysicsEngine.prototype.getImpostors = function () {
  67314. return this._impostors;
  67315. };
  67316. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  67317. for (var i = 0; i < this._impostors.length; ++i) {
  67318. if (this._impostors[i].object === object) {
  67319. return this._impostors[i];
  67320. }
  67321. }
  67322. return null;
  67323. };
  67324. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  67325. for (var i = 0; i < this._impostors.length; ++i) {
  67326. if (this._impostors[i].physicsBody === body) {
  67327. return this._impostors[i];
  67328. }
  67329. }
  67330. return null;
  67331. };
  67332. // Statics
  67333. PhysicsEngine.Epsilon = 0.001;
  67334. return PhysicsEngine;
  67335. }());
  67336. BABYLON.PhysicsEngine = PhysicsEngine;
  67337. })(BABYLON || (BABYLON = {}));
  67338. //# sourceMappingURL=babylon.physicsEngine.js.map
  67339. var BABYLON;
  67340. (function (BABYLON) {
  67341. /**
  67342. * The strenght of the force in correspondence to the distance of the affected object
  67343. */
  67344. var PhysicsRadialImpulseFalloff;
  67345. (function (PhysicsRadialImpulseFalloff) {
  67346. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  67347. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  67348. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  67349. /**
  67350. * The strenght of the force in correspondence to the distance of the affected object
  67351. */
  67352. var PhysicsUpdraftMode;
  67353. (function (PhysicsUpdraftMode) {
  67354. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  67355. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  67356. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  67357. var PhysicsHelper = /** @class */ (function () {
  67358. function PhysicsHelper(scene) {
  67359. this._scene = scene;
  67360. this._physicsEngine = this._scene.getPhysicsEngine();
  67361. if (!this._physicsEngine) {
  67362. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  67363. }
  67364. }
  67365. /**
  67366. * @param {Vector3} origin the origin of the explosion
  67367. * @param {number} radius the explosion radius
  67368. * @param {number} strength the explosion strength
  67369. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67370. */
  67371. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  67372. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67373. if (!this._physicsEngine) {
  67374. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  67375. return null;
  67376. }
  67377. var impostors = this._physicsEngine.getImpostors();
  67378. if (impostors.length === 0) {
  67379. return null;
  67380. }
  67381. var event = new PhysicsRadialExplosionEvent(this._scene);
  67382. impostors.forEach(function (impostor) {
  67383. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67384. if (!impostorForceAndContactPoint) {
  67385. return;
  67386. }
  67387. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67388. });
  67389. event.dispose(false);
  67390. return event;
  67391. };
  67392. /**
  67393. * @param {Vector3} origin the origin of the explosion
  67394. * @param {number} radius the explosion radius
  67395. * @param {number} strength the explosion strength
  67396. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67397. */
  67398. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  67399. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67400. if (!this._physicsEngine) {
  67401. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67402. return null;
  67403. }
  67404. var impostors = this._physicsEngine.getImpostors();
  67405. if (impostors.length === 0) {
  67406. return null;
  67407. }
  67408. var event = new PhysicsRadialExplosionEvent(this._scene);
  67409. impostors.forEach(function (impostor) {
  67410. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67411. if (!impostorForceAndContactPoint) {
  67412. return;
  67413. }
  67414. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67415. });
  67416. event.dispose(false);
  67417. return event;
  67418. };
  67419. /**
  67420. * @param {Vector3} origin the origin of the explosion
  67421. * @param {number} radius the explosion radius
  67422. * @param {number} strength the explosion strength
  67423. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67424. */
  67425. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  67426. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67427. if (!this._physicsEngine) {
  67428. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67429. return null;
  67430. }
  67431. var impostors = this._physicsEngine.getImpostors();
  67432. if (impostors.length === 0) {
  67433. return null;
  67434. }
  67435. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  67436. event.dispose(false);
  67437. return event;
  67438. };
  67439. /**
  67440. * @param {Vector3} origin the origin of the updraft
  67441. * @param {number} radius the radius of the updraft
  67442. * @param {number} strength the strength of the updraft
  67443. * @param {number} height the height of the updraft
  67444. */
  67445. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  67446. if (!this._physicsEngine) {
  67447. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67448. return null;
  67449. }
  67450. if (this._physicsEngine.getImpostors().length === 0) {
  67451. return null;
  67452. }
  67453. var event = new PhysicsUpdraftEvent(this._physicsEngine, this._scene, origin, radius, strength, height, updraftMode);
  67454. event.dispose(false);
  67455. return event;
  67456. };
  67457. return PhysicsHelper;
  67458. }());
  67459. BABYLON.PhysicsHelper = PhysicsHelper;
  67460. /***** Radial explosion *****/
  67461. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  67462. function PhysicsRadialExplosionEvent(scene) {
  67463. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  67464. this._rays = [];
  67465. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  67466. this._scene = scene;
  67467. }
  67468. /**
  67469. * Returns the data related to the radial explosion event (sphere & rays).
  67470. * @returns {PhysicsRadialExplosionEventData}
  67471. */
  67472. PhysicsRadialExplosionEvent.prototype.getData = function () {
  67473. this._dataFetched = true;
  67474. return {
  67475. sphere: this._sphere,
  67476. rays: this._rays,
  67477. };
  67478. };
  67479. /**
  67480. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67481. * @param impostor
  67482. * @param {Vector3} origin the origin of the explosion
  67483. * @param {number} radius the explosion radius
  67484. * @param {number} strength the explosion strength
  67485. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  67486. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67487. */
  67488. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67489. if (impostor.mass === 0) {
  67490. return null;
  67491. }
  67492. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67493. return null;
  67494. }
  67495. var impostorObject = impostor.object;
  67496. var impostorObjectCenter = impostor.getObjectCenter();
  67497. var direction = impostorObjectCenter.subtract(origin);
  67498. var ray = new BABYLON.Ray(origin, direction, radius);
  67499. this._rays.push(ray);
  67500. var hit = ray.intersectsMesh(impostorObject);
  67501. var contactPoint = hit.pickedPoint;
  67502. if (!contactPoint) {
  67503. return null;
  67504. }
  67505. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67506. if (distanceFromOrigin > radius) {
  67507. return null;
  67508. }
  67509. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  67510. ? strength
  67511. : strength * (1 - (distanceFromOrigin / radius));
  67512. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67513. return { force: force, contactPoint: contactPoint };
  67514. };
  67515. /**
  67516. * Disposes the sphere.
  67517. * @param {bolean} force
  67518. */
  67519. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67520. var _this = this;
  67521. if (force === void 0) { force = true; }
  67522. if (force) {
  67523. this._sphere.dispose();
  67524. }
  67525. else {
  67526. setTimeout(function () {
  67527. if (!_this._dataFetched) {
  67528. _this._sphere.dispose();
  67529. }
  67530. }, 0);
  67531. }
  67532. };
  67533. /*** Helpers ***/
  67534. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67535. if (!this._sphere) {
  67536. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67537. this._sphere.isVisible = false;
  67538. }
  67539. };
  67540. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67541. var impostorObject = impostor.object;
  67542. this._prepareSphere();
  67543. this._sphere.position = origin;
  67544. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67545. this._sphere._updateBoundingInfo();
  67546. this._sphere.computeWorldMatrix(true);
  67547. return this._sphere.intersectsMesh(impostorObject, true);
  67548. };
  67549. return PhysicsRadialExplosionEvent;
  67550. }());
  67551. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67552. /***** Gravitational Field *****/
  67553. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67554. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67555. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67556. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67557. this._physicsHelper = physicsHelper;
  67558. this._scene = scene;
  67559. this._origin = origin;
  67560. this._radius = radius;
  67561. this._strength = strength;
  67562. this._falloff = falloff;
  67563. this._tickCallback = this._tick.bind(this);
  67564. }
  67565. /**
  67566. * Returns the data related to the gravitational field event (sphere).
  67567. * @returns {PhysicsGravitationalFieldEventData}
  67568. */
  67569. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67570. this._dataFetched = true;
  67571. return {
  67572. sphere: this._sphere,
  67573. };
  67574. };
  67575. /**
  67576. * Enables the gravitational field.
  67577. */
  67578. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67579. this._tickCallback.call(this);
  67580. this._scene.registerBeforeRender(this._tickCallback);
  67581. };
  67582. /**
  67583. * Disables the gravitational field.
  67584. */
  67585. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67586. this._scene.unregisterBeforeRender(this._tickCallback);
  67587. };
  67588. /**
  67589. * Disposes the sphere.
  67590. * @param {bolean} force
  67591. */
  67592. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67593. var _this = this;
  67594. if (force === void 0) { force = true; }
  67595. if (force) {
  67596. this._sphere.dispose();
  67597. }
  67598. else {
  67599. setTimeout(function () {
  67600. if (!_this._dataFetched) {
  67601. _this._sphere.dispose();
  67602. }
  67603. }, 0);
  67604. }
  67605. };
  67606. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67607. // Since the params won't change, we fetch the event only once
  67608. if (this._sphere) {
  67609. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67610. }
  67611. else {
  67612. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67613. if (radialExplosionEvent) {
  67614. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67615. }
  67616. }
  67617. };
  67618. return PhysicsGravitationalFieldEvent;
  67619. }());
  67620. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67621. /***** Updraft *****/
  67622. var PhysicsUpdraftEvent = /** @class */ (function () {
  67623. function PhysicsUpdraftEvent(physicsEngine, scene, origin, radius, strength, height, updraftMode) {
  67624. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67625. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67626. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67627. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67628. this._physicsEngine = physicsEngine;
  67629. this._scene = scene;
  67630. this._origin = origin;
  67631. this._radius = radius;
  67632. this._strength = strength;
  67633. this._height = height;
  67634. this._updraftMode = updraftMode;
  67635. // TODO: for this._cylinderPosition & this._originTop, take rotation into account
  67636. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67637. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67638. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67639. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67640. }
  67641. this._tickCallback = this._tick.bind(this);
  67642. }
  67643. /**
  67644. * Returns the data related to the updraft event (cylinder).
  67645. * @returns {PhysicsGravitationalFieldEventData}
  67646. */
  67647. PhysicsUpdraftEvent.prototype.getData = function () {
  67648. this._dataFetched = true;
  67649. return {
  67650. cylinder: this._cylinder,
  67651. };
  67652. };
  67653. /**
  67654. * Enables the updraft.
  67655. */
  67656. PhysicsUpdraftEvent.prototype.enable = function () {
  67657. this._tickCallback.call(this);
  67658. this._scene.registerBeforeRender(this._tickCallback);
  67659. };
  67660. /**
  67661. * Disables the cortex.
  67662. */
  67663. PhysicsUpdraftEvent.prototype.disable = function () {
  67664. this._scene.unregisterBeforeRender(this._tickCallback);
  67665. };
  67666. /**
  67667. * Disposes the sphere.
  67668. * @param {bolean} force
  67669. */
  67670. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67671. var _this = this;
  67672. if (force === void 0) { force = true; }
  67673. if (force) {
  67674. this._cylinder.dispose();
  67675. }
  67676. else {
  67677. setTimeout(function () {
  67678. if (!_this._dataFetched) {
  67679. _this._cylinder.dispose();
  67680. }
  67681. }, 0);
  67682. }
  67683. };
  67684. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67685. if (impostor.mass === 0) {
  67686. return null;
  67687. }
  67688. if (!this._intersectsWithCylinder(impostor)) {
  67689. return null;
  67690. }
  67691. var impostorObjectCenter = impostor.getObjectCenter();
  67692. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67693. var direction = this._originDirection;
  67694. }
  67695. else {
  67696. var direction = impostorObjectCenter.subtract(this._originTop);
  67697. }
  67698. var multiplier = this._strength * -1;
  67699. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67700. return { force: force, contactPoint: impostorObjectCenter };
  67701. };
  67702. PhysicsUpdraftEvent.prototype._tick = function () {
  67703. var _this = this;
  67704. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67705. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67706. if (!impostorForceAndContactPoint) {
  67707. return;
  67708. }
  67709. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67710. });
  67711. };
  67712. /*** Helpers ***/
  67713. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67714. if (!this._cylinder) {
  67715. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67716. height: this._height,
  67717. diameter: this._radius * 2,
  67718. }, this._scene);
  67719. this._cylinder.isVisible = false;
  67720. }
  67721. };
  67722. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67723. var impostorObject = impostor.object;
  67724. this._prepareCylinder();
  67725. this._cylinder.position = this._cylinderPosition;
  67726. return this._cylinder.intersectsMesh(impostorObject, true);
  67727. };
  67728. return PhysicsUpdraftEvent;
  67729. }());
  67730. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67731. })(BABYLON || (BABYLON = {}));
  67732. //# sourceMappingURL=babylon.physicsHelper.js.map
  67733. var BABYLON;
  67734. (function (BABYLON) {
  67735. var CannonJSPlugin = /** @class */ (function () {
  67736. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  67737. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  67738. if (iterations === void 0) { iterations = 10; }
  67739. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  67740. this.name = "CannonJSPlugin";
  67741. this._physicsMaterials = new Array();
  67742. this._fixedTimeStep = 1 / 60;
  67743. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  67744. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  67745. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  67746. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  67747. this._tmpPosition = BABYLON.Vector3.Zero();
  67748. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  67749. this._tmpUnityRotation = new BABYLON.Quaternion();
  67750. if (!this.isSupported()) {
  67751. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  67752. return;
  67753. }
  67754. this._extendNamespace();
  67755. this.world = new this.BJSCANNON.World();
  67756. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  67757. this.world.solver.iterations = iterations;
  67758. }
  67759. CannonJSPlugin.prototype.setGravity = function (gravity) {
  67760. this.world.gravity.copy(gravity);
  67761. };
  67762. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  67763. this._fixedTimeStep = timeStep;
  67764. };
  67765. CannonJSPlugin.prototype.getTimeStep = function () {
  67766. return this._fixedTimeStep;
  67767. };
  67768. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  67769. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  67770. };
  67771. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67772. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67773. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67774. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  67775. };
  67776. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67777. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67778. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67779. impostor.physicsBody.applyForce(impulse, worldPoint);
  67780. };
  67781. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67782. //parent-child relationship. Does this impostor has a parent impostor?
  67783. if (impostor.parent) {
  67784. if (impostor.physicsBody) {
  67785. this.removePhysicsBody(impostor);
  67786. //TODO is that needed?
  67787. impostor.forceUpdate();
  67788. }
  67789. return;
  67790. }
  67791. //should a new body be created for this impostor?
  67792. if (impostor.isBodyInitRequired()) {
  67793. var shape = this._createShape(impostor);
  67794. //unregister events, if body is being changed
  67795. var oldBody = impostor.physicsBody;
  67796. if (oldBody) {
  67797. this.removePhysicsBody(impostor);
  67798. }
  67799. //create the body and material
  67800. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  67801. var bodyCreationObject = {
  67802. mass: impostor.getParam("mass"),
  67803. material: material
  67804. };
  67805. // A simple extend, in case native options were used.
  67806. var nativeOptions = impostor.getParam("nativeOptions");
  67807. for (var key in nativeOptions) {
  67808. if (nativeOptions.hasOwnProperty(key)) {
  67809. bodyCreationObject[key] = nativeOptions[key];
  67810. }
  67811. }
  67812. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  67813. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  67814. this.world.addEventListener("preStep", impostor.beforeStep);
  67815. this.world.addEventListener("postStep", impostor.afterStep);
  67816. impostor.physicsBody.addShape(shape);
  67817. this.world.add(impostor.physicsBody);
  67818. //try to keep the body moving in the right direction by taking old properties.
  67819. //Should be tested!
  67820. if (oldBody) {
  67821. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  67822. impostor.physicsBody[param].copy(oldBody[param]);
  67823. });
  67824. }
  67825. this._processChildMeshes(impostor);
  67826. }
  67827. //now update the body's transformation
  67828. this._updatePhysicsBodyTransformation(impostor);
  67829. };
  67830. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  67831. var _this = this;
  67832. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  67833. var currentRotation = mainImpostor.object.rotationQuaternion;
  67834. if (meshChildren.length) {
  67835. var processMesh = function (localPosition, mesh) {
  67836. if (!currentRotation || !mesh.rotationQuaternion) {
  67837. return;
  67838. }
  67839. var childImpostor = mesh.getPhysicsImpostor();
  67840. if (childImpostor) {
  67841. var parent = childImpostor.parent;
  67842. if (parent !== mainImpostor) {
  67843. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67844. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67845. if (childImpostor.physicsBody) {
  67846. _this.removePhysicsBody(childImpostor);
  67847. childImpostor.physicsBody = null;
  67848. }
  67849. childImpostor.parent = mainImpostor;
  67850. childImpostor.resetUpdateFlags();
  67851. 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));
  67852. //Add the mass of the children.
  67853. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67854. }
  67855. }
  67856. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67857. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67858. };
  67859. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67860. }
  67861. };
  67862. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67863. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67864. this.world.removeEventListener("preStep", impostor.beforeStep);
  67865. this.world.removeEventListener("postStep", impostor.afterStep);
  67866. this.world.remove(impostor.physicsBody);
  67867. };
  67868. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67869. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67870. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67871. if (!mainBody || !connectedBody) {
  67872. return;
  67873. }
  67874. var constraint;
  67875. var jointData = impostorJoint.joint.jointData;
  67876. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67877. var constraintData = {
  67878. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67879. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67880. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67881. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67882. maxForce: jointData.nativeParams.maxForce,
  67883. collideConnected: !!jointData.collision
  67884. };
  67885. switch (impostorJoint.joint.type) {
  67886. case BABYLON.PhysicsJoint.HingeJoint:
  67887. case BABYLON.PhysicsJoint.Hinge2Joint:
  67888. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67889. break;
  67890. case BABYLON.PhysicsJoint.DistanceJoint:
  67891. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67892. break;
  67893. case BABYLON.PhysicsJoint.SpringJoint:
  67894. var springData = jointData;
  67895. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67896. restLength: springData.length,
  67897. stiffness: springData.stiffness,
  67898. damping: springData.damping,
  67899. localAnchorA: constraintData.pivotA,
  67900. localAnchorB: constraintData.pivotB
  67901. });
  67902. break;
  67903. case BABYLON.PhysicsJoint.LockJoint:
  67904. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67905. break;
  67906. case BABYLON.PhysicsJoint.PointToPointJoint:
  67907. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67908. default:
  67909. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67910. break;
  67911. }
  67912. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67913. constraint.collideConnected = !!jointData.collision;
  67914. impostorJoint.joint.physicsJoint = constraint;
  67915. //don't add spring as constraint, as it is not one.
  67916. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67917. this.world.addConstraint(constraint);
  67918. }
  67919. else {
  67920. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67921. constraint.applyForce();
  67922. });
  67923. }
  67924. };
  67925. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67926. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67927. };
  67928. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67929. var index;
  67930. var mat;
  67931. for (index = 0; index < this._physicsMaterials.length; index++) {
  67932. mat = this._physicsMaterials[index];
  67933. if (mat.friction === friction && mat.restitution === restitution) {
  67934. return mat;
  67935. }
  67936. }
  67937. var currentMat = new this.BJSCANNON.Material(name);
  67938. currentMat.friction = friction;
  67939. currentMat.restitution = restitution;
  67940. this._physicsMaterials.push(currentMat);
  67941. return currentMat;
  67942. };
  67943. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67944. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67945. };
  67946. CannonJSPlugin.prototype._createShape = function (impostor) {
  67947. var object = impostor.object;
  67948. var returnValue;
  67949. var extendSize = impostor.getObjectExtendSize();
  67950. switch (impostor.type) {
  67951. case BABYLON.PhysicsImpostor.SphereImpostor:
  67952. var radiusX = extendSize.x;
  67953. var radiusY = extendSize.y;
  67954. var radiusZ = extendSize.z;
  67955. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67956. break;
  67957. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67958. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67959. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67960. break;
  67961. case BABYLON.PhysicsImpostor.BoxImpostor:
  67962. var box = extendSize.scale(0.5);
  67963. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67964. break;
  67965. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67966. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67967. returnValue = new this.BJSCANNON.Plane();
  67968. break;
  67969. case BABYLON.PhysicsImpostor.MeshImpostor:
  67970. // should transform the vertex data to world coordinates!!
  67971. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67972. var rawFaces = object.getIndices ? object.getIndices() : [];
  67973. if (!rawVerts)
  67974. return;
  67975. // get only scale! so the object could transform correctly.
  67976. var oldPosition = object.position.clone();
  67977. var oldRotation = object.rotation && object.rotation.clone();
  67978. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67979. object.position.copyFromFloats(0, 0, 0);
  67980. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67981. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67982. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67983. var transform = object.computeWorldMatrix(true);
  67984. // convert rawVerts to object space
  67985. var temp = new Array();
  67986. var index;
  67987. for (index = 0; index < rawVerts.length; index += 3) {
  67988. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67989. }
  67990. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67991. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67992. //now set back the transformation!
  67993. object.position.copyFrom(oldPosition);
  67994. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67995. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67996. break;
  67997. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67998. var oldPosition2 = object.position.clone();
  67999. var oldRotation2 = object.rotation && object.rotation.clone();
  68000. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  68001. object.position.copyFromFloats(0, 0, 0);
  68002. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68003. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68004. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68005. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  68006. returnValue = this._createHeightmap(object);
  68007. object.position.copyFrom(oldPosition2);
  68008. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  68009. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  68010. object.computeWorldMatrix(true);
  68011. break;
  68012. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68013. returnValue = new this.BJSCANNON.Particle();
  68014. break;
  68015. }
  68016. return returnValue;
  68017. };
  68018. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  68019. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68020. var transform = object.computeWorldMatrix(true);
  68021. // convert rawVerts to object space
  68022. var temp = new Array();
  68023. var index;
  68024. for (index = 0; index < pos.length; index += 3) {
  68025. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  68026. }
  68027. pos = temp;
  68028. var matrix = new Array();
  68029. //For now pointDepth will not be used and will be automatically calculated.
  68030. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  68031. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  68032. var boundingInfo = object.getBoundingInfo();
  68033. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  68034. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  68035. var elementSize = dim * 2 / arraySize;
  68036. for (var i = 0; i < pos.length; i = i + 3) {
  68037. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  68038. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  68039. var y = -pos[i + 2] + minY;
  68040. if (!matrix[x]) {
  68041. matrix[x] = [];
  68042. }
  68043. if (!matrix[x][z]) {
  68044. matrix[x][z] = y;
  68045. }
  68046. matrix[x][z] = Math.max(y, matrix[x][z]);
  68047. }
  68048. for (var x = 0; x <= arraySize; ++x) {
  68049. if (!matrix[x]) {
  68050. var loc = 1;
  68051. while (!matrix[(x + loc) % arraySize]) {
  68052. loc++;
  68053. }
  68054. matrix[x] = matrix[(x + loc) % arraySize].slice();
  68055. //console.log("missing x", x);
  68056. }
  68057. for (var z = 0; z <= arraySize; ++z) {
  68058. if (!matrix[x][z]) {
  68059. var loc = 1;
  68060. var newValue;
  68061. while (newValue === undefined) {
  68062. newValue = matrix[x][(z + loc++) % arraySize];
  68063. }
  68064. matrix[x][z] = newValue;
  68065. }
  68066. }
  68067. }
  68068. var shape = new this.BJSCANNON.Heightfield(matrix, {
  68069. elementSize: elementSize
  68070. });
  68071. //For future reference, needed for body transformation
  68072. shape.minY = minY;
  68073. return shape;
  68074. };
  68075. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  68076. var object = impostor.object;
  68077. //make sure it is updated...
  68078. object.computeWorldMatrix && object.computeWorldMatrix(true);
  68079. // The delta between the mesh position and the mesh bounding box center
  68080. var bInfo = object.getBoundingInfo();
  68081. if (!bInfo)
  68082. return;
  68083. var center = impostor.getObjectCenter();
  68084. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  68085. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  68086. this._tmpPosition.copyFrom(center);
  68087. var quaternion = object.rotationQuaternion;
  68088. if (!quaternion) {
  68089. return;
  68090. }
  68091. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  68092. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  68093. //-90 DEG in X, precalculated
  68094. quaternion = quaternion.multiply(this._minus90X);
  68095. //Invert! (Precalculated, 90 deg in X)
  68096. //No need to clone. this will never change.
  68097. impostor.setDeltaRotation(this._plus90X);
  68098. }
  68099. //If it is a heightfield, if should be centered.
  68100. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  68101. var mesh = object;
  68102. var boundingInfo = mesh.getBoundingInfo();
  68103. //calculate the correct body position:
  68104. var rotationQuaternion = mesh.rotationQuaternion;
  68105. mesh.rotationQuaternion = this._tmpUnityRotation;
  68106. mesh.computeWorldMatrix(true);
  68107. //get original center with no rotation
  68108. var c = center.clone();
  68109. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  68110. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  68111. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  68112. mesh.setPivotMatrix(p);
  68113. mesh.computeWorldMatrix(true);
  68114. //calculate the translation
  68115. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  68116. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  68117. //add it inverted to the delta
  68118. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  68119. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  68120. //rotation is back
  68121. mesh.rotationQuaternion = rotationQuaternion;
  68122. mesh.setPivotMatrix(oldPivot);
  68123. mesh.computeWorldMatrix(true);
  68124. }
  68125. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  68126. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  68127. //this._tmpPosition.copyFrom(object.position);
  68128. }
  68129. impostor.setDeltaPosition(this._tmpDeltaPosition);
  68130. //Now update the impostor object
  68131. impostor.physicsBody.position.copy(this._tmpPosition);
  68132. impostor.physicsBody.quaternion.copy(quaternion);
  68133. };
  68134. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68135. impostor.object.position.copyFrom(impostor.physicsBody.position);
  68136. if (impostor.object.rotationQuaternion) {
  68137. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  68138. }
  68139. };
  68140. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68141. impostor.physicsBody.position.copy(newPosition);
  68142. impostor.physicsBody.quaternion.copy(newRotation);
  68143. };
  68144. CannonJSPlugin.prototype.isSupported = function () {
  68145. return this.BJSCANNON !== undefined;
  68146. };
  68147. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68148. impostor.physicsBody.velocity.copy(velocity);
  68149. };
  68150. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68151. impostor.physicsBody.angularVelocity.copy(velocity);
  68152. };
  68153. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68154. var v = impostor.physicsBody.velocity;
  68155. if (!v) {
  68156. return null;
  68157. }
  68158. return new BABYLON.Vector3(v.x, v.y, v.z);
  68159. };
  68160. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68161. var v = impostor.physicsBody.angularVelocity;
  68162. if (!v) {
  68163. return null;
  68164. }
  68165. return new BABYLON.Vector3(v.x, v.y, v.z);
  68166. };
  68167. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68168. impostor.physicsBody.mass = mass;
  68169. impostor.physicsBody.updateMassProperties();
  68170. };
  68171. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  68172. return impostor.physicsBody.mass;
  68173. };
  68174. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  68175. return impostor.physicsBody.material.friction;
  68176. };
  68177. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68178. impostor.physicsBody.material.friction = friction;
  68179. };
  68180. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68181. return impostor.physicsBody.material.restitution;
  68182. };
  68183. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68184. impostor.physicsBody.material.restitution = restitution;
  68185. };
  68186. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  68187. impostor.physicsBody.sleep();
  68188. };
  68189. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  68190. impostor.physicsBody.wakeUp();
  68191. };
  68192. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68193. joint.physicsJoint.distance = maxDistance;
  68194. };
  68195. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68196. // if (!motorIndex) {
  68197. // joint.physicsJoint.enableMotor();
  68198. // }
  68199. // }
  68200. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68201. // if (!motorIndex) {
  68202. // joint.physicsJoint.disableMotor();
  68203. // }
  68204. // }
  68205. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68206. if (!motorIndex) {
  68207. joint.physicsJoint.enableMotor();
  68208. joint.physicsJoint.setMotorSpeed(speed);
  68209. if (maxForce) {
  68210. this.setLimit(joint, maxForce);
  68211. }
  68212. }
  68213. };
  68214. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  68215. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  68216. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  68217. };
  68218. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68219. var body = impostor.physicsBody;
  68220. mesh.position.x = body.position.x;
  68221. mesh.position.y = body.position.y;
  68222. mesh.position.z = body.position.z;
  68223. if (mesh.rotationQuaternion) {
  68224. mesh.rotationQuaternion.x = body.quaternion.x;
  68225. mesh.rotationQuaternion.y = body.quaternion.y;
  68226. mesh.rotationQuaternion.z = body.quaternion.z;
  68227. mesh.rotationQuaternion.w = body.quaternion.w;
  68228. }
  68229. };
  68230. CannonJSPlugin.prototype.getRadius = function (impostor) {
  68231. var shape = impostor.physicsBody.shapes[0];
  68232. return shape.boundingSphereRadius;
  68233. };
  68234. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68235. var shape = impostor.physicsBody.shapes[0];
  68236. result.x = shape.halfExtents.x * 2;
  68237. result.y = shape.halfExtents.y * 2;
  68238. result.z = shape.halfExtents.z * 2;
  68239. };
  68240. CannonJSPlugin.prototype.dispose = function () {
  68241. };
  68242. CannonJSPlugin.prototype._extendNamespace = function () {
  68243. //this will force cannon to execute at least one step when using interpolation
  68244. var step_tmp1 = new this.BJSCANNON.Vec3();
  68245. var Engine = this.BJSCANNON;
  68246. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  68247. maxSubSteps = maxSubSteps || 10;
  68248. timeSinceLastCalled = timeSinceLastCalled || 0;
  68249. if (timeSinceLastCalled === 0) {
  68250. this.internalStep(dt);
  68251. this.time += dt;
  68252. }
  68253. else {
  68254. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  68255. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  68256. var t0 = performance.now();
  68257. for (var i = 0; i !== internalSteps; i++) {
  68258. this.internalStep(dt);
  68259. if (performance.now() - t0 > dt * 1000) {
  68260. break;
  68261. }
  68262. }
  68263. this.time += timeSinceLastCalled;
  68264. var h = this.time % dt;
  68265. var h_div_dt = h / dt;
  68266. var interpvelo = step_tmp1;
  68267. var bodies = this.bodies;
  68268. for (var j = 0; j !== bodies.length; j++) {
  68269. var b = bodies[j];
  68270. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  68271. b.position.vsub(b.previousPosition, interpvelo);
  68272. interpvelo.scale(h_div_dt, interpvelo);
  68273. b.position.vadd(interpvelo, b.interpolatedPosition);
  68274. }
  68275. else {
  68276. b.interpolatedPosition.copy(b.position);
  68277. b.interpolatedQuaternion.copy(b.quaternion);
  68278. }
  68279. }
  68280. }
  68281. };
  68282. };
  68283. return CannonJSPlugin;
  68284. }());
  68285. BABYLON.CannonJSPlugin = CannonJSPlugin;
  68286. })(BABYLON || (BABYLON = {}));
  68287. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  68288. var BABYLON;
  68289. (function (BABYLON) {
  68290. var OimoJSPlugin = /** @class */ (function () {
  68291. function OimoJSPlugin(iterations) {
  68292. this.name = "OimoJSPlugin";
  68293. this._tmpImpostorsArray = [];
  68294. this._tmpPositionVector = BABYLON.Vector3.Zero();
  68295. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  68296. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  68297. this.world.worldscale(1);
  68298. this.world.clear();
  68299. //making sure no stats are calculated
  68300. this.world.isNoStat = true;
  68301. }
  68302. OimoJSPlugin.prototype.setGravity = function (gravity) {
  68303. this.world.gravity.copy(gravity);
  68304. };
  68305. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  68306. this.world.timeStep = timeStep;
  68307. };
  68308. OimoJSPlugin.prototype.getTimeStep = function () {
  68309. return this.world.timeStep;
  68310. };
  68311. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  68312. var _this = this;
  68313. impostors.forEach(function (impostor) {
  68314. impostor.beforeStep();
  68315. });
  68316. this.world.step();
  68317. impostors.forEach(function (impostor) {
  68318. impostor.afterStep();
  68319. //update the ordered impostors array
  68320. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  68321. });
  68322. //check for collisions
  68323. var contact = this.world.contacts;
  68324. while (contact !== null) {
  68325. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  68326. contact = contact.next;
  68327. continue;
  68328. }
  68329. //is this body colliding with any other? get the impostor
  68330. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  68331. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  68332. if (!mainImpostor || !collidingImpostor) {
  68333. contact = contact.next;
  68334. continue;
  68335. }
  68336. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  68337. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  68338. contact = contact.next;
  68339. }
  68340. };
  68341. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68342. var mass = impostor.physicsBody.massInfo.mass;
  68343. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  68344. };
  68345. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68346. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  68347. this.applyImpulse(impostor, force, contactPoint);
  68348. };
  68349. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68350. var _this = this;
  68351. //parent-child relationship. Does this impostor has a parent impostor?
  68352. if (impostor.parent) {
  68353. if (impostor.physicsBody) {
  68354. this.removePhysicsBody(impostor);
  68355. //TODO is that needed?
  68356. impostor.forceUpdate();
  68357. }
  68358. return;
  68359. }
  68360. if (impostor.isBodyInitRequired()) {
  68361. var bodyConfig = {
  68362. name: impostor.uniqueId,
  68363. //Oimo must have mass, also for static objects.
  68364. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  68365. size: [],
  68366. type: [],
  68367. pos: [],
  68368. rot: [],
  68369. move: impostor.getParam("mass") !== 0,
  68370. //Supporting older versions of Oimo
  68371. world: this.world
  68372. };
  68373. var impostors = [impostor];
  68374. var addToArray = function (parent) {
  68375. if (!parent.getChildMeshes)
  68376. return;
  68377. parent.getChildMeshes().forEach(function (m) {
  68378. if (m.physicsImpostor) {
  68379. impostors.push(m.physicsImpostor);
  68380. //m.physicsImpostor._init();
  68381. }
  68382. });
  68383. };
  68384. addToArray(impostor.object);
  68385. var checkWithEpsilon_1 = function (value) {
  68386. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  68387. };
  68388. impostors.forEach(function (i) {
  68389. if (!impostor.object.rotationQuaternion) {
  68390. return;
  68391. }
  68392. //get the correct bounding box
  68393. var oldQuaternion = i.object.rotationQuaternion;
  68394. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  68395. x: impostor.object.rotationQuaternion.x,
  68396. y: impostor.object.rotationQuaternion.y,
  68397. z: impostor.object.rotationQuaternion.z,
  68398. s: impostor.object.rotationQuaternion.w
  68399. });
  68400. var extendSize = i.getObjectExtendSize();
  68401. if (i === impostor) {
  68402. var center = impostor.getObjectCenter();
  68403. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  68404. //Can also use Array.prototype.push.apply
  68405. bodyConfig.pos.push(center.x);
  68406. bodyConfig.pos.push(center.y);
  68407. bodyConfig.pos.push(center.z);
  68408. //tmp solution
  68409. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68410. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68411. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68412. }
  68413. else {
  68414. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  68415. bodyConfig.pos.push(localPosition.x);
  68416. bodyConfig.pos.push(localPosition.y);
  68417. bodyConfig.pos.push(localPosition.z);
  68418. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  68419. bodyConfig.rot.push(0);
  68420. bodyConfig.rot.push(0);
  68421. bodyConfig.rot.push(0);
  68422. }
  68423. // register mesh
  68424. switch (i.type) {
  68425. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68426. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  68427. case BABYLON.PhysicsImpostor.SphereImpostor:
  68428. var radiusX = extendSize.x;
  68429. var radiusY = extendSize.y;
  68430. var radiusZ = extendSize.z;
  68431. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  68432. bodyConfig.type.push('sphere');
  68433. //due to the way oimo works with compounds, add 3 times
  68434. bodyConfig.size.push(size);
  68435. bodyConfig.size.push(size);
  68436. bodyConfig.size.push(size);
  68437. break;
  68438. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68439. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  68440. var sizeY = checkWithEpsilon_1(extendSize.y);
  68441. bodyConfig.type.push('cylinder');
  68442. bodyConfig.size.push(sizeX);
  68443. bodyConfig.size.push(sizeY);
  68444. //due to the way oimo works with compounds, add one more value.
  68445. bodyConfig.size.push(sizeY);
  68446. break;
  68447. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68448. case BABYLON.PhysicsImpostor.BoxImpostor:
  68449. default:
  68450. var sizeX = checkWithEpsilon_1(extendSize.x);
  68451. var sizeY = checkWithEpsilon_1(extendSize.y);
  68452. var sizeZ = checkWithEpsilon_1(extendSize.z);
  68453. bodyConfig.type.push('box');
  68454. bodyConfig.size.push(sizeX);
  68455. bodyConfig.size.push(sizeY);
  68456. bodyConfig.size.push(sizeZ);
  68457. break;
  68458. }
  68459. //actually not needed, but hey...
  68460. i.object.rotationQuaternion = oldQuaternion;
  68461. });
  68462. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  68463. }
  68464. else {
  68465. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  68466. }
  68467. impostor.setDeltaPosition(this._tmpPositionVector);
  68468. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  68469. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  68470. };
  68471. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68472. //impostor.physicsBody.dispose();
  68473. //Same as : (older oimo versions)
  68474. this.world.removeRigidBody(impostor.physicsBody);
  68475. };
  68476. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68477. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68478. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68479. if (!mainBody || !connectedBody) {
  68480. return;
  68481. }
  68482. var jointData = impostorJoint.joint.jointData;
  68483. var options = jointData.nativeParams || {};
  68484. var type;
  68485. var nativeJointData = {
  68486. body1: mainBody,
  68487. body2: connectedBody,
  68488. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  68489. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  68490. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  68491. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  68492. min: options.min,
  68493. max: options.max,
  68494. collision: options.collision || jointData.collision,
  68495. spring: options.spring,
  68496. //supporting older version of Oimo
  68497. world: this.world
  68498. };
  68499. switch (impostorJoint.joint.type) {
  68500. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68501. type = "jointBall";
  68502. break;
  68503. case BABYLON.PhysicsJoint.SpringJoint:
  68504. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  68505. var springData = jointData;
  68506. nativeJointData.min = springData.length || nativeJointData.min;
  68507. //Max should also be set, just make sure it is at least min
  68508. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  68509. case BABYLON.PhysicsJoint.DistanceJoint:
  68510. type = "jointDistance";
  68511. nativeJointData.max = jointData.maxDistance;
  68512. break;
  68513. case BABYLON.PhysicsJoint.PrismaticJoint:
  68514. type = "jointPrisme";
  68515. break;
  68516. case BABYLON.PhysicsJoint.SliderJoint:
  68517. type = "jointSlide";
  68518. break;
  68519. case BABYLON.PhysicsJoint.WheelJoint:
  68520. type = "jointWheel";
  68521. break;
  68522. case BABYLON.PhysicsJoint.HingeJoint:
  68523. default:
  68524. type = "jointHinge";
  68525. break;
  68526. }
  68527. nativeJointData.type = type;
  68528. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68529. };
  68530. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68531. //Bug in Oimo prevents us from disposing a joint in the playground
  68532. //joint.joint.physicsJoint.dispose();
  68533. //So we will bruteforce it!
  68534. try {
  68535. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68536. }
  68537. catch (e) {
  68538. BABYLON.Tools.Warn(e);
  68539. }
  68540. };
  68541. OimoJSPlugin.prototype.isSupported = function () {
  68542. return this.BJSOIMO !== undefined;
  68543. };
  68544. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68545. if (!impostor.physicsBody.sleeping) {
  68546. //TODO check that
  68547. if (impostor.physicsBody.shapes.next) {
  68548. var parentShape = this._getLastShape(impostor.physicsBody);
  68549. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68550. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68551. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68552. }
  68553. else {
  68554. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68555. }
  68556. if (impostor.object.rotationQuaternion) {
  68557. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68558. impostor.object.rotationQuaternion.normalize();
  68559. }
  68560. }
  68561. };
  68562. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68563. var body = impostor.physicsBody;
  68564. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68565. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68566. body.syncShapes();
  68567. body.awake();
  68568. };
  68569. OimoJSPlugin.prototype._getLastShape = function (body) {
  68570. var lastShape = body.shapes;
  68571. while (lastShape.next) {
  68572. lastShape = lastShape.next;
  68573. }
  68574. return lastShape;
  68575. };
  68576. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68577. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68578. };
  68579. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68580. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68581. };
  68582. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68583. var v = impostor.physicsBody.linearVelocity;
  68584. if (!v) {
  68585. return null;
  68586. }
  68587. return new BABYLON.Vector3(v.x, v.y, v.z);
  68588. };
  68589. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68590. var v = impostor.physicsBody.angularVelocity;
  68591. if (!v) {
  68592. return null;
  68593. }
  68594. return new BABYLON.Vector3(v.x, v.y, v.z);
  68595. };
  68596. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68597. var staticBody = mass === 0;
  68598. //this will actually set the body's density and not its mass.
  68599. //But this is how oimo treats the mass variable.
  68600. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68601. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68602. };
  68603. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68604. return impostor.physicsBody.shapes.density;
  68605. };
  68606. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68607. return impostor.physicsBody.shapes.friction;
  68608. };
  68609. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68610. impostor.physicsBody.shapes.friction = friction;
  68611. };
  68612. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68613. return impostor.physicsBody.shapes.restitution;
  68614. };
  68615. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68616. impostor.physicsBody.shapes.restitution = restitution;
  68617. };
  68618. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68619. impostor.physicsBody.sleep();
  68620. };
  68621. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68622. impostor.physicsBody.awake();
  68623. };
  68624. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68625. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68626. if (minDistance !== void 0) {
  68627. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68628. }
  68629. };
  68630. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68631. //TODO separate rotational and transational motors.
  68632. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68633. if (motor) {
  68634. motor.setMotor(speed, maxForce);
  68635. }
  68636. };
  68637. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68638. //TODO separate rotational and transational motors.
  68639. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68640. if (motor) {
  68641. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68642. }
  68643. };
  68644. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68645. var body = impostor.physicsBody;
  68646. mesh.position.x = body.position.x;
  68647. mesh.position.y = body.position.y;
  68648. mesh.position.z = body.position.z;
  68649. if (mesh.rotationQuaternion) {
  68650. mesh.rotationQuaternion.x = body.orientation.x;
  68651. mesh.rotationQuaternion.y = body.orientation.y;
  68652. mesh.rotationQuaternion.z = body.orientation.z;
  68653. mesh.rotationQuaternion.w = body.orientation.s;
  68654. }
  68655. };
  68656. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68657. return impostor.physicsBody.shapes.radius;
  68658. };
  68659. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68660. var shape = impostor.physicsBody.shapes;
  68661. result.x = shape.halfWidth * 2;
  68662. result.y = shape.halfHeight * 2;
  68663. result.z = shape.halfDepth * 2;
  68664. };
  68665. OimoJSPlugin.prototype.dispose = function () {
  68666. this.world.clear();
  68667. };
  68668. return OimoJSPlugin;
  68669. }());
  68670. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68671. })(BABYLON || (BABYLON = {}));
  68672. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68673. var BABYLON;
  68674. (function (BABYLON) {
  68675. var Internals;
  68676. (function (Internals) {
  68677. /*
  68678. * Based on jsTGALoader - Javascript loader for TGA file
  68679. * By Vincent Thibault
  68680. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68681. */
  68682. var TGATools = /** @class */ (function () {
  68683. function TGATools() {
  68684. }
  68685. TGATools.GetTGAHeader = function (data) {
  68686. var offset = 0;
  68687. var header = {
  68688. id_length: data[offset++],
  68689. colormap_type: data[offset++],
  68690. image_type: data[offset++],
  68691. colormap_index: data[offset++] | data[offset++] << 8,
  68692. colormap_length: data[offset++] | data[offset++] << 8,
  68693. colormap_size: data[offset++],
  68694. origin: [
  68695. data[offset++] | data[offset++] << 8,
  68696. data[offset++] | data[offset++] << 8
  68697. ],
  68698. width: data[offset++] | data[offset++] << 8,
  68699. height: data[offset++] | data[offset++] << 8,
  68700. pixel_size: data[offset++],
  68701. flags: data[offset++]
  68702. };
  68703. return header;
  68704. };
  68705. TGATools.UploadContent = function (gl, data) {
  68706. // Not enough data to contain header ?
  68707. if (data.length < 19) {
  68708. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68709. return;
  68710. }
  68711. // Read Header
  68712. var offset = 18;
  68713. var header = TGATools.GetTGAHeader(data);
  68714. // Assume it's a valid Targa file.
  68715. if (header.id_length + offset > data.length) {
  68716. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  68717. return;
  68718. }
  68719. // Skip not needed data
  68720. offset += header.id_length;
  68721. var use_rle = false;
  68722. var use_pal = false;
  68723. var use_grey = false;
  68724. // Get some informations.
  68725. switch (header.image_type) {
  68726. case TGATools._TYPE_RLE_INDEXED:
  68727. use_rle = true;
  68728. case TGATools._TYPE_INDEXED:
  68729. use_pal = true;
  68730. break;
  68731. case TGATools._TYPE_RLE_RGB:
  68732. use_rle = true;
  68733. case TGATools._TYPE_RGB:
  68734. // use_rgb = true;
  68735. break;
  68736. case TGATools._TYPE_RLE_GREY:
  68737. use_rle = true;
  68738. case TGATools._TYPE_GREY:
  68739. use_grey = true;
  68740. break;
  68741. }
  68742. var pixel_data;
  68743. // var numAlphaBits = header.flags & 0xf;
  68744. var pixel_size = header.pixel_size >> 3;
  68745. var pixel_total = header.width * header.height * pixel_size;
  68746. // Read palettes
  68747. var palettes;
  68748. if (use_pal) {
  68749. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  68750. }
  68751. // Read LRE
  68752. if (use_rle) {
  68753. pixel_data = new Uint8Array(pixel_total);
  68754. var c, count, i;
  68755. var localOffset = 0;
  68756. var pixels = new Uint8Array(pixel_size);
  68757. while (offset < pixel_total && localOffset < pixel_total) {
  68758. c = data[offset++];
  68759. count = (c & 0x7f) + 1;
  68760. // RLE pixels
  68761. if (c & 0x80) {
  68762. // Bind pixel tmp array
  68763. for (i = 0; i < pixel_size; ++i) {
  68764. pixels[i] = data[offset++];
  68765. }
  68766. // Copy pixel array
  68767. for (i = 0; i < count; ++i) {
  68768. pixel_data.set(pixels, localOffset + i * pixel_size);
  68769. }
  68770. localOffset += pixel_size * count;
  68771. }
  68772. else {
  68773. count *= pixel_size;
  68774. for (i = 0; i < count; ++i) {
  68775. pixel_data[localOffset + i] = data[offset++];
  68776. }
  68777. localOffset += count;
  68778. }
  68779. }
  68780. }
  68781. else {
  68782. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  68783. }
  68784. // Load to texture
  68785. var x_start, y_start, x_step, y_step, y_end, x_end;
  68786. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  68787. default:
  68788. case TGATools._ORIGIN_UL:
  68789. x_start = 0;
  68790. x_step = 1;
  68791. x_end = header.width;
  68792. y_start = 0;
  68793. y_step = 1;
  68794. y_end = header.height;
  68795. break;
  68796. case TGATools._ORIGIN_BL:
  68797. x_start = 0;
  68798. x_step = 1;
  68799. x_end = header.width;
  68800. y_start = header.height - 1;
  68801. y_step = -1;
  68802. y_end = -1;
  68803. break;
  68804. case TGATools._ORIGIN_UR:
  68805. x_start = header.width - 1;
  68806. x_step = -1;
  68807. x_end = -1;
  68808. y_start = 0;
  68809. y_step = 1;
  68810. y_end = header.height;
  68811. break;
  68812. case TGATools._ORIGIN_BR:
  68813. x_start = header.width - 1;
  68814. x_step = -1;
  68815. x_end = -1;
  68816. y_start = header.height - 1;
  68817. y_step = -1;
  68818. y_end = -1;
  68819. break;
  68820. }
  68821. // Load the specify method
  68822. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  68823. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  68824. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68825. };
  68826. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68827. var image = pixel_data, colormap = palettes;
  68828. var width = header.width, height = header.height;
  68829. var color, i = 0, x, y;
  68830. var imageData = new Uint8Array(width * height * 4);
  68831. for (y = y_start; y !== y_end; y += y_step) {
  68832. for (x = x_start; x !== x_end; x += x_step, i++) {
  68833. color = image[i];
  68834. imageData[(x + width * y) * 4 + 3] = 255;
  68835. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  68836. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  68837. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  68838. }
  68839. }
  68840. return imageData;
  68841. };
  68842. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68843. var image = pixel_data;
  68844. var width = header.width, height = header.height;
  68845. var color, i = 0, x, y;
  68846. var imageData = new Uint8Array(width * height * 4);
  68847. for (y = y_start; y !== y_end; y += y_step) {
  68848. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68849. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  68850. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  68851. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  68852. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  68853. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  68854. }
  68855. }
  68856. return imageData;
  68857. };
  68858. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68859. var image = pixel_data;
  68860. var width = header.width, height = header.height;
  68861. var i = 0, x, y;
  68862. var imageData = new Uint8Array(width * height * 4);
  68863. for (y = y_start; y !== y_end; y += y_step) {
  68864. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  68865. imageData[(x + width * y) * 4 + 3] = 255;
  68866. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68867. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68868. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68869. }
  68870. }
  68871. return imageData;
  68872. };
  68873. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68874. var image = pixel_data;
  68875. var width = header.width, height = header.height;
  68876. var i = 0, x, y;
  68877. var imageData = new Uint8Array(width * height * 4);
  68878. for (y = y_start; y !== y_end; y += y_step) {
  68879. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  68880. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68881. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68882. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68883. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68884. }
  68885. }
  68886. return imageData;
  68887. };
  68888. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68889. var image = pixel_data;
  68890. var width = header.width, height = header.height;
  68891. var color, i = 0, x, y;
  68892. var imageData = new Uint8Array(width * height * 4);
  68893. for (y = y_start; y !== y_end; y += y_step) {
  68894. for (x = x_start; x !== x_end; x += x_step, i++) {
  68895. color = image[i];
  68896. imageData[(x + width * y) * 4 + 0] = color;
  68897. imageData[(x + width * y) * 4 + 1] = color;
  68898. imageData[(x + width * y) * 4 + 2] = color;
  68899. imageData[(x + width * y) * 4 + 3] = 255;
  68900. }
  68901. }
  68902. return imageData;
  68903. };
  68904. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68905. var image = pixel_data;
  68906. var width = header.width, height = header.height;
  68907. var i = 0, x, y;
  68908. var imageData = new Uint8Array(width * height * 4);
  68909. for (y = y_start; y !== y_end; y += y_step) {
  68910. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68911. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68912. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68913. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68914. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68915. }
  68916. }
  68917. return imageData;
  68918. };
  68919. //private static _TYPE_NO_DATA = 0;
  68920. TGATools._TYPE_INDEXED = 1;
  68921. TGATools._TYPE_RGB = 2;
  68922. TGATools._TYPE_GREY = 3;
  68923. TGATools._TYPE_RLE_INDEXED = 9;
  68924. TGATools._TYPE_RLE_RGB = 10;
  68925. TGATools._TYPE_RLE_GREY = 11;
  68926. TGATools._ORIGIN_MASK = 0x30;
  68927. TGATools._ORIGIN_SHIFT = 0x04;
  68928. TGATools._ORIGIN_BL = 0x00;
  68929. TGATools._ORIGIN_BR = 0x01;
  68930. TGATools._ORIGIN_UL = 0x02;
  68931. TGATools._ORIGIN_UR = 0x03;
  68932. return TGATools;
  68933. }());
  68934. Internals.TGATools = TGATools;
  68935. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68936. })(BABYLON || (BABYLON = {}));
  68937. //# sourceMappingURL=babylon.tga.js.map
  68938. var BABYLON;
  68939. (function (BABYLON) {
  68940. var Internals;
  68941. (function (Internals) {
  68942. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68943. // All values and structures referenced from:
  68944. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68945. var DDS_MAGIC = 0x20534444;
  68946. var
  68947. //DDSD_CAPS = 0x1,
  68948. //DDSD_HEIGHT = 0x2,
  68949. //DDSD_WIDTH = 0x4,
  68950. //DDSD_PITCH = 0x8,
  68951. //DDSD_PIXELFORMAT = 0x1000,
  68952. DDSD_MIPMAPCOUNT = 0x20000;
  68953. //DDSD_LINEARSIZE = 0x80000,
  68954. //DDSD_DEPTH = 0x800000;
  68955. // var DDSCAPS_COMPLEX = 0x8,
  68956. // DDSCAPS_MIPMAP = 0x400000,
  68957. // DDSCAPS_TEXTURE = 0x1000;
  68958. var DDSCAPS2_CUBEMAP = 0x200;
  68959. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68960. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68961. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68962. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68963. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68964. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68965. // DDSCAPS2_VOLUME = 0x200000;
  68966. var
  68967. //DDPF_ALPHAPIXELS = 0x1,
  68968. //DDPF_ALPHA = 0x2,
  68969. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68970. //DDPF_YUV = 0x200,
  68971. DDPF_LUMINANCE = 0x20000;
  68972. function FourCCToInt32(value) {
  68973. return value.charCodeAt(0) +
  68974. (value.charCodeAt(1) << 8) +
  68975. (value.charCodeAt(2) << 16) +
  68976. (value.charCodeAt(3) << 24);
  68977. }
  68978. function Int32ToFourCC(value) {
  68979. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68980. }
  68981. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68982. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68983. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68984. var FOURCC_DX10 = FourCCToInt32("DX10");
  68985. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68986. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68987. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68988. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68989. var headerLengthInt = 31; // The header length in 32 bit ints
  68990. // Offsets into the header array
  68991. var off_magic = 0;
  68992. var off_size = 1;
  68993. var off_flags = 2;
  68994. var off_height = 3;
  68995. var off_width = 4;
  68996. var off_mipmapCount = 7;
  68997. var off_pfFlags = 20;
  68998. var off_pfFourCC = 21;
  68999. var off_RGBbpp = 22;
  69000. // var off_RMask = 23;
  69001. // var off_GMask = 24;
  69002. // var off_BMask = 25;
  69003. // var off_AMask = 26;
  69004. // var off_caps1 = 27;
  69005. var off_caps2 = 28;
  69006. // var off_caps3 = 29;
  69007. // var off_caps4 = 30;
  69008. var off_dxgiFormat = 32;
  69009. ;
  69010. var DDSTools = /** @class */ (function () {
  69011. function DDSTools() {
  69012. }
  69013. DDSTools.GetDDSInfo = function (arrayBuffer) {
  69014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69015. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  69016. var mipmapCount = 1;
  69017. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  69018. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69019. }
  69020. var fourCC = header[off_pfFourCC];
  69021. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  69022. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69023. switch (fourCC) {
  69024. case FOURCC_D3DFMT_R16G16B16A16F:
  69025. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69026. break;
  69027. case FOURCC_D3DFMT_R32G32B32A32F:
  69028. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69029. break;
  69030. case FOURCC_DX10:
  69031. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  69032. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69033. break;
  69034. }
  69035. }
  69036. return {
  69037. width: header[off_width],
  69038. height: header[off_height],
  69039. mipmapCount: mipmapCount,
  69040. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  69041. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  69042. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  69043. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  69044. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  69045. dxgiFormat: dxgiFormat,
  69046. textureType: textureType
  69047. };
  69048. };
  69049. DDSTools._ToHalfFloat = function (value) {
  69050. if (!DDSTools._FloatView) {
  69051. DDSTools._FloatView = new Float32Array(1);
  69052. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  69053. }
  69054. DDSTools._FloatView[0] = value;
  69055. var x = DDSTools._Int32View[0];
  69056. var bits = (x >> 16) & 0x8000; /* Get the sign */
  69057. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  69058. var e = (x >> 23) & 0xff; /* Using int is faster here */
  69059. /* If zero, or denormal, or exponent underflows too much for a denormal
  69060. * half, return signed zero. */
  69061. if (e < 103) {
  69062. return bits;
  69063. }
  69064. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  69065. if (e > 142) {
  69066. bits |= 0x7c00;
  69067. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  69068. * not Inf, so make sure we set one mantissa bit too. */
  69069. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  69070. return bits;
  69071. }
  69072. /* If exponent underflows but not too much, return a denormal */
  69073. if (e < 113) {
  69074. m |= 0x0800;
  69075. /* Extra rounding may overflow and set mantissa to 0 and exponent
  69076. * to 1, which is OK. */
  69077. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  69078. return bits;
  69079. }
  69080. bits |= ((e - 112) << 10) | (m >> 1);
  69081. bits += m & 1;
  69082. return bits;
  69083. };
  69084. DDSTools._FromHalfFloat = function (value) {
  69085. var s = (value & 0x8000) >> 15;
  69086. var e = (value & 0x7C00) >> 10;
  69087. var f = value & 0x03FF;
  69088. if (e === 0) {
  69089. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  69090. }
  69091. else if (e == 0x1F) {
  69092. return f ? NaN : ((s ? -1 : 1) * Infinity);
  69093. }
  69094. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  69095. };
  69096. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69097. var destArray = new Float32Array(dataLength);
  69098. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69099. var index = 0;
  69100. for (var y = 0; y < height; y++) {
  69101. for (var x = 0; x < width; x++) {
  69102. var srcPos = (x + y * width) * 4;
  69103. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  69104. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  69105. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  69106. if (DDSTools.StoreLODInAlphaChannel) {
  69107. destArray[index + 3] = lod;
  69108. }
  69109. else {
  69110. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  69111. }
  69112. index += 4;
  69113. }
  69114. }
  69115. return destArray;
  69116. };
  69117. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69118. if (DDSTools.StoreLODInAlphaChannel) {
  69119. var destArray = new Uint16Array(dataLength);
  69120. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69121. var index = 0;
  69122. for (var y = 0; y < height; y++) {
  69123. for (var x = 0; x < width; x++) {
  69124. var srcPos = (x + y * width) * 4;
  69125. destArray[index] = srcData[srcPos];
  69126. destArray[index + 1] = srcData[srcPos + 1];
  69127. destArray[index + 2] = srcData[srcPos + 2];
  69128. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  69129. index += 4;
  69130. }
  69131. }
  69132. return destArray;
  69133. }
  69134. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  69135. };
  69136. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69137. if (DDSTools.StoreLODInAlphaChannel) {
  69138. var destArray = new Float32Array(dataLength);
  69139. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69140. var index = 0;
  69141. for (var y = 0; y < height; y++) {
  69142. for (var x = 0; x < width; x++) {
  69143. var srcPos = (x + y * width) * 4;
  69144. destArray[index] = srcData[srcPos];
  69145. destArray[index + 1] = srcData[srcPos + 1];
  69146. destArray[index + 2] = srcData[srcPos + 2];
  69147. destArray[index + 3] = lod;
  69148. index += 4;
  69149. }
  69150. }
  69151. return destArray;
  69152. }
  69153. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  69154. };
  69155. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69156. var destArray = new Uint8Array(dataLength);
  69157. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69158. var index = 0;
  69159. for (var y = 0; y < height; y++) {
  69160. for (var x = 0; x < width; x++) {
  69161. var srcPos = (x + y * width) * 4;
  69162. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  69163. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  69164. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  69165. if (DDSTools.StoreLODInAlphaChannel) {
  69166. destArray[index + 3] = lod;
  69167. }
  69168. else {
  69169. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  69170. }
  69171. index += 4;
  69172. }
  69173. }
  69174. return destArray;
  69175. };
  69176. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69177. var destArray = new Uint8Array(dataLength);
  69178. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69179. var index = 0;
  69180. for (var y = 0; y < height; y++) {
  69181. for (var x = 0; x < width; x++) {
  69182. var srcPos = (x + y * width) * 4;
  69183. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  69184. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  69185. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  69186. if (DDSTools.StoreLODInAlphaChannel) {
  69187. destArray[index + 3] = lod;
  69188. }
  69189. else {
  69190. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  69191. }
  69192. index += 4;
  69193. }
  69194. }
  69195. return destArray;
  69196. };
  69197. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69198. var byteArray = new Uint8Array(dataLength);
  69199. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69200. var index = 0;
  69201. for (var y = 0; y < height; y++) {
  69202. for (var x = 0; x < width; x++) {
  69203. var srcPos = (x + y * width) * 4;
  69204. byteArray[index] = srcData[srcPos + 2];
  69205. byteArray[index + 1] = srcData[srcPos + 1];
  69206. byteArray[index + 2] = srcData[srcPos];
  69207. byteArray[index + 3] = srcData[srcPos + 3];
  69208. index += 4;
  69209. }
  69210. }
  69211. return byteArray;
  69212. };
  69213. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69214. var byteArray = new Uint8Array(dataLength);
  69215. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69216. var index = 0;
  69217. for (var y = 0; y < height; y++) {
  69218. for (var x = 0; x < width; x++) {
  69219. var srcPos = (x + y * width) * 3;
  69220. byteArray[index] = srcData[srcPos + 2];
  69221. byteArray[index + 1] = srcData[srcPos + 1];
  69222. byteArray[index + 2] = srcData[srcPos];
  69223. index += 3;
  69224. }
  69225. }
  69226. return byteArray;
  69227. };
  69228. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69229. var byteArray = new Uint8Array(dataLength);
  69230. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69231. var index = 0;
  69232. for (var y = 0; y < height; y++) {
  69233. for (var x = 0; x < width; x++) {
  69234. var srcPos = (x + y * width);
  69235. byteArray[index] = srcData[srcPos];
  69236. index++;
  69237. }
  69238. }
  69239. return byteArray;
  69240. };
  69241. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  69242. if (lodIndex === void 0) { lodIndex = -1; }
  69243. var ext = engine.getCaps().s3tc;
  69244. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69245. var fourCC, width, height, dataLength = 0, dataOffset;
  69246. var byteArray, mipmapCount, mip;
  69247. var internalFormat = 0;
  69248. var format = 0;
  69249. var blockBytes = 1;
  69250. if (header[off_magic] !== DDS_MAGIC) {
  69251. BABYLON.Tools.Error("Invalid magic number in DDS header");
  69252. return;
  69253. }
  69254. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  69255. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  69256. return;
  69257. }
  69258. if (info.isCompressed && !ext) {
  69259. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  69260. return;
  69261. }
  69262. var bpp = header[off_RGBbpp];
  69263. dataOffset = header[off_size] + 4;
  69264. var computeFormats = false;
  69265. if (info.isFourCC) {
  69266. fourCC = header[off_pfFourCC];
  69267. switch (fourCC) {
  69268. case FOURCC_DXT1:
  69269. blockBytes = 8;
  69270. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  69271. break;
  69272. case FOURCC_DXT3:
  69273. blockBytes = 16;
  69274. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  69275. break;
  69276. case FOURCC_DXT5:
  69277. blockBytes = 16;
  69278. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  69279. break;
  69280. case FOURCC_D3DFMT_R16G16B16A16F:
  69281. computeFormats = true;
  69282. break;
  69283. case FOURCC_D3DFMT_R32G32B32A32F:
  69284. computeFormats = true;
  69285. break;
  69286. case FOURCC_DX10:
  69287. // There is an additionnal header so dataOffset need to be changed
  69288. dataOffset += 5 * 4; // 5 uints
  69289. var supported = false;
  69290. switch (info.dxgiFormat) {
  69291. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  69292. computeFormats = true;
  69293. supported = true;
  69294. break;
  69295. case DXGI_FORMAT_B8G8R8X8_UNORM:
  69296. info.isRGB = true;
  69297. info.isFourCC = false;
  69298. bpp = 32;
  69299. supported = true;
  69300. break;
  69301. }
  69302. if (supported) {
  69303. break;
  69304. }
  69305. default:
  69306. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  69307. return;
  69308. }
  69309. }
  69310. if (computeFormats) {
  69311. format = engine._getWebGLTextureType(info.textureType);
  69312. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69313. }
  69314. mipmapCount = 1;
  69315. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  69316. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69317. }
  69318. for (var face = 0; face < faces; face++) {
  69319. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  69320. width = header[off_width];
  69321. height = header[off_height];
  69322. for (mip = 0; mip < mipmapCount; ++mip) {
  69323. if (lodIndex === -1 || lodIndex === mip) {
  69324. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  69325. var i = (lodIndex === -1) ? mip : 0;
  69326. if (!info.isCompressed && info.isFourCC) {
  69327. dataLength = width * height * 4;
  69328. var floatArray = null;
  69329. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  69330. if (bpp === 128) {
  69331. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69332. }
  69333. else if (bpp === 64) {
  69334. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69335. }
  69336. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69337. format = engine._getWebGLTextureType(info.textureType);
  69338. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69339. }
  69340. else {
  69341. if (bpp === 128) {
  69342. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69343. }
  69344. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  69345. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69346. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69347. format = engine._getWebGLTextureType(info.textureType);
  69348. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69349. }
  69350. else {
  69351. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69352. }
  69353. }
  69354. if (floatArray) {
  69355. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  69356. }
  69357. }
  69358. else if (info.isRGB) {
  69359. if (bpp === 24) {
  69360. dataLength = width * height * 3;
  69361. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69362. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  69363. }
  69364. else {
  69365. dataLength = width * height * 4;
  69366. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69367. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  69368. }
  69369. }
  69370. else if (info.isLuminance) {
  69371. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  69372. var unpaddedRowSize = width;
  69373. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  69374. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  69375. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69376. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  69377. }
  69378. else {
  69379. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  69380. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  69381. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  69382. }
  69383. }
  69384. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  69385. width *= 0.5;
  69386. height *= 0.5;
  69387. width = Math.max(1.0, width);
  69388. height = Math.max(1.0, height);
  69389. }
  69390. if (currentFace !== undefined) {
  69391. // Loading a single face
  69392. break;
  69393. }
  69394. }
  69395. };
  69396. DDSTools.StoreLODInAlphaChannel = false;
  69397. return DDSTools;
  69398. }());
  69399. Internals.DDSTools = DDSTools;
  69400. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69401. })(BABYLON || (BABYLON = {}));
  69402. //# sourceMappingURL=babylon.dds.js.map
  69403. var BABYLON;
  69404. (function (BABYLON) {
  69405. var Internals;
  69406. (function (Internals) {
  69407. /**
  69408. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  69409. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  69410. */
  69411. var KhronosTextureContainer = /** @class */ (function () {
  69412. /**
  69413. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  69414. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  69415. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  69416. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  69417. */
  69418. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  69419. this.arrayBuffer = arrayBuffer;
  69420. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  69421. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  69422. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  69423. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  69424. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  69425. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  69426. BABYLON.Tools.Error("texture missing KTX identifier");
  69427. return;
  69428. }
  69429. // load the reset of the header in native 32 bit int
  69430. var header = new Int32Array(this.arrayBuffer, 12, 13);
  69431. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  69432. var oppositeEndianess = header[0] === 0x01020304;
  69433. // read all the header elements in order they exist in the file, without modification (sans endainness)
  69434. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  69435. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  69436. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  69437. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  69438. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  69439. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  69440. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  69441. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  69442. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  69443. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  69444. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  69445. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  69446. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  69447. if (this.glType !== 0) {
  69448. BABYLON.Tools.Error("only compressed formats currently supported");
  69449. return;
  69450. }
  69451. else {
  69452. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  69453. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  69454. }
  69455. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  69456. BABYLON.Tools.Error("only 2D textures currently supported");
  69457. return;
  69458. }
  69459. if (this.numberOfArrayElements !== 0) {
  69460. BABYLON.Tools.Error("texture arrays not currently supported");
  69461. return;
  69462. }
  69463. if (this.numberOfFaces !== facesExpected) {
  69464. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  69465. return;
  69466. }
  69467. // we now have a completely validated file, so could use existence of loadType as success
  69468. // would need to make this more elaborate & adjust checks above to support more than one load type
  69469. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  69470. }
  69471. // not as fast hardware based, but will probably never need to use
  69472. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  69473. return ((val & 0xFF) << 24)
  69474. | ((val & 0xFF00) << 8)
  69475. | ((val >> 8) & 0xFF00)
  69476. | ((val >> 24) & 0xFF);
  69477. };
  69478. /**
  69479. * It is assumed that the texture has already been created & is currently bound
  69480. */
  69481. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  69482. switch (this.loadType) {
  69483. case KhronosTextureContainer.COMPRESSED_2D:
  69484. this._upload2DCompressedLevels(gl, loadMipmaps);
  69485. break;
  69486. case KhronosTextureContainer.TEX_2D:
  69487. case KhronosTextureContainer.COMPRESSED_3D:
  69488. case KhronosTextureContainer.TEX_3D:
  69489. }
  69490. };
  69491. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  69492. // initialize width & height for level 1
  69493. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  69494. var width = this.pixelWidth;
  69495. var height = this.pixelHeight;
  69496. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  69497. for (var level = 0; level < mipmapCount; level++) {
  69498. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  69499. for (var face = 0; face < this.numberOfFaces; face++) {
  69500. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  69501. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  69502. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  69503. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  69504. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  69505. }
  69506. width = Math.max(1.0, width * 0.5);
  69507. height = Math.max(1.0, height * 0.5);
  69508. }
  69509. };
  69510. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  69511. // load types
  69512. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  69513. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  69514. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  69515. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  69516. return KhronosTextureContainer;
  69517. }());
  69518. Internals.KhronosTextureContainer = KhronosTextureContainer;
  69519. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69520. })(BABYLON || (BABYLON = {}));
  69521. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69522. var BABYLON;
  69523. (function (BABYLON) {
  69524. var Debug;
  69525. (function (Debug) {
  69526. /**
  69527. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69528. */
  69529. var SkeletonViewer = /** @class */ (function () {
  69530. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69531. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69532. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69533. this.skeleton = skeleton;
  69534. this.mesh = mesh;
  69535. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69536. this.renderingGroupId = renderingGroupId;
  69537. this.color = BABYLON.Color3.White();
  69538. this._debugLines = new Array();
  69539. this._isEnabled = false;
  69540. this._scene = scene;
  69541. this.update();
  69542. this._renderFunction = this.update.bind(this);
  69543. }
  69544. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69545. get: function () {
  69546. return this._isEnabled;
  69547. },
  69548. set: function (value) {
  69549. if (this._isEnabled === value) {
  69550. return;
  69551. }
  69552. this._isEnabled = value;
  69553. if (value) {
  69554. this._scene.registerBeforeRender(this._renderFunction);
  69555. }
  69556. else {
  69557. this._scene.unregisterBeforeRender(this._renderFunction);
  69558. }
  69559. },
  69560. enumerable: true,
  69561. configurable: true
  69562. });
  69563. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69564. if (x === void 0) { x = 0; }
  69565. if (y === void 0) { y = 0; }
  69566. if (z === void 0) { z = 0; }
  69567. var tmat = BABYLON.Tmp.Matrix[0];
  69568. var parentBone = bone.getParent();
  69569. tmat.copyFrom(bone.getLocalMatrix());
  69570. if (x !== 0 || y !== 0 || z !== 0) {
  69571. var tmat2 = BABYLON.Tmp.Matrix[1];
  69572. BABYLON.Matrix.IdentityToRef(tmat2);
  69573. tmat2.m[12] = x;
  69574. tmat2.m[13] = y;
  69575. tmat2.m[14] = z;
  69576. tmat2.multiplyToRef(tmat, tmat);
  69577. }
  69578. if (parentBone) {
  69579. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69580. }
  69581. tmat.multiplyToRef(meshMat, tmat);
  69582. position.x = tmat.m[12];
  69583. position.y = tmat.m[13];
  69584. position.z = tmat.m[14];
  69585. };
  69586. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69587. var len = bones.length;
  69588. var meshPos = this.mesh.position;
  69589. for (var i = 0; i < len; i++) {
  69590. var bone = bones[i];
  69591. var points = this._debugLines[i];
  69592. if (!points) {
  69593. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69594. this._debugLines[i] = points;
  69595. }
  69596. this._getBonePosition(points[0], bone, meshMat);
  69597. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69598. points[0].subtractInPlace(meshPos);
  69599. points[1].subtractInPlace(meshPos);
  69600. }
  69601. };
  69602. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69603. var len = bones.length;
  69604. var boneNum = 0;
  69605. var meshPos = this.mesh.position;
  69606. for (var i = len - 1; i >= 0; i--) {
  69607. var childBone = bones[i];
  69608. var parentBone = childBone.getParent();
  69609. if (!parentBone) {
  69610. continue;
  69611. }
  69612. var points = this._debugLines[boneNum];
  69613. if (!points) {
  69614. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69615. this._debugLines[boneNum] = points;
  69616. }
  69617. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69618. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69619. points[0].subtractInPlace(meshPos);
  69620. points[1].subtractInPlace(meshPos);
  69621. boneNum++;
  69622. }
  69623. };
  69624. SkeletonViewer.prototype.update = function () {
  69625. if (this.autoUpdateBonesMatrices) {
  69626. this.skeleton.computeAbsoluteTransforms();
  69627. }
  69628. if (this.skeleton.bones[0].length === undefined) {
  69629. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69630. }
  69631. else {
  69632. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69633. }
  69634. if (!this._debugMesh) {
  69635. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69636. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69637. }
  69638. else {
  69639. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69640. }
  69641. this._debugMesh.position.copyFrom(this.mesh.position);
  69642. this._debugMesh.color = this.color;
  69643. };
  69644. SkeletonViewer.prototype.dispose = function () {
  69645. if (this._debugMesh) {
  69646. this.isEnabled = false;
  69647. this._debugMesh.dispose();
  69648. this._debugMesh = null;
  69649. }
  69650. };
  69651. return SkeletonViewer;
  69652. }());
  69653. Debug.SkeletonViewer = SkeletonViewer;
  69654. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69655. })(BABYLON || (BABYLON = {}));
  69656. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69657. var BABYLON;
  69658. (function (BABYLON) {
  69659. var Debug;
  69660. (function (Debug) {
  69661. var AxesViewer = /** @class */ (function () {
  69662. function AxesViewer(scene, scaleLines) {
  69663. if (scaleLines === void 0) { scaleLines = 1; }
  69664. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69665. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69666. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69667. this.scaleLines = 1;
  69668. this.scaleLines = scaleLines;
  69669. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69670. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69671. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69672. this._xmesh.renderingGroupId = 2;
  69673. this._ymesh.renderingGroupId = 2;
  69674. this._zmesh.renderingGroupId = 2;
  69675. this._xmesh.material.checkReadyOnlyOnce = true;
  69676. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69677. this._ymesh.material.checkReadyOnlyOnce = true;
  69678. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69679. this._zmesh.material.checkReadyOnlyOnce = true;
  69680. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69681. this.scene = scene;
  69682. }
  69683. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69684. var scaleLines = this.scaleLines;
  69685. if (this._xmesh) {
  69686. this._xmesh.position.copyFrom(position);
  69687. }
  69688. if (this._ymesh) {
  69689. this._ymesh.position.copyFrom(position);
  69690. }
  69691. if (this._zmesh) {
  69692. this._zmesh.position.copyFrom(position);
  69693. }
  69694. var point2 = this._xline[1];
  69695. point2.x = xaxis.x * scaleLines;
  69696. point2.y = xaxis.y * scaleLines;
  69697. point2.z = xaxis.z * scaleLines;
  69698. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69699. point2 = this._yline[1];
  69700. point2.x = yaxis.x * scaleLines;
  69701. point2.y = yaxis.y * scaleLines;
  69702. point2.z = yaxis.z * scaleLines;
  69703. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69704. point2 = this._zline[1];
  69705. point2.x = zaxis.x * scaleLines;
  69706. point2.y = zaxis.y * scaleLines;
  69707. point2.z = zaxis.z * scaleLines;
  69708. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69709. };
  69710. AxesViewer.prototype.dispose = function () {
  69711. if (this._xmesh) {
  69712. this._xmesh.dispose();
  69713. }
  69714. if (this._ymesh) {
  69715. this._ymesh.dispose();
  69716. }
  69717. if (this._zmesh) {
  69718. this._zmesh.dispose();
  69719. }
  69720. this._xmesh = null;
  69721. this._ymesh = null;
  69722. this._zmesh = null;
  69723. this.scene = null;
  69724. };
  69725. return AxesViewer;
  69726. }());
  69727. Debug.AxesViewer = AxesViewer;
  69728. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69729. })(BABYLON || (BABYLON = {}));
  69730. //# sourceMappingURL=babylon.axesViewer.js.map
  69731. var BABYLON;
  69732. (function (BABYLON) {
  69733. var Debug;
  69734. (function (Debug) {
  69735. var BoneAxesViewer = /** @class */ (function (_super) {
  69736. __extends(BoneAxesViewer, _super);
  69737. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  69738. if (scaleLines === void 0) { scaleLines = 1; }
  69739. var _this = _super.call(this, scene, scaleLines) || this;
  69740. _this.pos = BABYLON.Vector3.Zero();
  69741. _this.xaxis = BABYLON.Vector3.Zero();
  69742. _this.yaxis = BABYLON.Vector3.Zero();
  69743. _this.zaxis = BABYLON.Vector3.Zero();
  69744. _this.mesh = mesh;
  69745. _this.bone = bone;
  69746. return _this;
  69747. }
  69748. BoneAxesViewer.prototype.update = function () {
  69749. if (!this.mesh || !this.bone) {
  69750. return;
  69751. }
  69752. var bone = this.bone;
  69753. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  69754. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  69755. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  69756. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  69757. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  69758. };
  69759. BoneAxesViewer.prototype.dispose = function () {
  69760. if (this.mesh) {
  69761. this.mesh = null;
  69762. this.bone = null;
  69763. _super.prototype.dispose.call(this);
  69764. }
  69765. };
  69766. return BoneAxesViewer;
  69767. }(Debug.AxesViewer));
  69768. Debug.BoneAxesViewer = BoneAxesViewer;
  69769. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69770. })(BABYLON || (BABYLON = {}));
  69771. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  69772. var BABYLON;
  69773. (function (BABYLON) {
  69774. var RayHelper = /** @class */ (function () {
  69775. function RayHelper(ray) {
  69776. this.ray = ray;
  69777. }
  69778. RayHelper.CreateAndShow = function (ray, scene, color) {
  69779. var helper = new RayHelper(ray);
  69780. helper.show(scene, color);
  69781. return helper;
  69782. };
  69783. RayHelper.prototype.show = function (scene, color) {
  69784. if (!this._renderFunction && this.ray) {
  69785. var ray = this.ray;
  69786. this._renderFunction = this._render.bind(this);
  69787. this._scene = scene;
  69788. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  69789. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  69790. if (this._renderFunction) {
  69791. this._scene.registerBeforeRender(this._renderFunction);
  69792. }
  69793. }
  69794. if (color && this._renderLine) {
  69795. this._renderLine.color.copyFrom(color);
  69796. }
  69797. };
  69798. RayHelper.prototype.hide = function () {
  69799. if (this._renderFunction && this._scene) {
  69800. this._scene.unregisterBeforeRender(this._renderFunction);
  69801. this._scene = null;
  69802. this._renderFunction = null;
  69803. if (this._renderLine) {
  69804. this._renderLine.dispose();
  69805. this._renderLine = null;
  69806. }
  69807. this._renderPoints = [];
  69808. }
  69809. };
  69810. RayHelper.prototype._render = function () {
  69811. var ray = this.ray;
  69812. if (!ray) {
  69813. return;
  69814. }
  69815. var point = this._renderPoints[1];
  69816. var len = Math.min(ray.length, 1000000);
  69817. point.copyFrom(ray.direction);
  69818. point.scaleInPlace(len);
  69819. point.addInPlace(ray.origin);
  69820. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  69821. };
  69822. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  69823. this._attachedToMesh = mesh;
  69824. var ray = this.ray;
  69825. if (!ray) {
  69826. return;
  69827. }
  69828. if (!ray.direction) {
  69829. ray.direction = BABYLON.Vector3.Zero();
  69830. }
  69831. if (!ray.origin) {
  69832. ray.origin = BABYLON.Vector3.Zero();
  69833. }
  69834. if (length) {
  69835. ray.length = length;
  69836. }
  69837. if (!meshSpaceOrigin) {
  69838. meshSpaceOrigin = BABYLON.Vector3.Zero();
  69839. }
  69840. if (!meshSpaceDirection) {
  69841. // -1 so that this will work with Mesh.lookAt
  69842. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  69843. }
  69844. if (!this._meshSpaceDirection) {
  69845. this._meshSpaceDirection = meshSpaceDirection.clone();
  69846. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  69847. }
  69848. else {
  69849. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  69850. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  69851. }
  69852. if (!this._updateToMeshFunction) {
  69853. this._updateToMeshFunction = this._updateToMesh.bind(this);
  69854. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  69855. }
  69856. this._updateToMesh();
  69857. };
  69858. RayHelper.prototype.detachFromMesh = function () {
  69859. if (this._attachedToMesh) {
  69860. if (this._updateToMeshFunction) {
  69861. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  69862. }
  69863. this._attachedToMesh = null;
  69864. this._updateToMeshFunction = null;
  69865. }
  69866. };
  69867. RayHelper.prototype._updateToMesh = function () {
  69868. var ray = this.ray;
  69869. if (!this._attachedToMesh || !ray) {
  69870. return;
  69871. }
  69872. if (this._attachedToMesh._isDisposed) {
  69873. this.detachFromMesh();
  69874. return;
  69875. }
  69876. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  69877. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  69878. };
  69879. RayHelper.prototype.dispose = function () {
  69880. this.hide();
  69881. this.detachFromMesh();
  69882. this.ray = null;
  69883. };
  69884. return RayHelper;
  69885. }());
  69886. BABYLON.RayHelper = RayHelper;
  69887. })(BABYLON || (BABYLON = {}));
  69888. //# sourceMappingURL=babylon.rayHelper.js.map
  69889. var BABYLON;
  69890. (function (BABYLON) {
  69891. // load the inspector using require, if not present in the global namespace.
  69892. var DebugLayer = /** @class */ (function () {
  69893. function DebugLayer(scene) {
  69894. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69895. this._scene = scene;
  69896. // load inspector using require, if it doesn't exist on the global namespace.
  69897. }
  69898. /** Creates the inspector window. */
  69899. DebugLayer.prototype._createInspector = function (config) {
  69900. if (config === void 0) { config = {}; }
  69901. var popup = config.popup || false;
  69902. var initialTab = config.initialTab || 0;
  69903. var parentElement = config.parentElement || null;
  69904. if (!this._inspector) {
  69905. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69906. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69907. } // else nothing to do,; instance is already existing
  69908. };
  69909. DebugLayer.prototype.isVisible = function () {
  69910. if (!this._inspector) {
  69911. return false;
  69912. }
  69913. return true;
  69914. };
  69915. DebugLayer.prototype.hide = function () {
  69916. if (this._inspector) {
  69917. try {
  69918. this._inspector.dispose();
  69919. }
  69920. catch (e) {
  69921. // If the inspector has been removed directly from the inspector tool
  69922. }
  69923. this._inspector = null;
  69924. }
  69925. };
  69926. DebugLayer.prototype.show = function (config) {
  69927. if (config === void 0) { config = {}; }
  69928. if (typeof this.BJSINSPECTOR == 'undefined') {
  69929. // Load inspector and add it to the DOM
  69930. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69931. }
  69932. else {
  69933. // Otherwise creates the inspector
  69934. this._createInspector(config);
  69935. }
  69936. };
  69937. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69938. return DebugLayer;
  69939. }());
  69940. BABYLON.DebugLayer = DebugLayer;
  69941. })(BABYLON || (BABYLON = {}));
  69942. //# sourceMappingURL=babylon.debugLayer.js.map
  69943. var BABYLON;
  69944. (function (BABYLON) {
  69945. var Debug;
  69946. (function (Debug) {
  69947. var PhysicsViewer = /** @class */ (function () {
  69948. function PhysicsViewer(scene) {
  69949. this._impostors = [];
  69950. this._meshes = [];
  69951. this._numMeshes = 0;
  69952. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69953. var physicEngine = this._scene.getPhysicsEngine();
  69954. if (physicEngine) {
  69955. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69956. }
  69957. }
  69958. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69959. var plugin = this._physicsEnginePlugin;
  69960. for (var i = 0; i < this._numMeshes; i++) {
  69961. var impostor = this._impostors[i];
  69962. if (!impostor) {
  69963. continue;
  69964. }
  69965. if (impostor.isDisposed) {
  69966. this.hideImpostor(this._impostors[i--]);
  69967. }
  69968. else {
  69969. var mesh = this._meshes[i];
  69970. if (mesh && plugin) {
  69971. plugin.syncMeshWithImpostor(mesh, impostor);
  69972. }
  69973. }
  69974. }
  69975. };
  69976. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69977. if (!this._scene) {
  69978. return;
  69979. }
  69980. for (var i = 0; i < this._numMeshes; i++) {
  69981. if (this._impostors[i] == impostor) {
  69982. return;
  69983. }
  69984. }
  69985. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69986. if (debugMesh) {
  69987. this._impostors[this._numMeshes] = impostor;
  69988. this._meshes[this._numMeshes] = debugMesh;
  69989. if (this._numMeshes === 0) {
  69990. this._renderFunction = this._updateDebugMeshes.bind(this);
  69991. this._scene.registerBeforeRender(this._renderFunction);
  69992. }
  69993. this._numMeshes++;
  69994. }
  69995. };
  69996. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69997. if (!impostor || !this._scene) {
  69998. return;
  69999. }
  70000. var removed = false;
  70001. for (var i = 0; i < this._numMeshes; i++) {
  70002. if (this._impostors[i] == impostor) {
  70003. var mesh = this._meshes[i];
  70004. if (!mesh) {
  70005. continue;
  70006. }
  70007. this._scene.removeMesh(mesh);
  70008. mesh.dispose();
  70009. this._numMeshes--;
  70010. if (this._numMeshes > 0) {
  70011. this._meshes[i] = this._meshes[this._numMeshes];
  70012. this._impostors[i] = this._impostors[this._numMeshes];
  70013. this._meshes[this._numMeshes] = null;
  70014. this._impostors[this._numMeshes] = null;
  70015. }
  70016. else {
  70017. this._meshes[0] = null;
  70018. this._impostors[0] = null;
  70019. }
  70020. removed = true;
  70021. break;
  70022. }
  70023. }
  70024. if (removed && this._numMeshes === 0) {
  70025. this._scene.unregisterBeforeRender(this._renderFunction);
  70026. }
  70027. };
  70028. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  70029. if (!this._debugMaterial) {
  70030. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  70031. this._debugMaterial.wireframe = true;
  70032. }
  70033. return this._debugMaterial;
  70034. };
  70035. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  70036. if (!this._debugBoxMesh) {
  70037. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  70038. this._debugBoxMesh.renderingGroupId = 1;
  70039. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70040. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  70041. scene.removeMesh(this._debugBoxMesh);
  70042. }
  70043. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  70044. };
  70045. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  70046. if (!this._debugSphereMesh) {
  70047. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  70048. this._debugSphereMesh.renderingGroupId = 1;
  70049. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70050. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  70051. scene.removeMesh(this._debugSphereMesh);
  70052. }
  70053. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  70054. };
  70055. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  70056. var mesh = null;
  70057. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  70058. mesh = this._getDebugBoxMesh(scene);
  70059. impostor.getBoxSizeToRef(mesh.scaling);
  70060. }
  70061. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  70062. mesh = this._getDebugSphereMesh(scene);
  70063. var radius = impostor.getRadius();
  70064. mesh.scaling.x = radius * 2;
  70065. mesh.scaling.y = radius * 2;
  70066. mesh.scaling.z = radius * 2;
  70067. }
  70068. return mesh;
  70069. };
  70070. PhysicsViewer.prototype.dispose = function () {
  70071. for (var i = 0; i < this._numMeshes; i++) {
  70072. this.hideImpostor(this._impostors[i]);
  70073. }
  70074. if (this._debugBoxMesh) {
  70075. this._debugBoxMesh.dispose();
  70076. }
  70077. if (this._debugSphereMesh) {
  70078. this._debugSphereMesh.dispose();
  70079. }
  70080. if (this._debugMaterial) {
  70081. this._debugMaterial.dispose();
  70082. }
  70083. this._impostors.length = 0;
  70084. this._scene = null;
  70085. this._physicsEnginePlugin = null;
  70086. };
  70087. return PhysicsViewer;
  70088. }());
  70089. Debug.PhysicsViewer = PhysicsViewer;
  70090. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70091. })(BABYLON || (BABYLON = {}));
  70092. //# sourceMappingURL=babylon.physicsViewer.js.map
  70093. var BABYLON;
  70094. (function (BABYLON) {
  70095. var BoundingBoxRenderer = /** @class */ (function () {
  70096. function BoundingBoxRenderer(scene) {
  70097. this.frontColor = new BABYLON.Color3(1, 1, 1);
  70098. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  70099. this.showBackLines = true;
  70100. this.renderList = new BABYLON.SmartArray(32);
  70101. this._vertexBuffers = {};
  70102. this._scene = scene;
  70103. }
  70104. BoundingBoxRenderer.prototype._prepareRessources = function () {
  70105. if (this._colorShader) {
  70106. return;
  70107. }
  70108. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  70109. attributes: [BABYLON.VertexBuffer.PositionKind],
  70110. uniforms: ["world", "viewProjection", "color"]
  70111. });
  70112. var engine = this._scene.getEngine();
  70113. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  70114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  70115. this._createIndexBuffer();
  70116. };
  70117. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  70118. var engine = this._scene.getEngine();
  70119. 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]);
  70120. };
  70121. BoundingBoxRenderer.prototype._rebuild = function () {
  70122. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70123. if (vb) {
  70124. vb._rebuild();
  70125. }
  70126. this._createIndexBuffer();
  70127. };
  70128. BoundingBoxRenderer.prototype.reset = function () {
  70129. this.renderList.reset();
  70130. };
  70131. BoundingBoxRenderer.prototype.render = function () {
  70132. if (this.renderList.length === 0) {
  70133. return;
  70134. }
  70135. this._prepareRessources();
  70136. if (!this._colorShader.isReady()) {
  70137. return;
  70138. }
  70139. var engine = this._scene.getEngine();
  70140. engine.setDepthWrite(false);
  70141. this._colorShader._preBind();
  70142. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  70143. var boundingBox = this.renderList.data[boundingBoxIndex];
  70144. var min = boundingBox.minimum;
  70145. var max = boundingBox.maximum;
  70146. var diff = max.subtract(min);
  70147. var median = min.add(diff.scale(0.5));
  70148. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70149. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70150. .multiply(boundingBox.getWorldMatrix());
  70151. // VBOs
  70152. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70153. if (this.showBackLines) {
  70154. // Back
  70155. engine.setDepthFunctionToGreaterOrEqual();
  70156. this._scene.resetCachedMaterial();
  70157. this._colorShader.setColor4("color", this.backColor.toColor4());
  70158. this._colorShader.bind(worldMatrix);
  70159. // Draw order
  70160. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70161. }
  70162. // Front
  70163. engine.setDepthFunctionToLess();
  70164. this._scene.resetCachedMaterial();
  70165. this._colorShader.setColor4("color", this.frontColor.toColor4());
  70166. this._colorShader.bind(worldMatrix);
  70167. // Draw order
  70168. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70169. }
  70170. this._colorShader.unbind();
  70171. engine.setDepthFunctionToLessOrEqual();
  70172. engine.setDepthWrite(true);
  70173. };
  70174. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  70175. this._prepareRessources();
  70176. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  70177. return;
  70178. }
  70179. var engine = this._scene.getEngine();
  70180. engine.setDepthWrite(false);
  70181. engine.setColorWrite(false);
  70182. this._colorShader._preBind();
  70183. var boundingBox = mesh._boundingInfo.boundingBox;
  70184. var min = boundingBox.minimum;
  70185. var max = boundingBox.maximum;
  70186. var diff = max.subtract(min);
  70187. var median = min.add(diff.scale(0.5));
  70188. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70189. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70190. .multiply(boundingBox.getWorldMatrix());
  70191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70192. engine.setDepthFunctionToLess();
  70193. this._scene.resetCachedMaterial();
  70194. this._colorShader.bind(worldMatrix);
  70195. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70196. this._colorShader.unbind();
  70197. engine.setDepthFunctionToLessOrEqual();
  70198. engine.setDepthWrite(true);
  70199. engine.setColorWrite(true);
  70200. };
  70201. BoundingBoxRenderer.prototype.dispose = function () {
  70202. if (!this._colorShader) {
  70203. return;
  70204. }
  70205. this.renderList.dispose();
  70206. this._colorShader.dispose();
  70207. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70208. if (buffer) {
  70209. buffer.dispose();
  70210. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70211. }
  70212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70213. };
  70214. return BoundingBoxRenderer;
  70215. }());
  70216. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  70217. })(BABYLON || (BABYLON = {}));
  70218. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  70219. var BABYLON;
  70220. (function (BABYLON) {
  70221. var MorphTarget = /** @class */ (function () {
  70222. function MorphTarget(name, influence) {
  70223. if (influence === void 0) { influence = 0; }
  70224. this.name = name;
  70225. this.animations = new Array();
  70226. this._positions = null;
  70227. this._normals = null;
  70228. this._tangents = null;
  70229. this.onInfluenceChanged = new BABYLON.Observable();
  70230. this.influence = influence;
  70231. }
  70232. Object.defineProperty(MorphTarget.prototype, "influence", {
  70233. get: function () {
  70234. return this._influence;
  70235. },
  70236. set: function (influence) {
  70237. if (this._influence === influence) {
  70238. return;
  70239. }
  70240. var previous = this._influence;
  70241. this._influence = influence;
  70242. if (this.onInfluenceChanged.hasObservers) {
  70243. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  70244. }
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  70250. get: function () {
  70251. return !!this._positions;
  70252. },
  70253. enumerable: true,
  70254. configurable: true
  70255. });
  70256. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  70257. get: function () {
  70258. return !!this._normals;
  70259. },
  70260. enumerable: true,
  70261. configurable: true
  70262. });
  70263. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  70264. get: function () {
  70265. return !!this._tangents;
  70266. },
  70267. enumerable: true,
  70268. configurable: true
  70269. });
  70270. MorphTarget.prototype.setPositions = function (data) {
  70271. this._positions = data;
  70272. };
  70273. MorphTarget.prototype.getPositions = function () {
  70274. return this._positions;
  70275. };
  70276. MorphTarget.prototype.setNormals = function (data) {
  70277. this._normals = data;
  70278. };
  70279. MorphTarget.prototype.getNormals = function () {
  70280. return this._normals;
  70281. };
  70282. MorphTarget.prototype.setTangents = function (data) {
  70283. this._tangents = data;
  70284. };
  70285. MorphTarget.prototype.getTangents = function () {
  70286. return this._tangents;
  70287. };
  70288. /**
  70289. * Serializes the current target into a Serialization object.
  70290. * Returns the serialized object.
  70291. */
  70292. MorphTarget.prototype.serialize = function () {
  70293. var serializationObject = {};
  70294. serializationObject.name = this.name;
  70295. serializationObject.influence = this.influence;
  70296. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  70297. if (this.hasNormals) {
  70298. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  70299. }
  70300. if (this.hasTangents) {
  70301. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  70302. }
  70303. // Animations
  70304. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  70305. return serializationObject;
  70306. };
  70307. // Statics
  70308. MorphTarget.Parse = function (serializationObject) {
  70309. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  70310. result.setPositions(serializationObject.positions);
  70311. if (serializationObject.normals) {
  70312. result.setNormals(serializationObject.normals);
  70313. }
  70314. if (serializationObject.tangents) {
  70315. result.setTangents(serializationObject.tangents);
  70316. }
  70317. // Animations
  70318. if (serializationObject.animations) {
  70319. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  70320. var parsedAnimation = serializationObject.animations[animationIndex];
  70321. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70322. }
  70323. }
  70324. return result;
  70325. };
  70326. MorphTarget.FromMesh = function (mesh, name, influence) {
  70327. if (!name) {
  70328. name = mesh.name;
  70329. }
  70330. var result = new MorphTarget(name, influence);
  70331. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  70332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70333. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  70334. }
  70335. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  70336. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  70337. }
  70338. return result;
  70339. };
  70340. return MorphTarget;
  70341. }());
  70342. BABYLON.MorphTarget = MorphTarget;
  70343. })(BABYLON || (BABYLON = {}));
  70344. //# sourceMappingURL=babylon.morphTarget.js.map
  70345. var BABYLON;
  70346. (function (BABYLON) {
  70347. var MorphTargetManager = /** @class */ (function () {
  70348. function MorphTargetManager(scene) {
  70349. if (scene === void 0) { scene = null; }
  70350. this._targets = new Array();
  70351. this._targetObservable = new Array();
  70352. this._activeTargets = new BABYLON.SmartArray(16);
  70353. this._supportsNormals = false;
  70354. this._supportsTangents = false;
  70355. this._vertexCount = 0;
  70356. this._uniqueId = 0;
  70357. this._tempInfluences = new Array();
  70358. if (!scene) {
  70359. scene = BABYLON.Engine.LastCreatedScene;
  70360. }
  70361. this._scene = scene;
  70362. if (this._scene) {
  70363. this._scene.morphTargetManagers.push(this);
  70364. this._uniqueId = this._scene.getUniqueId();
  70365. }
  70366. }
  70367. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  70368. get: function () {
  70369. return this._uniqueId;
  70370. },
  70371. enumerable: true,
  70372. configurable: true
  70373. });
  70374. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  70375. get: function () {
  70376. return this._vertexCount;
  70377. },
  70378. enumerable: true,
  70379. configurable: true
  70380. });
  70381. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  70382. get: function () {
  70383. return this._supportsNormals;
  70384. },
  70385. enumerable: true,
  70386. configurable: true
  70387. });
  70388. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  70389. get: function () {
  70390. return this._supportsTangents;
  70391. },
  70392. enumerable: true,
  70393. configurable: true
  70394. });
  70395. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  70396. get: function () {
  70397. return this._targets.length;
  70398. },
  70399. enumerable: true,
  70400. configurable: true
  70401. });
  70402. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  70403. get: function () {
  70404. return this._activeTargets.length;
  70405. },
  70406. enumerable: true,
  70407. configurable: true
  70408. });
  70409. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  70410. get: function () {
  70411. return this._influences;
  70412. },
  70413. enumerable: true,
  70414. configurable: true
  70415. });
  70416. MorphTargetManager.prototype.getActiveTarget = function (index) {
  70417. return this._activeTargets.data[index];
  70418. };
  70419. MorphTargetManager.prototype.getTarget = function (index) {
  70420. return this._targets[index];
  70421. };
  70422. MorphTargetManager.prototype.addTarget = function (target) {
  70423. var _this = this;
  70424. this._targets.push(target);
  70425. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  70426. _this._syncActiveTargets(needUpdate);
  70427. }));
  70428. this._syncActiveTargets(true);
  70429. };
  70430. MorphTargetManager.prototype.removeTarget = function (target) {
  70431. var index = this._targets.indexOf(target);
  70432. if (index >= 0) {
  70433. this._targets.splice(index, 1);
  70434. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  70435. this._syncActiveTargets(true);
  70436. }
  70437. };
  70438. /**
  70439. * Serializes the current manager into a Serialization object.
  70440. * Returns the serialized object.
  70441. */
  70442. MorphTargetManager.prototype.serialize = function () {
  70443. var serializationObject = {};
  70444. serializationObject.id = this.uniqueId;
  70445. serializationObject.targets = [];
  70446. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70447. var target = _a[_i];
  70448. serializationObject.targets.push(target.serialize());
  70449. }
  70450. return serializationObject;
  70451. };
  70452. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  70453. var influenceCount = 0;
  70454. this._activeTargets.reset();
  70455. this._supportsNormals = true;
  70456. this._supportsTangents = true;
  70457. this._vertexCount = 0;
  70458. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70459. var target = _a[_i];
  70460. if (target.influence > 0) {
  70461. this._activeTargets.push(target);
  70462. this._tempInfluences[influenceCount++] = target.influence;
  70463. this._supportsNormals = this._supportsNormals && target.hasNormals;
  70464. this._supportsTangents = this._supportsTangents && target.hasTangents;
  70465. var positions = target.getPositions();
  70466. if (!positions) {
  70467. BABYLON.Tools.Error("Invalid target. Target must positions.");
  70468. return;
  70469. }
  70470. var vertexCount = positions.length / 3;
  70471. if (this._vertexCount === 0) {
  70472. this._vertexCount = vertexCount;
  70473. }
  70474. else if (this._vertexCount !== vertexCount) {
  70475. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  70476. return;
  70477. }
  70478. }
  70479. }
  70480. if (!this._influences || this._influences.length !== influenceCount) {
  70481. this._influences = new Float32Array(influenceCount);
  70482. }
  70483. for (var index = 0; index < influenceCount; index++) {
  70484. this._influences[index] = this._tempInfluences[index];
  70485. }
  70486. if (needUpdate && this._scene) {
  70487. // Flag meshes as dirty to resync with the active targets
  70488. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  70489. var mesh = _c[_b];
  70490. if (mesh.morphTargetManager === this) {
  70491. mesh._syncGeometryWithMorphTargetManager();
  70492. }
  70493. }
  70494. }
  70495. };
  70496. // Statics
  70497. MorphTargetManager.Parse = function (serializationObject, scene) {
  70498. var result = new MorphTargetManager(scene);
  70499. result._uniqueId = serializationObject.id;
  70500. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  70501. var targetData = _a[_i];
  70502. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  70503. }
  70504. return result;
  70505. };
  70506. return MorphTargetManager;
  70507. }());
  70508. BABYLON.MorphTargetManager = MorphTargetManager;
  70509. })(BABYLON || (BABYLON = {}));
  70510. //# sourceMappingURL=babylon.morphTargetManager.js.map
  70511. var BABYLON;
  70512. (function (BABYLON) {
  70513. var Octree = /** @class */ (function () {
  70514. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  70515. if (maxDepth === void 0) { maxDepth = 2; }
  70516. this.maxDepth = maxDepth;
  70517. this.dynamicContent = new Array();
  70518. this._maxBlockCapacity = maxBlockCapacity || 64;
  70519. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70520. this._creationFunc = creationFunc;
  70521. }
  70522. // Methods
  70523. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70524. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70525. };
  70526. Octree.prototype.addMesh = function (entry) {
  70527. for (var index = 0; index < this.blocks.length; index++) {
  70528. var block = this.blocks[index];
  70529. block.addEntry(entry);
  70530. }
  70531. };
  70532. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70533. this._selectionContent.reset();
  70534. for (var index = 0; index < this.blocks.length; index++) {
  70535. var block = this.blocks[index];
  70536. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70537. }
  70538. if (allowDuplicate) {
  70539. this._selectionContent.concat(this.dynamicContent);
  70540. }
  70541. else {
  70542. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70543. }
  70544. return this._selectionContent;
  70545. };
  70546. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70547. this._selectionContent.reset();
  70548. for (var index = 0; index < this.blocks.length; index++) {
  70549. var block = this.blocks[index];
  70550. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70551. }
  70552. if (allowDuplicate) {
  70553. this._selectionContent.concat(this.dynamicContent);
  70554. }
  70555. else {
  70556. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70557. }
  70558. return this._selectionContent;
  70559. };
  70560. Octree.prototype.intersectsRay = function (ray) {
  70561. this._selectionContent.reset();
  70562. for (var index = 0; index < this.blocks.length; index++) {
  70563. var block = this.blocks[index];
  70564. block.intersectsRay(ray, this._selectionContent);
  70565. }
  70566. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70567. return this._selectionContent;
  70568. };
  70569. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70570. target.blocks = new Array();
  70571. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70572. // Segmenting space
  70573. for (var x = 0; x < 2; x++) {
  70574. for (var y = 0; y < 2; y++) {
  70575. for (var z = 0; z < 2; z++) {
  70576. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70577. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70578. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70579. block.addEntries(entries);
  70580. target.blocks.push(block);
  70581. }
  70582. }
  70583. }
  70584. };
  70585. Octree.CreationFuncForMeshes = function (entry, block) {
  70586. var boundingInfo = entry.getBoundingInfo();
  70587. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70588. block.entries.push(entry);
  70589. }
  70590. };
  70591. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70592. var boundingInfo = entry.getBoundingInfo();
  70593. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70594. block.entries.push(entry);
  70595. }
  70596. };
  70597. return Octree;
  70598. }());
  70599. BABYLON.Octree = Octree;
  70600. })(BABYLON || (BABYLON = {}));
  70601. //# sourceMappingURL=babylon.octree.js.map
  70602. var BABYLON;
  70603. (function (BABYLON) {
  70604. var OctreeBlock = /** @class */ (function () {
  70605. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70606. this.entries = new Array();
  70607. this._boundingVectors = new Array();
  70608. this._capacity = capacity;
  70609. this._depth = depth;
  70610. this._maxDepth = maxDepth;
  70611. this._creationFunc = creationFunc;
  70612. this._minPoint = minPoint;
  70613. this._maxPoint = maxPoint;
  70614. this._boundingVectors.push(minPoint.clone());
  70615. this._boundingVectors.push(maxPoint.clone());
  70616. this._boundingVectors.push(minPoint.clone());
  70617. this._boundingVectors[2].x = maxPoint.x;
  70618. this._boundingVectors.push(minPoint.clone());
  70619. this._boundingVectors[3].y = maxPoint.y;
  70620. this._boundingVectors.push(minPoint.clone());
  70621. this._boundingVectors[4].z = maxPoint.z;
  70622. this._boundingVectors.push(maxPoint.clone());
  70623. this._boundingVectors[5].z = minPoint.z;
  70624. this._boundingVectors.push(maxPoint.clone());
  70625. this._boundingVectors[6].x = minPoint.x;
  70626. this._boundingVectors.push(maxPoint.clone());
  70627. this._boundingVectors[7].y = minPoint.y;
  70628. }
  70629. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70630. // Property
  70631. get: function () {
  70632. return this._capacity;
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70638. get: function () {
  70639. return this._minPoint;
  70640. },
  70641. enumerable: true,
  70642. configurable: true
  70643. });
  70644. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70645. get: function () {
  70646. return this._maxPoint;
  70647. },
  70648. enumerable: true,
  70649. configurable: true
  70650. });
  70651. // Methods
  70652. OctreeBlock.prototype.addEntry = function (entry) {
  70653. if (this.blocks) {
  70654. for (var index = 0; index < this.blocks.length; index++) {
  70655. var block = this.blocks[index];
  70656. block.addEntry(entry);
  70657. }
  70658. return;
  70659. }
  70660. this._creationFunc(entry, this);
  70661. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70662. this.createInnerBlocks();
  70663. }
  70664. };
  70665. OctreeBlock.prototype.addEntries = function (entries) {
  70666. for (var index = 0; index < entries.length; index++) {
  70667. var mesh = entries[index];
  70668. this.addEntry(mesh);
  70669. }
  70670. };
  70671. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70672. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70673. if (this.blocks) {
  70674. for (var index = 0; index < this.blocks.length; index++) {
  70675. var block = this.blocks[index];
  70676. block.select(frustumPlanes, selection, allowDuplicate);
  70677. }
  70678. return;
  70679. }
  70680. if (allowDuplicate) {
  70681. selection.concat(this.entries);
  70682. }
  70683. else {
  70684. selection.concatWithNoDuplicate(this.entries);
  70685. }
  70686. }
  70687. };
  70688. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70689. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70690. if (this.blocks) {
  70691. for (var index = 0; index < this.blocks.length; index++) {
  70692. var block = this.blocks[index];
  70693. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70694. }
  70695. return;
  70696. }
  70697. if (allowDuplicate) {
  70698. selection.concat(this.entries);
  70699. }
  70700. else {
  70701. selection.concatWithNoDuplicate(this.entries);
  70702. }
  70703. }
  70704. };
  70705. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70706. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70707. if (this.blocks) {
  70708. for (var index = 0; index < this.blocks.length; index++) {
  70709. var block = this.blocks[index];
  70710. block.intersectsRay(ray, selection);
  70711. }
  70712. return;
  70713. }
  70714. selection.concatWithNoDuplicate(this.entries);
  70715. }
  70716. };
  70717. OctreeBlock.prototype.createInnerBlocks = function () {
  70718. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  70719. };
  70720. return OctreeBlock;
  70721. }());
  70722. BABYLON.OctreeBlock = OctreeBlock;
  70723. })(BABYLON || (BABYLON = {}));
  70724. //# sourceMappingURL=babylon.octreeBlock.js.map
  70725. var BABYLON;
  70726. (function (BABYLON) {
  70727. var SIMDVector3 = /** @class */ (function () {
  70728. function SIMDVector3() {
  70729. }
  70730. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  70731. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  70732. };
  70733. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  70734. var m = transformation.m;
  70735. var m0 = SIMD.Float32x4.load(m, 0);
  70736. var m1 = SIMD.Float32x4.load(m, 4);
  70737. var m2 = SIMD.Float32x4.load(m, 8);
  70738. var m3 = SIMD.Float32x4.load(m, 12);
  70739. 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));
  70740. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  70741. result.x = SIMD.Float32x4.extractLane(r, 0);
  70742. result.y = SIMD.Float32x4.extractLane(r, 1);
  70743. result.z = SIMD.Float32x4.extractLane(r, 2);
  70744. };
  70745. return SIMDVector3;
  70746. }());
  70747. var SIMDMatrix = /** @class */ (function () {
  70748. function SIMDMatrix() {
  70749. }
  70750. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  70751. var tm = this.m;
  70752. var om = other.m;
  70753. var m0 = SIMD.Float32x4.load(om, 0);
  70754. var m1 = SIMD.Float32x4.load(om, 4);
  70755. var m2 = SIMD.Float32x4.load(om, 8);
  70756. var m3 = SIMD.Float32x4.load(om, 12);
  70757. for (var i = 0; i < 16; i += 4) {
  70758. 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)))));
  70759. }
  70760. return this;
  70761. };
  70762. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  70763. var src = this.m;
  70764. var dest = other.m;
  70765. // Load the 4 rows
  70766. var src0 = SIMD.Float32x4.load(src, 0);
  70767. var src1 = SIMD.Float32x4.load(src, 4);
  70768. var src2 = SIMD.Float32x4.load(src, 8);
  70769. var src3 = SIMD.Float32x4.load(src, 12);
  70770. // Transpose the source matrix. Sort of. Not a true transpose operation
  70771. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  70772. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  70773. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  70774. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  70775. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  70776. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  70777. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  70778. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  70779. // This is a true transposition, but it will lead to an incorrect result
  70780. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  70781. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  70782. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70783. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70784. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  70785. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  70786. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70787. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70788. // ----
  70789. tmp1 = SIMD.Float32x4.mul(row2, row3);
  70790. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70791. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  70792. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  70793. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70794. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  70795. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  70796. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  70797. // ----
  70798. tmp1 = SIMD.Float32x4.mul(row1, row2);
  70799. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70800. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  70801. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  70802. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70803. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  70804. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  70805. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  70806. // ----
  70807. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  70808. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70809. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  70810. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  70811. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  70812. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70813. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  70814. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  70815. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  70816. // ----
  70817. tmp1 = SIMD.Float32x4.mul(row0, row1);
  70818. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70819. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70820. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  70821. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70822. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70823. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  70824. // ----
  70825. tmp1 = SIMD.Float32x4.mul(row0, row3);
  70826. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70827. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  70828. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  70829. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70830. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  70831. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  70832. // ----
  70833. tmp1 = SIMD.Float32x4.mul(row0, row2);
  70834. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70835. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  70836. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  70837. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70838. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  70839. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  70840. // Compute determinant
  70841. var det = SIMD.Float32x4.mul(row0, minor0);
  70842. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  70843. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  70844. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  70845. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  70846. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  70847. // These shuffles aren't necessary if the faulty transposition is done
  70848. // up at the top of this function.
  70849. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  70850. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  70851. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  70852. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  70853. // Compute final values by multiplying with 1/det
  70854. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  70855. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  70856. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  70857. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  70858. return this;
  70859. };
  70860. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  70861. var out = result.m;
  70862. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  70863. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  70864. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  70865. // cc.kmVec3Subtract(f, pCenter, pEye);
  70866. var f = SIMD.Float32x4.sub(center, eye);
  70867. // cc.kmVec3Normalize(f, f);
  70868. var tmp = SIMD.Float32x4.mul(f, f);
  70869. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70870. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70871. // cc.kmVec3Assign(up, pUp);
  70872. // cc.kmVec3Normalize(up, up);
  70873. tmp = SIMD.Float32x4.mul(up, up);
  70874. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70875. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70876. // cc.kmVec3Cross(s, f, up);
  70877. 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)));
  70878. // cc.kmVec3Normalize(s, s);
  70879. tmp = SIMD.Float32x4.mul(s, s);
  70880. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70881. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70882. // cc.kmVec3Cross(u, s, f);
  70883. 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)));
  70884. // cc.kmVec3Normalize(s, s);
  70885. tmp = SIMD.Float32x4.mul(s, s);
  70886. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70887. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70888. var zero = SIMD.Float32x4.splat(0.0);
  70889. s = SIMD.Float32x4.neg(s);
  70890. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70891. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70892. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70893. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70894. 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);
  70895. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70896. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70897. 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)))));
  70898. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70899. 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)))));
  70900. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70901. 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)))));
  70902. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70903. 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)))));
  70904. };
  70905. return SIMDMatrix;
  70906. }());
  70907. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70908. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70909. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70910. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70911. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70912. var SIMDHelper = /** @class */ (function () {
  70913. function SIMDHelper() {
  70914. }
  70915. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70916. get: function () {
  70917. return SIMDHelper._isEnabled;
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. SIMDHelper.DisableSIMD = function () {
  70923. // Replace functions
  70924. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70925. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70926. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70927. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70929. SIMDHelper._isEnabled = false;
  70930. };
  70931. SIMDHelper.EnableSIMD = function () {
  70932. if (self.SIMD === undefined) {
  70933. return;
  70934. }
  70935. // check if polyfills needed
  70936. if (!self.Math.fround) {
  70937. self.Math.fround = (function (array) { return function (x) {
  70938. return array[0] = x, array[0];
  70939. }; })(new Float32Array(1));
  70940. }
  70941. if (!self.Math.imul) {
  70942. self.Math.imul = function (a, b) {
  70943. var ah = (a >>> 16) & 0xffff;
  70944. var al = a & 0xffff;
  70945. var bh = (b >>> 16) & 0xffff;
  70946. var bl = b & 0xffff;
  70947. // the shift by 0 fixes the sign on the high part
  70948. // the final |0 converts the unsigned value into a signed value
  70949. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70950. };
  70951. }
  70952. // Replace functions
  70953. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70954. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70955. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70956. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70958. SIMDHelper._isEnabled = true;
  70959. };
  70960. SIMDHelper._isEnabled = false;
  70961. return SIMDHelper;
  70962. }());
  70963. BABYLON.SIMDHelper = SIMDHelper;
  70964. })(BABYLON || (BABYLON = {}));
  70965. //# sourceMappingURL=babylon.math.SIMD.js.map
  70966. var BABYLON;
  70967. (function (BABYLON) {
  70968. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70969. __extends(VRDistortionCorrectionPostProcess, _super);
  70970. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70971. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70972. 'LensCenter',
  70973. 'Scale',
  70974. 'ScaleIn',
  70975. 'HmdWarpParam'
  70976. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70977. _this._isRightEye = isRightEye;
  70978. _this._distortionFactors = vrMetrics.distortionK;
  70979. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70980. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70981. _this.adaptScaleToCurrentViewport = true;
  70982. _this.onSizeChangedObservable.add(function () {
  70983. _this.aspectRatio = _this.width * .5 / _this.height;
  70984. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70985. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70986. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70987. });
  70988. _this.onApplyObservable.add(function (effect) {
  70989. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70990. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70991. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70992. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70993. });
  70994. return _this;
  70995. }
  70996. return VRDistortionCorrectionPostProcess;
  70997. }(BABYLON.PostProcess));
  70998. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70999. })(BABYLON || (BABYLON = {}));
  71000. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  71001. var BABYLON;
  71002. (function (BABYLON) {
  71003. var AnaglyphPostProcess = /** @class */ (function (_super) {
  71004. __extends(AnaglyphPostProcess, _super);
  71005. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  71006. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  71007. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71008. _this.onApplyObservable.add(function (effect) {
  71009. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  71010. });
  71011. return _this;
  71012. }
  71013. return AnaglyphPostProcess;
  71014. }(BABYLON.PostProcess));
  71015. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  71016. })(BABYLON || (BABYLON = {}));
  71017. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  71018. var BABYLON;
  71019. (function (BABYLON) {
  71020. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  71021. __extends(StereoscopicInterlacePostProcess, _super);
  71022. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  71023. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  71024. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71025. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71026. _this.onSizeChangedObservable.add(function () {
  71027. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71028. });
  71029. _this.onApplyObservable.add(function (effect) {
  71030. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  71031. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  71032. });
  71033. return _this;
  71034. }
  71035. return StereoscopicInterlacePostProcess;
  71036. }(BABYLON.PostProcess));
  71037. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  71038. })(BABYLON || (BABYLON = {}));
  71039. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  71040. var BABYLON;
  71041. (function (BABYLON) {
  71042. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  71043. function FreeCameraDeviceOrientationInput() {
  71044. var _this = this;
  71045. this._screenOrientationAngle = 0;
  71046. this._screenQuaternion = new BABYLON.Quaternion();
  71047. this._alpha = 0;
  71048. this._beta = 0;
  71049. this._gamma = 0;
  71050. this._orientationChanged = function () {
  71051. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  71052. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  71053. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  71054. };
  71055. this._deviceOrientation = function (evt) {
  71056. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  71057. _this._beta = evt.beta !== null ? evt.beta : 0;
  71058. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  71059. };
  71060. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  71061. this._orientationChanged();
  71062. }
  71063. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  71064. get: function () {
  71065. return this._camera;
  71066. },
  71067. set: function (camera) {
  71068. this._camera = camera;
  71069. if (this._camera != null && !this._camera.rotationQuaternion) {
  71070. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  71071. }
  71072. },
  71073. enumerable: true,
  71074. configurable: true
  71075. });
  71076. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71077. window.addEventListener("orientationchange", this._orientationChanged);
  71078. window.addEventListener("deviceorientation", this._deviceOrientation);
  71079. //In certain cases, the attach control is called AFTER orientation was changed,
  71080. //So this is needed.
  71081. this._orientationChanged();
  71082. };
  71083. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  71084. window.removeEventListener("orientationchange", this._orientationChanged);
  71085. window.removeEventListener("deviceorientation", this._deviceOrientation);
  71086. };
  71087. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  71088. //if no device orientation provided, don't update the rotation.
  71089. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  71090. if (!this._alpha)
  71091. return;
  71092. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  71093. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  71094. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  71095. //Mirror on XY Plane
  71096. this._camera.rotationQuaternion.z *= -1;
  71097. this._camera.rotationQuaternion.w *= -1;
  71098. };
  71099. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  71100. return "FreeCameraDeviceOrientationInput";
  71101. };
  71102. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  71103. return "deviceOrientation";
  71104. };
  71105. return FreeCameraDeviceOrientationInput;
  71106. }());
  71107. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  71108. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  71109. })(BABYLON || (BABYLON = {}));
  71110. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  71111. var BABYLON;
  71112. (function (BABYLON) {
  71113. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  71114. function ArcRotateCameraVRDeviceOrientationInput() {
  71115. this.alphaCorrection = 1;
  71116. this.betaCorrection = 1;
  71117. this.gammaCorrection = 1;
  71118. this._alpha = 0;
  71119. this._gamma = 0;
  71120. this._dirty = false;
  71121. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  71122. }
  71123. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71124. this.camera.attachControl(element, noPreventDefault);
  71125. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  71126. };
  71127. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  71128. if (evt.alpha !== null) {
  71129. this._alpha = +evt.alpha | 0;
  71130. }
  71131. if (evt.gamma !== null) {
  71132. this._gamma = +evt.gamma | 0;
  71133. }
  71134. this._dirty = true;
  71135. };
  71136. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  71137. if (this._dirty) {
  71138. this._dirty = false;
  71139. if (this._gamma < 0) {
  71140. this._gamma = 180 + this._gamma;
  71141. }
  71142. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  71143. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  71144. }
  71145. };
  71146. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  71147. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  71148. };
  71149. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  71150. return "ArcRotateCameraVRDeviceOrientationInput";
  71151. };
  71152. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  71153. return "VRDeviceOrientation";
  71154. };
  71155. return ArcRotateCameraVRDeviceOrientationInput;
  71156. }());
  71157. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  71158. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  71159. })(BABYLON || (BABYLON = {}));
  71160. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  71161. var BABYLON;
  71162. (function (BABYLON) {
  71163. var VRCameraMetrics = /** @class */ (function () {
  71164. function VRCameraMetrics() {
  71165. this.compensateDistortion = true;
  71166. }
  71167. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  71168. get: function () {
  71169. return this.hResolution / (2 * this.vResolution);
  71170. },
  71171. enumerable: true,
  71172. configurable: true
  71173. });
  71174. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  71175. get: function () {
  71176. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  71177. },
  71178. enumerable: true,
  71179. configurable: true
  71180. });
  71181. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  71182. get: function () {
  71183. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71184. var h = (4 * meters) / this.hScreenSize;
  71185. return BABYLON.Matrix.Translation(h, 0, 0);
  71186. },
  71187. enumerable: true,
  71188. configurable: true
  71189. });
  71190. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  71191. get: function () {
  71192. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71193. var h = (4 * meters) / this.hScreenSize;
  71194. return BABYLON.Matrix.Translation(-h, 0, 0);
  71195. },
  71196. enumerable: true,
  71197. configurable: true
  71198. });
  71199. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  71200. get: function () {
  71201. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  71202. },
  71203. enumerable: true,
  71204. configurable: true
  71205. });
  71206. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  71207. get: function () {
  71208. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  71209. },
  71210. enumerable: true,
  71211. configurable: true
  71212. });
  71213. VRCameraMetrics.GetDefault = function () {
  71214. var result = new VRCameraMetrics();
  71215. result.hResolution = 1280;
  71216. result.vResolution = 800;
  71217. result.hScreenSize = 0.149759993;
  71218. result.vScreenSize = 0.0935999975;
  71219. result.vScreenCenter = 0.0467999987;
  71220. result.eyeToScreenDistance = 0.0410000011;
  71221. result.lensSeparationDistance = 0.0635000020;
  71222. result.interpupillaryDistance = 0.0640000030;
  71223. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  71224. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  71225. result.postProcessScaleFactor = 1.714605507808412;
  71226. result.lensCenterOffset = 0.151976421;
  71227. return result;
  71228. };
  71229. return VRCameraMetrics;
  71230. }());
  71231. BABYLON.VRCameraMetrics = VRCameraMetrics;
  71232. })(BABYLON || (BABYLON = {}));
  71233. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  71234. var BABYLON;
  71235. (function (BABYLON) {
  71236. var WebVRFreeCamera = /** @class */ (function (_super) {
  71237. __extends(WebVRFreeCamera, _super);
  71238. function WebVRFreeCamera(name, position, scene, webVROptions) {
  71239. if (webVROptions === void 0) { webVROptions = {}; }
  71240. var _this = _super.call(this, name, position, scene) || this;
  71241. _this.webVROptions = webVROptions;
  71242. _this._vrDevice = null;
  71243. _this.rawPose = null;
  71244. _this._specsVersion = "1.1";
  71245. _this._attached = false;
  71246. _this._descendants = [];
  71247. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71248. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71249. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  71250. _this._standingMatrix = null;
  71251. // Represents device position and rotation in babylon space
  71252. _this.devicePosition = BABYLON.Vector3.Zero();
  71253. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  71254. _this.deviceScaleFactor = 1;
  71255. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71256. _this._worldToDevice = BABYLON.Matrix.Identity();
  71257. _this.controllers = [];
  71258. _this.onControllersAttachedObservable = new BABYLON.Observable();
  71259. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  71260. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  71261. _this._defaultHeight = 0;
  71262. _this.deviceDistanceToRoomGround = function () {
  71263. if (_this._standingMatrix) {
  71264. // Add standing matrix offset to get real offset from ground in room
  71265. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  71266. return _this._deviceRoomPosition.y + _this._workingVector.y;
  71267. }
  71268. else {
  71269. return _this._defaultHeight;
  71270. }
  71271. };
  71272. _this.useStandingMatrix = function (callback) {
  71273. if (callback === void 0) { callback = function (bool) { }; }
  71274. // Use standing matrix if availible
  71275. if (!navigator || !navigator.getVRDisplays) {
  71276. callback(false);
  71277. }
  71278. else {
  71279. navigator.getVRDisplays().then(function (displays) {
  71280. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  71281. callback(false);
  71282. }
  71283. else {
  71284. _this._standingMatrix = new BABYLON.Matrix();
  71285. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  71286. if (!_this.getScene().useRightHandedSystem) {
  71287. [2, 6, 8, 9, 14].forEach(function (num) {
  71288. if (_this._standingMatrix) {
  71289. _this._standingMatrix.m[num] *= -1;
  71290. }
  71291. });
  71292. }
  71293. callback(true);
  71294. }
  71295. });
  71296. }
  71297. };
  71298. _this._workingVector = BABYLON.Vector3.Zero();
  71299. _this._oneVector = BABYLON.Vector3.One();
  71300. _this._workingMatrix = BABYLON.Matrix.Identity();
  71301. _this._cache.position = BABYLON.Vector3.Zero();
  71302. if (webVROptions.defaultHeight) {
  71303. _this._defaultHeight = webVROptions.defaultHeight;
  71304. _this.position.y = _this._defaultHeight;
  71305. }
  71306. _this.minZ = 0.1;
  71307. //legacy support - the compensation boolean was removed.
  71308. if (arguments.length === 5) {
  71309. _this.webVROptions = arguments[4];
  71310. }
  71311. // default webVR options
  71312. if (_this.webVROptions.trackPosition == undefined) {
  71313. _this.webVROptions.trackPosition = true;
  71314. }
  71315. if (_this.webVROptions.controllerMeshes == undefined) {
  71316. _this.webVROptions.controllerMeshes = true;
  71317. }
  71318. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  71319. _this.webVROptions.defaultLightingOnControllers = true;
  71320. }
  71321. _this.rotationQuaternion = new BABYLON.Quaternion();
  71322. if (_this.webVROptions && _this.webVROptions.positionScale) {
  71323. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  71324. }
  71325. //enable VR
  71326. var engine = _this.getEngine();
  71327. _this._onVREnabled = function (success) { if (success) {
  71328. _this.initControllers();
  71329. } };
  71330. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  71331. engine.initWebVR().add(function (event) {
  71332. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  71333. return;
  71334. }
  71335. _this._vrDevice = event.vrDisplay;
  71336. //reset the rig parameters.
  71337. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  71338. if (_this._attached) {
  71339. _this.getEngine().enableVR();
  71340. }
  71341. });
  71342. if (typeof (VRFrameData) !== "undefined")
  71343. _this._frameData = new VRFrameData();
  71344. /**
  71345. * The idea behind the following lines:
  71346. * objects that have the camera as parent should actually have the rig cameras as a parent.
  71347. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  71348. * the second will not show it correctly.
  71349. *
  71350. * To solve this - each object that has the camera as parent will be added to a protected array.
  71351. * When the rig camera renders, it will take this array and set all of those to be its children.
  71352. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  71353. * Amazing!
  71354. */
  71355. scene.onBeforeCameraRenderObservable.add(function (camera) {
  71356. if (camera.parent === _this && _this.rigParenting) {
  71357. _this._descendants = _this.getDescendants(true, function (n) {
  71358. // don't take the cameras or the controllers!
  71359. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  71360. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  71361. return !isController && !isRigCamera;
  71362. });
  71363. _this._descendants.forEach(function (node) {
  71364. node.parent = camera;
  71365. });
  71366. }
  71367. });
  71368. scene.onAfterCameraRenderObservable.add(function (camera) {
  71369. if (camera.parent === _this && _this.rigParenting) {
  71370. _this._descendants.forEach(function (node) {
  71371. node.parent = _this;
  71372. });
  71373. }
  71374. });
  71375. return _this;
  71376. }
  71377. WebVRFreeCamera.prototype.dispose = function () {
  71378. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  71379. _super.prototype.dispose.call(this);
  71380. };
  71381. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  71382. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  71383. var gp = _a[_i];
  71384. if (gp.hand === name) {
  71385. return gp;
  71386. }
  71387. }
  71388. return null;
  71389. };
  71390. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  71391. get: function () {
  71392. if (!this._leftController) {
  71393. this._leftController = this.getControllerByName("left");
  71394. }
  71395. return this._leftController;
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. ;
  71401. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  71402. get: function () {
  71403. if (!this._rightController) {
  71404. this._rightController = this.getControllerByName("right");
  71405. }
  71406. return this._rightController;
  71407. },
  71408. enumerable: true,
  71409. configurable: true
  71410. });
  71411. ;
  71412. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  71413. if (length === void 0) { length = 100; }
  71414. if (this.leftCamera) {
  71415. // Use left eye to avoid computation to compute center on every call
  71416. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  71417. }
  71418. else {
  71419. return _super.prototype.getForwardRay.call(this, length);
  71420. }
  71421. };
  71422. WebVRFreeCamera.prototype._checkInputs = function () {
  71423. if (this._vrDevice && this._vrDevice.isPresenting) {
  71424. this._vrDevice.getFrameData(this._frameData);
  71425. this.updateFromDevice(this._frameData.pose);
  71426. }
  71427. _super.prototype._checkInputs.call(this);
  71428. };
  71429. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  71430. if (poseData && poseData.orientation) {
  71431. this.rawPose = poseData;
  71432. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  71433. if (this.getScene().useRightHandedSystem) {
  71434. this._deviceRoomRotationQuaternion.z *= -1;
  71435. this._deviceRoomRotationQuaternion.w *= -1;
  71436. }
  71437. if (this.webVROptions.trackPosition && this.rawPose.position) {
  71438. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  71439. if (this.getScene().useRightHandedSystem) {
  71440. this._deviceRoomPosition.z *= -1;
  71441. }
  71442. }
  71443. }
  71444. };
  71445. /**
  71446. * WebVR's attach control will start broadcasting frames to the device.
  71447. * Note that in certain browsers (chrome for example) this function must be called
  71448. * within a user-interaction callback. Example:
  71449. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  71450. *
  71451. * @param {HTMLElement} element
  71452. * @param {boolean} [noPreventDefault]
  71453. *
  71454. * @memberOf WebVRFreeCamera
  71455. */
  71456. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  71457. _super.prototype.attachControl.call(this, element, noPreventDefault);
  71458. this._attached = true;
  71459. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  71460. if (this._vrDevice) {
  71461. this.getEngine().enableVR();
  71462. }
  71463. };
  71464. WebVRFreeCamera.prototype.detachControl = function (element) {
  71465. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71466. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71467. _super.prototype.detachControl.call(this, element);
  71468. this._attached = false;
  71469. this.getEngine().disableVR();
  71470. };
  71471. WebVRFreeCamera.prototype.getClassName = function () {
  71472. return "WebVRFreeCamera";
  71473. };
  71474. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  71475. //uses the vrDisplay's "resetPose()".
  71476. //pitch and roll won't be affected.
  71477. this._vrDevice.resetPose();
  71478. };
  71479. WebVRFreeCamera.prototype._updateRigCameras = function () {
  71480. var camLeft = this._rigCameras[0];
  71481. var camRight = this._rigCameras[1];
  71482. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71483. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71484. camLeft.position.copyFrom(this._deviceRoomPosition);
  71485. camRight.position.copyFrom(this._deviceRoomPosition);
  71486. };
  71487. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  71488. var _this = this;
  71489. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  71490. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  71491. this.update();
  71492. // Set working vector to the device position in room space rotated by the new rotation
  71493. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  71494. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  71495. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  71496. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  71497. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  71498. // Add translation from anchor position
  71499. this._deviceToWorld.getTranslationToRef(this._workingVector);
  71500. this._workingVector.addInPlace(this.position);
  71501. this._workingVector.subtractInPlace(this._cache.position);
  71502. this._deviceToWorld.setTranslation(this._workingVector);
  71503. // Set an inverted matrix to be used when updating the camera
  71504. this._deviceToWorld.invertToRef(this._worldToDevice);
  71505. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  71506. this.controllers.forEach(function (controller) {
  71507. controller._deviceToWorld = _this._deviceToWorld;
  71508. controller.update();
  71509. });
  71510. this.update();
  71511. }
  71512. if (!ignoreParentClass) {
  71513. _super.prototype._updateCache.call(this);
  71514. }
  71515. };
  71516. WebVRFreeCamera.prototype.update = function () {
  71517. // Get current device position in babylon world
  71518. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  71519. // Get current device rotation in babylon world
  71520. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  71521. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  71522. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71523. _super.prototype.update.call(this);
  71524. };
  71525. WebVRFreeCamera.prototype._getViewMatrix = function () {
  71526. return BABYLON.Matrix.Identity();
  71527. };
  71528. /**
  71529. * This function is called by the two RIG cameras.
  71530. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  71531. */
  71532. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  71533. var _this = this;
  71534. //WebVR 1.1
  71535. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  71536. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  71537. if (!this.getScene().useRightHandedSystem) {
  71538. [2, 6, 8, 9, 14].forEach(function (num) {
  71539. _this._webvrViewMatrix.m[num] *= -1;
  71540. });
  71541. }
  71542. // update the camera rotation matrix
  71543. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  71544. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  71545. // Computing target and final matrix
  71546. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  71547. var parentCamera = this._cameraRigParams["parentCamera"];
  71548. // should the view matrix be updated with scale and position offset?
  71549. if (parentCamera.deviceScaleFactor !== 1) {
  71550. this._webvrViewMatrix.invert();
  71551. // scale the position, if set
  71552. if (parentCamera.deviceScaleFactor) {
  71553. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  71554. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  71555. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  71556. }
  71557. this._webvrViewMatrix.invert();
  71558. }
  71559. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  71560. return this._webvrViewMatrix;
  71561. };
  71562. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  71563. var _this = this;
  71564. var parentCamera = this.parent;
  71565. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  71566. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  71567. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  71568. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  71569. //babylon compatible matrix
  71570. if (!this.getScene().useRightHandedSystem) {
  71571. [8, 9, 10, 11].forEach(function (num) {
  71572. _this._projectionMatrix.m[num] *= -1;
  71573. });
  71574. }
  71575. return this._projectionMatrix;
  71576. };
  71577. WebVRFreeCamera.prototype.initControllers = function () {
  71578. var _this = this;
  71579. this.controllers = [];
  71580. var manager = this.getScene().gamepadManager;
  71581. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71582. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71583. var webVrController = gamepad;
  71584. if (webVrController.defaultModel) {
  71585. webVrController.defaultModel.setEnabled(false);
  71586. }
  71587. if (webVrController.hand === "right") {
  71588. _this._rightController = null;
  71589. }
  71590. if (webVrController.hand === "left") {
  71591. _this._rightController = null;
  71592. }
  71593. var controllerIndex = _this.controllers.indexOf(webVrController);
  71594. if (controllerIndex !== -1) {
  71595. _this.controllers.splice(controllerIndex, 1);
  71596. }
  71597. }
  71598. });
  71599. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71600. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71601. var webVrController_1 = gamepad;
  71602. webVrController_1._deviceToWorld = _this._deviceToWorld;
  71603. if (_this.webVROptions.controllerMeshes) {
  71604. if (webVrController_1.defaultModel) {
  71605. webVrController_1.defaultModel.setEnabled(true);
  71606. }
  71607. else {
  71608. // Load the meshes
  71609. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  71610. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  71611. if (_this.webVROptions.defaultLightingOnControllers) {
  71612. if (!_this._lightOnControllers) {
  71613. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71614. }
  71615. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71616. var children = mesh.getChildren();
  71617. if (children.length !== 0) {
  71618. children.forEach(function (mesh) {
  71619. light.includedOnlyMeshes.push(mesh);
  71620. activateLightOnSubMeshes_1(mesh, light);
  71621. });
  71622. }
  71623. };
  71624. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71625. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71626. }
  71627. });
  71628. }
  71629. }
  71630. webVrController_1.attachToPoseControlledCamera(_this);
  71631. // since this is async - sanity check. Is the controller already stored?
  71632. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71633. //add to the controllers array
  71634. _this.controllers.push(webVrController_1);
  71635. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71636. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71637. // So we're overriding setting left & right manually to be sure
  71638. var firstViveWandDetected = false;
  71639. for (var i = 0; i < _this.controllers.length; i++) {
  71640. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71641. if (!firstViveWandDetected) {
  71642. firstViveWandDetected = true;
  71643. _this.controllers[i].hand = "left";
  71644. }
  71645. else {
  71646. _this.controllers[i].hand = "right";
  71647. }
  71648. }
  71649. }
  71650. //did we find enough controllers? Great! let the developer know.
  71651. if (_this.controllers.length >= 2) {
  71652. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  71653. }
  71654. }
  71655. }
  71656. });
  71657. };
  71658. return WebVRFreeCamera;
  71659. }(BABYLON.FreeCamera));
  71660. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  71661. })(BABYLON || (BABYLON = {}));
  71662. //# sourceMappingURL=babylon.webVRCamera.js.map
  71663. var BABYLON;
  71664. (function (BABYLON) {
  71665. // We're mainly based on the logic defined into the FreeCamera code
  71666. var DeviceOrientationCamera = /** @class */ (function (_super) {
  71667. __extends(DeviceOrientationCamera, _super);
  71668. function DeviceOrientationCamera(name, position, scene) {
  71669. var _this = _super.call(this, name, position, scene) || this;
  71670. _this._quaternionCache = new BABYLON.Quaternion();
  71671. _this.inputs.addDeviceOrientation();
  71672. return _this;
  71673. }
  71674. DeviceOrientationCamera.prototype.getClassName = function () {
  71675. return "DeviceOrientationCamera";
  71676. };
  71677. DeviceOrientationCamera.prototype._checkInputs = function () {
  71678. _super.prototype._checkInputs.call(this);
  71679. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71680. if (this._initialQuaternion) {
  71681. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71682. }
  71683. };
  71684. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71685. var _this = this;
  71686. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71687. //can only work if this camera has a rotation quaternion already.
  71688. if (!this.rotationQuaternion)
  71689. return;
  71690. if (!this._initialQuaternion) {
  71691. this._initialQuaternion = new BABYLON.Quaternion();
  71692. }
  71693. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71694. ['x', 'y', 'z'].forEach(function (axisName) {
  71695. if (!axis[axisName]) {
  71696. _this._initialQuaternion[axisName] = 0;
  71697. }
  71698. else {
  71699. _this._initialQuaternion[axisName] *= -1;
  71700. }
  71701. });
  71702. this._initialQuaternion.normalize();
  71703. //force rotation update
  71704. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71705. };
  71706. return DeviceOrientationCamera;
  71707. }(BABYLON.FreeCamera));
  71708. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71709. })(BABYLON || (BABYLON = {}));
  71710. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71711. var BABYLON;
  71712. (function (BABYLON) {
  71713. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71714. __extends(VRDeviceOrientationFreeCamera, _super);
  71715. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71716. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71717. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71718. var _this = _super.call(this, name, position, scene) || this;
  71719. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71720. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71721. return _this;
  71722. }
  71723. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  71724. return "VRDeviceOrientationFreeCamera";
  71725. };
  71726. return VRDeviceOrientationFreeCamera;
  71727. }(BABYLON.DeviceOrientationCamera));
  71728. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  71729. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  71730. __extends(VRDeviceOrientationGamepadCamera, _super);
  71731. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71732. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71733. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71734. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  71735. _this.inputs.addGamepad();
  71736. return _this;
  71737. }
  71738. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  71739. return "VRDeviceOrientationGamepadCamera";
  71740. };
  71741. return VRDeviceOrientationGamepadCamera;
  71742. }(VRDeviceOrientationFreeCamera));
  71743. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  71744. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  71745. __extends(VRDeviceOrientationArcRotateCamera, _super);
  71746. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  71747. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71748. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71749. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71750. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71751. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71752. _this.inputs.addVRDeviceOrientation();
  71753. return _this;
  71754. }
  71755. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  71756. return "VRDeviceOrientationArcRotateCamera";
  71757. };
  71758. return VRDeviceOrientationArcRotateCamera;
  71759. }(BABYLON.ArcRotateCamera));
  71760. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  71761. })(BABYLON || (BABYLON = {}));
  71762. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  71763. var BABYLON;
  71764. (function (BABYLON) {
  71765. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  71766. __extends(AnaglyphFreeCamera, _super);
  71767. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  71768. var _this = _super.call(this, name, position, scene) || this;
  71769. _this.interaxialDistance = interaxialDistance;
  71770. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71771. return _this;
  71772. }
  71773. AnaglyphFreeCamera.prototype.getClassName = function () {
  71774. return "AnaglyphFreeCamera";
  71775. };
  71776. return AnaglyphFreeCamera;
  71777. }(BABYLON.FreeCamera));
  71778. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  71779. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  71780. __extends(AnaglyphArcRotateCamera, _super);
  71781. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  71782. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71783. _this.interaxialDistance = interaxialDistance;
  71784. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71785. return _this;
  71786. }
  71787. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  71788. return "AnaglyphArcRotateCamera";
  71789. };
  71790. return AnaglyphArcRotateCamera;
  71791. }(BABYLON.ArcRotateCamera));
  71792. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  71793. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  71794. __extends(AnaglyphGamepadCamera, _super);
  71795. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  71796. var _this = _super.call(this, name, position, scene) || this;
  71797. _this.interaxialDistance = interaxialDistance;
  71798. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71799. return _this;
  71800. }
  71801. AnaglyphGamepadCamera.prototype.getClassName = function () {
  71802. return "AnaglyphGamepadCamera";
  71803. };
  71804. return AnaglyphGamepadCamera;
  71805. }(BABYLON.GamepadCamera));
  71806. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  71807. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  71808. __extends(AnaglyphUniversalCamera, _super);
  71809. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  71810. var _this = _super.call(this, name, position, scene) || this;
  71811. _this.interaxialDistance = interaxialDistance;
  71812. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71813. return _this;
  71814. }
  71815. AnaglyphUniversalCamera.prototype.getClassName = function () {
  71816. return "AnaglyphUniversalCamera";
  71817. };
  71818. return AnaglyphUniversalCamera;
  71819. }(BABYLON.UniversalCamera));
  71820. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  71821. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  71822. __extends(StereoscopicFreeCamera, _super);
  71823. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71824. var _this = _super.call(this, name, position, scene) || this;
  71825. _this.interaxialDistance = interaxialDistance;
  71826. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71827. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71828. return _this;
  71829. }
  71830. StereoscopicFreeCamera.prototype.getClassName = function () {
  71831. return "StereoscopicFreeCamera";
  71832. };
  71833. return StereoscopicFreeCamera;
  71834. }(BABYLON.FreeCamera));
  71835. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  71836. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  71837. __extends(StereoscopicArcRotateCamera, _super);
  71838. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  71839. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71840. _this.interaxialDistance = interaxialDistance;
  71841. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71842. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71843. return _this;
  71844. }
  71845. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  71846. return "StereoscopicArcRotateCamera";
  71847. };
  71848. return StereoscopicArcRotateCamera;
  71849. }(BABYLON.ArcRotateCamera));
  71850. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  71851. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  71852. __extends(StereoscopicGamepadCamera, _super);
  71853. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71854. var _this = _super.call(this, name, position, scene) || this;
  71855. _this.interaxialDistance = interaxialDistance;
  71856. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71857. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71858. return _this;
  71859. }
  71860. StereoscopicGamepadCamera.prototype.getClassName = function () {
  71861. return "StereoscopicGamepadCamera";
  71862. };
  71863. return StereoscopicGamepadCamera;
  71864. }(BABYLON.GamepadCamera));
  71865. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  71866. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  71867. __extends(StereoscopicUniversalCamera, _super);
  71868. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71869. var _this = _super.call(this, name, position, scene) || this;
  71870. _this.interaxialDistance = interaxialDistance;
  71871. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71872. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71873. return _this;
  71874. }
  71875. StereoscopicUniversalCamera.prototype.getClassName = function () {
  71876. return "StereoscopicUniversalCamera";
  71877. };
  71878. return StereoscopicUniversalCamera;
  71879. }(BABYLON.UniversalCamera));
  71880. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  71881. })(BABYLON || (BABYLON = {}));
  71882. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  71883. var BABYLON;
  71884. (function (BABYLON) {
  71885. var VRExperienceHelper = /** @class */ (function () {
  71886. function VRExperienceHelper(scene, webVROptions) {
  71887. if (webVROptions === void 0) { webVROptions = {}; }
  71888. var _this = this;
  71889. this.webVROptions = webVROptions;
  71890. // Can the system support WebVR, even if a headset isn't plugged in?
  71891. this._webVRsupported = false;
  71892. // If WebVR is supported, is a headset plugged in and are we ready to present?
  71893. this._webVRready = false;
  71894. // Are we waiting for the requestPresent callback to complete?
  71895. this._webVRrequesting = false;
  71896. // Are we presenting to the headset right now?
  71897. this._webVRpresenting = false;
  71898. // Are we presenting in the fullscreen fallback?
  71899. this._fullscreenVRpresenting = false;
  71900. /**
  71901. * Observable raised when entering VR.
  71902. */
  71903. this.onEnteringVRObservable = new BABYLON.Observable();
  71904. /**
  71905. * Observable raised when exiting VR.
  71906. */
  71907. this.onExitingVRObservable = new BABYLON.Observable();
  71908. /**
  71909. * Observable raised when controller mesh is loaded.
  71910. */
  71911. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  71912. this._useCustomVRButton = false;
  71913. this._teleportationRequested = false;
  71914. this._teleportationEnabledOnLeftController = false;
  71915. this._teleportationEnabledOnRightController = false;
  71916. this._interactionsEnabledOnLeftController = false;
  71917. this._interactionsEnabledOnRightController = false;
  71918. this._leftControllerReady = false;
  71919. this._rightControllerReady = false;
  71920. this._floorMeshesCollection = [];
  71921. this._teleportationAllowed = false;
  71922. this._rotationAllowed = true;
  71923. this._teleportationRequestInitiated = false;
  71924. this._teleportationBackRequestInitiated = false;
  71925. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  71926. this._rotationRightAsked = false;
  71927. this._rotationLeftAsked = false;
  71928. this._isDefaultTeleportationTarget = true;
  71929. this._teleportationFillColor = "#444444";
  71930. this._teleportationBorderColor = "#FFFFFF";
  71931. this._rotationAngle = 0;
  71932. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  71933. this._padSensibilityUp = 0.65;
  71934. this._padSensibilityDown = 0.35;
  71935. this.onNewMeshSelected = new BABYLON.Observable();
  71936. this._pointerDownOnMeshAsked = false;
  71937. this._isActionableMesh = false;
  71938. this._teleportationEnabled = false;
  71939. this._interactionsEnabled = false;
  71940. this._interactionsRequested = false;
  71941. this._displayGaze = true;
  71942. this._displayLaserPointer = true;
  71943. this._dpadPressed = true;
  71944. this._onResize = function () {
  71945. _this.moveButtonToBottomRight();
  71946. if (_this._fullscreenVRpresenting && _this._webVRready) {
  71947. _this.exitVR();
  71948. }
  71949. };
  71950. this._onFullscreenChange = function () {
  71951. if (document.fullscreen !== undefined) {
  71952. _this._fullscreenVRpresenting = document.fullscreen;
  71953. }
  71954. else if (document.mozFullScreen !== undefined) {
  71955. _this._fullscreenVRpresenting = document.mozFullScreen;
  71956. }
  71957. else if (document.webkitIsFullScreen !== undefined) {
  71958. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71959. }
  71960. else if (document.msIsFullScreen !== undefined) {
  71961. _this._fullscreenVRpresenting = document.msIsFullScreen;
  71962. }
  71963. if (!_this._fullscreenVRpresenting && _this._canvas) {
  71964. _this.exitVR();
  71965. if (!_this._useCustomVRButton) {
  71966. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  71967. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  71968. }
  71969. }
  71970. };
  71971. this.beforeRender = function () {
  71972. _this._castRayAndSelectObject();
  71973. };
  71974. this._onNewGamepadConnected = function (gamepad) {
  71975. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71976. if (gamepad.leftStick) {
  71977. gamepad.onleftstickchanged(function (stickValues) {
  71978. if (_this._teleportationEnabled) {
  71979. // Listening to classic/xbox gamepad only if no VR controller is active
  71980. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  71981. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  71982. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  71983. _this._checkTeleportWithRay(stickValues);
  71984. _this._checkTeleportBackwards(stickValues);
  71985. }
  71986. }
  71987. });
  71988. }
  71989. if (gamepad.rightStick) {
  71990. gamepad.onrightstickchanged(function (stickValues) {
  71991. if (_this._teleportationEnabled) {
  71992. _this._checkRotate(stickValues);
  71993. }
  71994. });
  71995. }
  71996. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  71997. gamepad.onbuttondown(function (buttonPressed) {
  71998. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  71999. _this._selectionPointerDown();
  72000. }
  72001. });
  72002. gamepad.onbuttonup(function (buttonPressed) {
  72003. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72004. _this._selectionPointerUp();
  72005. }
  72006. });
  72007. }
  72008. }
  72009. else {
  72010. var webVRController = gamepad;
  72011. _this._tryEnableInteractionOnController(webVRController);
  72012. }
  72013. };
  72014. // 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
  72015. this._tryEnableInteractionOnController = function (webVRController) {
  72016. if (webVRController.hand === "left") {
  72017. _this._leftControllerReady = true;
  72018. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  72019. _this._enableInteractionOnController(webVRController);
  72020. }
  72021. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  72022. _this._enableTeleportationOnController(webVRController);
  72023. }
  72024. }
  72025. if (webVRController.hand === "right") {
  72026. _this._rightControllerReady = true;
  72027. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  72028. _this._enableInteractionOnController(webVRController);
  72029. }
  72030. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  72031. _this._enableTeleportationOnController(webVRController);
  72032. }
  72033. }
  72034. };
  72035. this._onNewGamepadDisconnected = function (gamepad) {
  72036. if (gamepad instanceof BABYLON.WebVRController) {
  72037. if (gamepad.hand === "left") {
  72038. _this._interactionsEnabledOnLeftController = false;
  72039. _this._teleportationEnabledOnLeftController = false;
  72040. _this._leftControllerReady = false;
  72041. if (_this._leftLaserPointer) {
  72042. _this._leftLaserPointer.dispose();
  72043. }
  72044. }
  72045. if (gamepad.hand === "right") {
  72046. _this._interactionsEnabledOnRightController = false;
  72047. _this._teleportationEnabledOnRightController = false;
  72048. _this._rightControllerReady = false;
  72049. if (_this._rightLaserPointer) {
  72050. _this._rightLaserPointer.dispose();
  72051. }
  72052. }
  72053. }
  72054. };
  72055. this._workingVector = BABYLON.Vector3.Zero();
  72056. this._workingQuaternion = BABYLON.Quaternion.Identity();
  72057. this._workingMatrix = BABYLON.Matrix.Identity();
  72058. this._scene = scene;
  72059. this._canvas = scene.getEngine().getRenderingCanvas();
  72060. // Parse options
  72061. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  72062. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  72063. }
  72064. if (webVROptions.createDeviceOrientationCamera === undefined) {
  72065. webVROptions.createDeviceOrientationCamera = true;
  72066. }
  72067. if (webVROptions.defaultHeight === undefined) {
  72068. webVROptions.defaultHeight = 1.7;
  72069. }
  72070. if (webVROptions.useCustomVRButton) {
  72071. this._useCustomVRButton = true;
  72072. if (webVROptions.customVRButton) {
  72073. this._btnVR = webVROptions.customVRButton;
  72074. }
  72075. }
  72076. if (webVROptions.rayLength) {
  72077. this._rayLength = webVROptions.rayLength;
  72078. }
  72079. this._defaultHeight = webVROptions.defaultHeight;
  72080. // Set position
  72081. if (this._scene.activeCamera) {
  72082. this._position = this._scene.activeCamera.position.clone();
  72083. }
  72084. else {
  72085. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  72086. }
  72087. // Set non-vr camera
  72088. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  72089. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  72090. // Copy data from existing camera
  72091. if (this._scene.activeCamera) {
  72092. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  72093. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  72094. // Set rotation from previous camera
  72095. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  72096. var targetCamera = this._scene.activeCamera;
  72097. if (targetCamera.rotationQuaternion) {
  72098. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  72099. }
  72100. else {
  72101. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  72102. }
  72103. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  72104. }
  72105. }
  72106. this._scene.activeCamera = this._deviceOrientationCamera;
  72107. if (this._canvas) {
  72108. this._scene.activeCamera.attachControl(this._canvas);
  72109. }
  72110. }
  72111. else {
  72112. this._existingCamera = this._scene.activeCamera;
  72113. }
  72114. // Create VR cameras
  72115. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72116. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  72117. }
  72118. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  72119. this._webVRCamera.useStandingMatrix();
  72120. // Create default button
  72121. if (!this._useCustomVRButton) {
  72122. this._btnVR = document.createElement("BUTTON");
  72123. this._btnVR.className = "babylonVRicon";
  72124. this._btnVR.id = "babylonVRiconbtn";
  72125. this._btnVR.title = "Click to switch to VR";
  72126. 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) }";
  72127. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  72128. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  72129. // css += ".babylonVRicon.vrdisplaysupported { }";
  72130. // css += ".babylonVRicon.vrdisplayready { }";
  72131. // css += ".babylonVRicon.vrdisplayrequesting { }";
  72132. var style = document.createElement('style');
  72133. style.appendChild(document.createTextNode(css));
  72134. document.getElementsByTagName('head')[0].appendChild(style);
  72135. this.moveButtonToBottomRight();
  72136. }
  72137. // VR button click event
  72138. if (this._btnVR) {
  72139. this._btnVR.addEventListener("click", function () {
  72140. if (!_this.isInVRMode) {
  72141. _this.enterVR();
  72142. }
  72143. else {
  72144. _this.exitVR();
  72145. }
  72146. });
  72147. }
  72148. // Window events
  72149. window.addEventListener("resize", this._onResize);
  72150. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  72151. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  72152. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  72153. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  72154. // Display vr button when headset is connected
  72155. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72156. this.displayVRButton();
  72157. }
  72158. else {
  72159. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  72160. if (e.vrDisplay) {
  72161. _this.displayVRButton();
  72162. }
  72163. });
  72164. }
  72165. // Exiting VR mode using 'ESC' key on desktop
  72166. this._onKeyDown = function (event) {
  72167. if (event.keyCode === 27 && _this.isInVRMode) {
  72168. _this.exitVR();
  72169. }
  72170. };
  72171. document.addEventListener("keydown", this._onKeyDown);
  72172. // Exiting VR mode double tapping the touch screen
  72173. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  72174. if (_this.isInVRMode) {
  72175. _this.exitVR();
  72176. if (_this._fullscreenVRpresenting) {
  72177. _this._scene.getEngine().switchFullscreen(true);
  72178. }
  72179. }
  72180. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  72181. // Listen for WebVR display changes
  72182. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  72183. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  72184. this._onVRRequestPresentStart = function () {
  72185. _this._webVRrequesting = true;
  72186. _this.updateButtonVisibility();
  72187. };
  72188. this._onVRRequestPresentComplete = function (success) {
  72189. _this._webVRrequesting = false;
  72190. _this.updateButtonVisibility();
  72191. };
  72192. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  72193. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  72194. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  72195. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72196. scene.onDisposeObservable.add(function () {
  72197. _this.dispose();
  72198. });
  72199. // Gamepad connection events
  72200. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  72201. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  72202. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  72203. this.updateButtonVisibility();
  72204. //create easing functions
  72205. this._circleEase = new BABYLON.CircleEase();
  72206. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72207. }
  72208. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  72209. /** Return this.onEnteringVRObservable
  72210. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  72211. */
  72212. get: function () {
  72213. return this.onEnteringVRObservable;
  72214. },
  72215. enumerable: true,
  72216. configurable: true
  72217. });
  72218. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  72219. /** Return this.onExitingVRObservable
  72220. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  72221. */
  72222. get: function () {
  72223. return this.onExitingVRObservable;
  72224. },
  72225. enumerable: true,
  72226. configurable: true
  72227. });
  72228. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  72229. /** Return this.onControllerMeshLoadedObservable
  72230. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  72231. */
  72232. get: function () {
  72233. return this.onControllerMeshLoadedObservable;
  72234. },
  72235. enumerable: true,
  72236. configurable: true
  72237. });
  72238. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  72239. get: function () {
  72240. return this._teleportationTarget;
  72241. },
  72242. set: function (value) {
  72243. if (value) {
  72244. value.name = "teleportationTarget";
  72245. this._isDefaultTeleportationTarget = false;
  72246. this._teleportationTarget = value;
  72247. }
  72248. },
  72249. enumerable: true,
  72250. configurable: true
  72251. });
  72252. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  72253. get: function () {
  72254. return this._displayGaze;
  72255. },
  72256. set: function (value) {
  72257. this._displayGaze = value;
  72258. if (!value) {
  72259. this._gazeTracker.isVisible = false;
  72260. }
  72261. },
  72262. enumerable: true,
  72263. configurable: true
  72264. });
  72265. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  72266. get: function () {
  72267. return this._displayLaserPointer;
  72268. },
  72269. set: function (value) {
  72270. this._displayLaserPointer = value;
  72271. if (!value) {
  72272. if (this._rightLaserPointer) {
  72273. this._rightLaserPointer.isVisible = false;
  72274. }
  72275. if (this._leftLaserPointer) {
  72276. this._leftLaserPointer.isVisible = false;
  72277. }
  72278. }
  72279. else {
  72280. if (this._rightLaserPointer) {
  72281. this._rightLaserPointer.isVisible = true;
  72282. }
  72283. else if (this._leftLaserPointer) {
  72284. this._leftLaserPointer.isVisible = true;
  72285. }
  72286. }
  72287. },
  72288. enumerable: true,
  72289. configurable: true
  72290. });
  72291. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  72292. get: function () {
  72293. return this._deviceOrientationCamera;
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  72299. // Based on the current WebVR support, returns the current VR camera used
  72300. get: function () {
  72301. if (this._webVRready) {
  72302. return this._webVRCamera;
  72303. }
  72304. else {
  72305. return this._scene.activeCamera;
  72306. }
  72307. },
  72308. enumerable: true,
  72309. configurable: true
  72310. });
  72311. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  72312. get: function () {
  72313. return this._webVRCamera;
  72314. },
  72315. enumerable: true,
  72316. configurable: true
  72317. });
  72318. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  72319. get: function () {
  72320. return this._vrDeviceOrientationCamera;
  72321. },
  72322. enumerable: true,
  72323. configurable: true
  72324. });
  72325. // Raised when one of the controller has loaded successfully its associated default mesh
  72326. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  72327. this._tryEnableInteractionOnController(webVRController);
  72328. try {
  72329. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  72330. }
  72331. catch (err) {
  72332. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  72333. }
  72334. };
  72335. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  72336. /**
  72337. * Gets a value indicating if we are currently in VR mode.
  72338. */
  72339. get: function () {
  72340. return this._webVRpresenting || this._fullscreenVRpresenting;
  72341. },
  72342. enumerable: true,
  72343. configurable: true
  72344. });
  72345. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  72346. var vrDisplay = this._scene.getEngine().getVRDevice();
  72347. if (vrDisplay) {
  72348. var wasPresenting = this._webVRpresenting;
  72349. // A VR display is connected
  72350. this._webVRpresenting = vrDisplay.isPresenting;
  72351. if (wasPresenting && !this._webVRpresenting)
  72352. this.exitVR();
  72353. }
  72354. else {
  72355. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  72356. }
  72357. this.updateButtonVisibility();
  72358. };
  72359. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  72360. this._webVRsupported = eventArgs.vrSupported;
  72361. this._webVRready = !!eventArgs.vrDisplay;
  72362. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  72363. this.updateButtonVisibility();
  72364. };
  72365. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  72366. if (this._canvas && !this._useCustomVRButton) {
  72367. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  72368. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  72369. }
  72370. };
  72371. VRExperienceHelper.prototype.displayVRButton = function () {
  72372. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  72373. document.body.appendChild(this._btnVR);
  72374. this._btnVRDisplayed = true;
  72375. }
  72376. };
  72377. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  72378. if (!this._btnVR || this._useCustomVRButton) {
  72379. return;
  72380. }
  72381. this._btnVR.className = "babylonVRicon";
  72382. if (this.isInVRMode) {
  72383. this._btnVR.className += " vrdisplaypresenting";
  72384. }
  72385. else {
  72386. if (this._webVRready)
  72387. this._btnVR.className += " vrdisplayready";
  72388. if (this._webVRsupported)
  72389. this._btnVR.className += " vrdisplaysupported";
  72390. if (this._webVRrequesting)
  72391. this._btnVR.className += " vrdisplayrequesting";
  72392. }
  72393. };
  72394. /**
  72395. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  72396. * Otherwise, will use the fullscreen API.
  72397. */
  72398. VRExperienceHelper.prototype.enterVR = function () {
  72399. if (this.onEnteringVRObservable) {
  72400. try {
  72401. this.onEnteringVRObservable.notifyObservers(this);
  72402. }
  72403. catch (err) {
  72404. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  72405. }
  72406. }
  72407. if (this._scene.activeCamera) {
  72408. this._position = this._scene.activeCamera.position.clone();
  72409. }
  72410. if (this._webVRrequesting)
  72411. return;
  72412. // If WebVR is supported and a headset is connected
  72413. if (this._webVRready) {
  72414. if (!this._webVRpresenting) {
  72415. this._webVRCamera.position = this._position;
  72416. this._scene.activeCamera = this._webVRCamera;
  72417. }
  72418. }
  72419. else if (this._vrDeviceOrientationCamera) {
  72420. this._vrDeviceOrientationCamera.position = this._position;
  72421. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  72422. this._scene.getEngine().switchFullscreen(true);
  72423. this.updateButtonVisibility();
  72424. }
  72425. if (this._scene.activeCamera && this._canvas) {
  72426. this._scene.activeCamera.attachControl(this._canvas);
  72427. }
  72428. };
  72429. /**
  72430. * Attempt to exit VR, or fullscreen.
  72431. */
  72432. VRExperienceHelper.prototype.exitVR = function () {
  72433. if (this.onExitingVRObservable) {
  72434. try {
  72435. this.onExitingVRObservable.notifyObservers(this);
  72436. }
  72437. catch (err) {
  72438. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  72439. }
  72440. }
  72441. if (this._webVRpresenting) {
  72442. this._scene.getEngine().disableVR();
  72443. }
  72444. if (this._scene.activeCamera) {
  72445. this._position = this._scene.activeCamera.position.clone();
  72446. }
  72447. if (this._deviceOrientationCamera) {
  72448. this._deviceOrientationCamera.position = this._position;
  72449. this._scene.activeCamera = this._deviceOrientationCamera;
  72450. if (this._canvas) {
  72451. this._scene.activeCamera.attachControl(this._canvas);
  72452. }
  72453. }
  72454. else if (this._existingCamera) {
  72455. this._existingCamera.position = this._position;
  72456. this._scene.activeCamera = this._existingCamera;
  72457. }
  72458. this.updateButtonVisibility();
  72459. };
  72460. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  72461. get: function () {
  72462. return this._position;
  72463. },
  72464. set: function (value) {
  72465. this._position = value;
  72466. if (this._scene.activeCamera) {
  72467. this._scene.activeCamera.position = value;
  72468. }
  72469. },
  72470. enumerable: true,
  72471. configurable: true
  72472. });
  72473. VRExperienceHelper.prototype.enableInteractions = function () {
  72474. var _this = this;
  72475. if (!this._interactionsEnabled) {
  72476. this._interactionsRequested = true;
  72477. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72478. this._enableInteractionOnController(this._webVRCamera.leftController);
  72479. }
  72480. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72481. this._enableInteractionOnController(this._webVRCamera.rightController);
  72482. }
  72483. this._createGazeTracker();
  72484. this.raySelectionPredicate = function (mesh) {
  72485. return true;
  72486. };
  72487. this.meshSelectionPredicate = function (mesh) {
  72488. return true;
  72489. };
  72490. this._raySelectionPredicate = function (mesh) {
  72491. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  72492. && mesh.name.indexOf("teleportationTarget") === -1
  72493. && mesh.name.indexOf("torusTeleportation") === -1
  72494. && mesh.name.indexOf("laserPointer") === -1)) {
  72495. return _this.raySelectionPredicate(mesh);
  72496. }
  72497. return false;
  72498. };
  72499. this._scene.registerBeforeRender(this.beforeRender);
  72500. this._interactionsEnabled = true;
  72501. }
  72502. };
  72503. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  72504. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  72505. if (this._floorMeshesCollection[i].id === mesh.id) {
  72506. return true;
  72507. }
  72508. }
  72509. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  72510. return true;
  72511. }
  72512. return false;
  72513. };
  72514. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  72515. if (!this._floorMeshesCollection) {
  72516. return;
  72517. }
  72518. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  72519. return;
  72520. }
  72521. this._floorMeshesCollection.push(floorMesh);
  72522. };
  72523. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  72524. if (!this._floorMeshesCollection) {
  72525. return;
  72526. }
  72527. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  72528. if (meshIndex !== -1) {
  72529. this._floorMeshesCollection.splice(meshIndex, 1);
  72530. }
  72531. };
  72532. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  72533. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  72534. if (!this._teleportationEnabled) {
  72535. this._teleportationRequested = true;
  72536. this.enableInteractions();
  72537. if (vrTeleportationOptions) {
  72538. if (vrTeleportationOptions.floorMeshName) {
  72539. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  72540. }
  72541. if (vrTeleportationOptions.floorMeshes) {
  72542. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  72543. }
  72544. }
  72545. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72546. this._enableTeleportationOnController(this._webVRCamera.leftController);
  72547. }
  72548. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72549. this._enableTeleportationOnController(this._webVRCamera.rightController);
  72550. }
  72551. // Creates an image processing post process for the vignette not relying
  72552. // on the main scene configuration for image processing to reduce setup and spaces
  72553. // (gamma/linear) conflicts.
  72554. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  72555. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  72556. imageProcessingConfiguration.vignetteEnabled = true;
  72557. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  72558. this._webVRCamera.detachPostProcess(this._postProcessMove);
  72559. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  72560. this._teleportationEnabled = true;
  72561. if (this._isDefaultTeleportationTarget) {
  72562. this._createTeleportationCircles();
  72563. }
  72564. }
  72565. };
  72566. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  72567. var _this = this;
  72568. var controllerMesh = webVRController.mesh;
  72569. if (controllerMesh) {
  72570. var makeNotPick = function (root) {
  72571. root.name += " laserPointer";
  72572. root.getChildMeshes().forEach(function (c) {
  72573. makeNotPick(c);
  72574. });
  72575. };
  72576. makeNotPick(controllerMesh);
  72577. var childMeshes = controllerMesh.getChildMeshes();
  72578. for (var i = 0; i < childMeshes.length; i++) {
  72579. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  72580. controllerMesh = childMeshes[i];
  72581. break;
  72582. }
  72583. }
  72584. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  72585. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  72586. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72587. laserPointerMaterial.alpha = 0.6;
  72588. laserPointer.material = laserPointerMaterial;
  72589. laserPointer.rotation.x = Math.PI / 2;
  72590. laserPointer.parent = controllerMesh;
  72591. laserPointer.position.z = -0.5;
  72592. laserPointer.isVisible = false;
  72593. if (webVRController.hand === "left") {
  72594. this._leftLaserPointer = laserPointer;
  72595. this._interactionsEnabledOnLeftController = true;
  72596. if (!this._rightLaserPointer) {
  72597. this._leftLaserPointer.isVisible = true;
  72598. }
  72599. }
  72600. else {
  72601. this._rightLaserPointer = laserPointer;
  72602. this._interactionsEnabledOnRightController = true;
  72603. if (!this._leftLaserPointer) {
  72604. this._rightLaserPointer.isVisible = true;
  72605. }
  72606. }
  72607. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  72608. // Enabling / disabling laserPointer
  72609. if (_this._displayLaserPointer && stateObject.value === 1) {
  72610. laserPointer.isVisible = !laserPointer.isVisible;
  72611. // Laser pointer can only be active on left or right, not both at the same time
  72612. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  72613. _this._rightLaserPointer.isVisible = false;
  72614. }
  72615. else if (_this._leftLaserPointer) {
  72616. _this._leftLaserPointer.isVisible = false;
  72617. }
  72618. }
  72619. });
  72620. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  72621. if (!_this._pointerDownOnMeshAsked) {
  72622. if (stateObject.value > _this._padSensibilityUp) {
  72623. _this._selectionPointerDown();
  72624. }
  72625. }
  72626. else if (stateObject.value < _this._padSensibilityDown) {
  72627. _this._selectionPointerUp();
  72628. }
  72629. });
  72630. }
  72631. };
  72632. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  72633. if (webVRController === void 0) { webVRController = null; }
  72634. if (!this._teleportationRequestInitiated) {
  72635. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  72636. if (webVRController) {
  72637. // If laser pointer wasn't enabled yet
  72638. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  72639. this._leftLaserPointer.isVisible = true;
  72640. if (this._rightLaserPointer) {
  72641. this._rightLaserPointer.isVisible = false;
  72642. }
  72643. }
  72644. else if (this._displayLaserPointer && this._rightLaserPointer) {
  72645. this._rightLaserPointer.isVisible = true;
  72646. if (this._leftLaserPointer) {
  72647. this._leftLaserPointer.isVisible = false;
  72648. }
  72649. }
  72650. }
  72651. this._teleportationRequestInitiated = true;
  72652. }
  72653. }
  72654. else {
  72655. // Listening to the proper controller values changes to confirm teleportation
  72656. if (webVRController == null
  72657. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  72658. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  72659. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  72660. if (this._teleportationAllowed) {
  72661. this._teleportationAllowed = false;
  72662. this._teleportCamera();
  72663. }
  72664. this._teleportationRequestInitiated = false;
  72665. }
  72666. }
  72667. }
  72668. };
  72669. VRExperienceHelper.prototype._selectionPointerDown = function () {
  72670. this._pointerDownOnMeshAsked = true;
  72671. if (this._currentMeshSelected && this._currentHit) {
  72672. this._scene.simulatePointerDown(this._currentHit);
  72673. }
  72674. };
  72675. VRExperienceHelper.prototype._selectionPointerUp = function () {
  72676. if (this._currentMeshSelected && this._currentHit) {
  72677. this._scene.simulatePointerUp(this._currentHit);
  72678. }
  72679. this._pointerDownOnMeshAsked = false;
  72680. };
  72681. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  72682. // Only rotate when user is not currently selecting a teleportation location
  72683. if (this._teleportationRequestInitiated) {
  72684. return;
  72685. }
  72686. if (!this._rotationLeftAsked) {
  72687. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  72688. this._rotationLeftAsked = true;
  72689. if (this._rotationAllowed) {
  72690. this._rotateCamera(false);
  72691. }
  72692. }
  72693. }
  72694. else {
  72695. if (stateObject.x > -this._padSensibilityDown) {
  72696. this._rotationLeftAsked = false;
  72697. }
  72698. }
  72699. if (!this._rotationRightAsked) {
  72700. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  72701. this._rotationRightAsked = true;
  72702. if (this._rotationAllowed) {
  72703. this._rotateCamera(true);
  72704. }
  72705. }
  72706. }
  72707. else {
  72708. if (stateObject.x < this._padSensibilityDown) {
  72709. this._rotationRightAsked = false;
  72710. }
  72711. }
  72712. };
  72713. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  72714. // Only teleport backwards when user is not currently selecting a teleportation location
  72715. if (this._teleportationRequestInitiated) {
  72716. return;
  72717. }
  72718. // Teleport backwards
  72719. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  72720. if (!this._teleportationBackRequestInitiated) {
  72721. if (!this.currentVRCamera) {
  72722. return;
  72723. }
  72724. // Get rotation and position of the current camera
  72725. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  72726. var position = this.currentVRCamera.position;
  72727. // If the camera has device position, use that instead
  72728. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  72729. rotation = this.currentVRCamera.deviceRotationQuaternion;
  72730. position = this.currentVRCamera.devicePosition;
  72731. }
  72732. // Get matrix with only the y rotation of the device rotation
  72733. rotation.toEulerAnglesToRef(this._workingVector);
  72734. this._workingVector.z = 0;
  72735. this._workingVector.x = 0;
  72736. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  72737. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  72738. // Rotate backwards ray by device rotation to cast at the ground behind the user
  72739. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  72740. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  72741. var ray = new BABYLON.Ray(position, this._workingVector);
  72742. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  72743. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  72744. this._teleportCamera(hit.pickedPoint);
  72745. }
  72746. this._teleportationBackRequestInitiated = true;
  72747. }
  72748. }
  72749. else {
  72750. this._teleportationBackRequestInitiated = false;
  72751. }
  72752. };
  72753. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  72754. var _this = this;
  72755. var controllerMesh = webVRController.mesh;
  72756. if (controllerMesh) {
  72757. if (webVRController.hand === "left") {
  72758. if (!this._interactionsEnabledOnLeftController) {
  72759. this._enableInteractionOnController(webVRController);
  72760. }
  72761. this._teleportationEnabledOnLeftController = true;
  72762. }
  72763. else {
  72764. if (!this._interactionsEnabledOnRightController) {
  72765. this._enableInteractionOnController(webVRController);
  72766. }
  72767. this._teleportationEnabledOnRightController = true;
  72768. }
  72769. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72770. this._dpadPressed = false;
  72771. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  72772. _this._dpadPressed = stateObject.pressed;
  72773. if (!_this._dpadPressed) {
  72774. _this._rotationLeftAsked = false;
  72775. _this._rotationRightAsked = false;
  72776. _this._teleportationBackRequestInitiated = false;
  72777. }
  72778. });
  72779. }
  72780. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  72781. _this._checkTeleportBackwards(stateObject);
  72782. _this._checkTeleportWithRay(stateObject, webVRController);
  72783. _this._checkRotate(stateObject);
  72784. });
  72785. }
  72786. };
  72787. // Gaze support used to point to teleport or to interact with an object
  72788. VRExperienceHelper.prototype._createGazeTracker = function () {
  72789. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  72790. this._gazeTracker.bakeCurrentTransformIntoVertices();
  72791. this._gazeTracker.isPickable = false;
  72792. this._gazeTracker.isVisible = false;
  72793. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  72794. targetMat.specularColor = BABYLON.Color3.Black();
  72795. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72796. targetMat.backFaceCulling = false;
  72797. this._gazeTracker.material = targetMat;
  72798. };
  72799. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  72800. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  72801. this._teleportationTarget.isPickable = false;
  72802. var length = 512;
  72803. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  72804. dynamicTexture.hasAlpha = true;
  72805. var context = dynamicTexture.getContext();
  72806. var centerX = length / 2;
  72807. var centerY = length / 2;
  72808. var radius = 200;
  72809. context.beginPath();
  72810. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  72811. context.fillStyle = this._teleportationFillColor;
  72812. context.fill();
  72813. context.lineWidth = 10;
  72814. context.strokeStyle = this._teleportationBorderColor;
  72815. context.stroke();
  72816. context.closePath();
  72817. dynamicTexture.update();
  72818. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  72819. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  72820. this._teleportationTarget.material = teleportationCircleMaterial;
  72821. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  72822. torus.isPickable = false;
  72823. torus.parent = this._teleportationTarget;
  72824. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72825. var keys = [];
  72826. keys.push({
  72827. frame: 0,
  72828. value: 0
  72829. });
  72830. keys.push({
  72831. frame: 30,
  72832. value: 0.4
  72833. });
  72834. keys.push({
  72835. frame: 60,
  72836. value: 0
  72837. });
  72838. animationInnerCircle.setKeys(keys);
  72839. var easingFunction = new BABYLON.SineEase();
  72840. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72841. animationInnerCircle.setEasingFunction(easingFunction);
  72842. torus.animations = [];
  72843. torus.animations.push(animationInnerCircle);
  72844. this._scene.beginAnimation(torus, 0, 60, true);
  72845. this._hideTeleportationTarget();
  72846. };
  72847. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  72848. if (this._teleportationEnabled) {
  72849. this._teleportationTarget.isVisible = true;
  72850. if (this._isDefaultTeleportationTarget) {
  72851. this._teleportationTarget.getChildren()[0].isVisible = true;
  72852. }
  72853. }
  72854. };
  72855. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  72856. if (this._teleportationEnabled) {
  72857. this._teleportationTarget.isVisible = false;
  72858. if (this._isDefaultTeleportationTarget) {
  72859. this._teleportationTarget.getChildren()[0].isVisible = false;
  72860. }
  72861. }
  72862. };
  72863. VRExperienceHelper.prototype._rotateCamera = function (right) {
  72864. var _this = this;
  72865. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72866. return;
  72867. }
  72868. if (right) {
  72869. this._rotationAngle++;
  72870. }
  72871. else {
  72872. this._rotationAngle--;
  72873. }
  72874. this.currentVRCamera.animations = [];
  72875. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  72876. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72877. var animationRotationKeys = [];
  72878. animationRotationKeys.push({
  72879. frame: 0,
  72880. value: this.currentVRCamera.rotationQuaternion
  72881. });
  72882. animationRotationKeys.push({
  72883. frame: 6,
  72884. value: target
  72885. });
  72886. animationRotation.setKeys(animationRotationKeys);
  72887. animationRotation.setEasingFunction(this._circleEase);
  72888. this.currentVRCamera.animations.push(animationRotation);
  72889. this._postProcessMove.animations = [];
  72890. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72891. var vignetteWeightKeys = [];
  72892. vignetteWeightKeys.push({
  72893. frame: 0,
  72894. value: 0
  72895. });
  72896. vignetteWeightKeys.push({
  72897. frame: 3,
  72898. value: 4
  72899. });
  72900. vignetteWeightKeys.push({
  72901. frame: 6,
  72902. value: 0
  72903. });
  72904. animationPP.setKeys(vignetteWeightKeys);
  72905. animationPP.setEasingFunction(this._circleEase);
  72906. this._postProcessMove.animations.push(animationPP);
  72907. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72908. var vignetteStretchKeys = [];
  72909. vignetteStretchKeys.push({
  72910. frame: 0,
  72911. value: 0
  72912. });
  72913. vignetteStretchKeys.push({
  72914. frame: 3,
  72915. value: 10
  72916. });
  72917. vignetteStretchKeys.push({
  72918. frame: 6,
  72919. value: 0
  72920. });
  72921. animationPP2.setKeys(vignetteStretchKeys);
  72922. animationPP2.setEasingFunction(this._circleEase);
  72923. this._postProcessMove.animations.push(animationPP2);
  72924. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  72925. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  72926. this._webVRCamera.attachPostProcess(this._postProcessMove);
  72927. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  72928. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  72929. });
  72930. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  72931. };
  72932. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  72933. if (hit.pickedPoint) {
  72934. this._teleportationAllowed = true;
  72935. if (this._teleportationRequestInitiated) {
  72936. this._displayTeleportationTarget();
  72937. }
  72938. else {
  72939. this._hideTeleportationTarget();
  72940. }
  72941. this._haloCenter.copyFrom(hit.pickedPoint);
  72942. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  72943. var pickNormal = hit.getNormal(true, false);
  72944. if (pickNormal) {
  72945. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72946. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72947. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  72948. }
  72949. this._teleportationTarget.position.y += 0.1;
  72950. }
  72951. };
  72952. VRExperienceHelper.prototype._teleportCamera = function (location) {
  72953. var _this = this;
  72954. if (location === void 0) { location = null; }
  72955. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72956. return;
  72957. }
  72958. if (!location) {
  72959. location = this._haloCenter;
  72960. }
  72961. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  72962. // offset of the headset from the anchor.
  72963. if (this.webVRCamera.leftCamera) {
  72964. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  72965. this._workingVector.subtractInPlace(this.webVRCamera.position);
  72966. location.subtractToRef(this._workingVector, this._workingVector);
  72967. }
  72968. else {
  72969. this._workingVector.copyFrom(location);
  72970. }
  72971. // Add height to account for user's height offset
  72972. if (this.isInVRMode) {
  72973. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  72974. }
  72975. else {
  72976. this._workingVector.y += this._defaultHeight;
  72977. }
  72978. // Create animation from the camera's position to the new location
  72979. this.currentVRCamera.animations = [];
  72980. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72981. var animationCameraTeleportationKeys = [{
  72982. frame: 0,
  72983. value: this.currentVRCamera.position
  72984. },
  72985. {
  72986. frame: 11,
  72987. value: this._workingVector
  72988. }
  72989. ];
  72990. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  72991. animationCameraTeleportation.setEasingFunction(this._circleEase);
  72992. this.currentVRCamera.animations.push(animationCameraTeleportation);
  72993. this._postProcessMove.animations = [];
  72994. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72995. var vignetteWeightKeys = [];
  72996. vignetteWeightKeys.push({
  72997. frame: 0,
  72998. value: 0
  72999. });
  73000. vignetteWeightKeys.push({
  73001. frame: 5,
  73002. value: 8
  73003. });
  73004. vignetteWeightKeys.push({
  73005. frame: 11,
  73006. value: 0
  73007. });
  73008. animationPP.setKeys(vignetteWeightKeys);
  73009. this._postProcessMove.animations.push(animationPP);
  73010. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73011. var vignetteStretchKeys = [];
  73012. vignetteStretchKeys.push({
  73013. frame: 0,
  73014. value: 0
  73015. });
  73016. vignetteStretchKeys.push({
  73017. frame: 5,
  73018. value: 10
  73019. });
  73020. vignetteStretchKeys.push({
  73021. frame: 11,
  73022. value: 0
  73023. });
  73024. animationPP2.setKeys(vignetteStretchKeys);
  73025. this._postProcessMove.animations.push(animationPP2);
  73026. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73027. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73028. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73029. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  73030. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73031. });
  73032. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  73033. };
  73034. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  73035. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73036. return;
  73037. }
  73038. var ray;
  73039. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  73040. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  73041. }
  73042. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  73043. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  73044. }
  73045. else {
  73046. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  73047. }
  73048. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73049. // Moving the gazeTracker on the mesh face targetted
  73050. if (hit && hit.pickedPoint) {
  73051. if (this._displayGaze) {
  73052. var multiplier = 1;
  73053. this._gazeTracker.isVisible = true;
  73054. if (this._isActionableMesh) {
  73055. multiplier = 3;
  73056. }
  73057. this._gazeTracker.scaling.x = hit.distance * multiplier;
  73058. this._gazeTracker.scaling.y = hit.distance * multiplier;
  73059. this._gazeTracker.scaling.z = hit.distance * multiplier;
  73060. var pickNormal = hit.getNormal();
  73061. // To avoid z-fighting
  73062. var deltaFighting = 0.002;
  73063. if (pickNormal) {
  73064. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73065. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73066. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  73067. }
  73068. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  73069. if (this._gazeTracker.position.x < 0) {
  73070. this._gazeTracker.position.x += deltaFighting;
  73071. }
  73072. else {
  73073. this._gazeTracker.position.x -= deltaFighting;
  73074. }
  73075. if (this._gazeTracker.position.y < 0) {
  73076. this._gazeTracker.position.y += deltaFighting;
  73077. }
  73078. else {
  73079. this._gazeTracker.position.y -= deltaFighting;
  73080. }
  73081. if (this._gazeTracker.position.z < 0) {
  73082. this._gazeTracker.position.z += deltaFighting;
  73083. }
  73084. else {
  73085. this._gazeTracker.position.z -= deltaFighting;
  73086. }
  73087. }
  73088. // Changing the size of the laser pointer based on the distance from the targetted point
  73089. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  73090. this._rightLaserPointer.scaling.y = hit.distance;
  73091. this._rightLaserPointer.position.z = -hit.distance / 2;
  73092. }
  73093. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  73094. this._leftLaserPointer.scaling.y = hit.distance;
  73095. this._leftLaserPointer.position.z = -hit.distance / 2;
  73096. }
  73097. }
  73098. else {
  73099. this._gazeTracker.isVisible = false;
  73100. }
  73101. if (hit && hit.pickedMesh) {
  73102. this._currentHit = hit;
  73103. if (this._pointerDownOnMeshAsked) {
  73104. this._scene.simulatePointerMove(this._currentHit);
  73105. }
  73106. // The object selected is the floor, we're in a teleportation scenario
  73107. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  73108. // Moving the teleportation area to this targetted point
  73109. this._moveTeleportationSelectorTo(hit);
  73110. return;
  73111. }
  73112. // If not, we're in a selection scenario
  73113. this._hideTeleportationTarget();
  73114. this._teleportationAllowed = false;
  73115. if (hit.pickedMesh !== this._currentMeshSelected) {
  73116. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  73117. this._currentMeshSelected = hit.pickedMesh;
  73118. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  73119. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  73120. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  73121. this._isActionableMesh = true;
  73122. }
  73123. else {
  73124. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73125. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73126. this._isActionableMesh = false;
  73127. }
  73128. try {
  73129. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  73130. }
  73131. catch (err) {
  73132. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  73133. }
  73134. }
  73135. else {
  73136. this._currentMeshSelected = null;
  73137. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73138. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73139. }
  73140. }
  73141. }
  73142. else {
  73143. this._currentHit = null;
  73144. this._currentMeshSelected = null;
  73145. this._teleportationAllowed = false;
  73146. this._hideTeleportationTarget();
  73147. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73148. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73149. }
  73150. };
  73151. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  73152. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  73153. this._leftLaserPointer.material.emissiveColor = color;
  73154. }
  73155. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  73156. this._rightLaserPointer.material.emissiveColor = color;
  73157. }
  73158. };
  73159. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  73160. if (this._gazeTracker.material) {
  73161. this._gazeTracker.material.emissiveColor = color;
  73162. }
  73163. };
  73164. VRExperienceHelper.prototype.dispose = function () {
  73165. if (this.isInVRMode) {
  73166. this.exitVR();
  73167. }
  73168. if (this._passProcessMove) {
  73169. this._passProcessMove.dispose();
  73170. }
  73171. if (this._postProcessMove) {
  73172. this._postProcessMove.dispose();
  73173. }
  73174. if (this._webVRCamera) {
  73175. this._webVRCamera.dispose();
  73176. }
  73177. if (this._vrDeviceOrientationCamera) {
  73178. this._vrDeviceOrientationCamera.dispose();
  73179. }
  73180. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  73181. document.body.removeChild(this._btnVR);
  73182. }
  73183. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  73184. this._deviceOrientationCamera.dispose();
  73185. }
  73186. if (this._gazeTracker) {
  73187. this._gazeTracker.dispose();
  73188. }
  73189. if (this._teleportationTarget) {
  73190. this._teleportationTarget.dispose();
  73191. }
  73192. this._floorMeshesCollection = [];
  73193. document.removeEventListener("keydown", this._onKeyDown);
  73194. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73195. window.removeEventListener("resize", this._onResize);
  73196. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  73197. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  73198. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  73199. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  73200. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  73201. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  73202. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  73203. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73204. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  73205. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  73206. this._scene.unregisterBeforeRender(this.beforeRender);
  73207. };
  73208. VRExperienceHelper.prototype.getClassName = function () {
  73209. return "VRExperienceHelper";
  73210. };
  73211. return VRExperienceHelper;
  73212. }());
  73213. BABYLON.VRExperienceHelper = VRExperienceHelper;
  73214. })(BABYLON || (BABYLON = {}));
  73215. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  73216. // Mainly based on these 2 articles :
  73217. // 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
  73218. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  73219. var BABYLON;
  73220. (function (BABYLON) {
  73221. var JoystickAxis;
  73222. (function (JoystickAxis) {
  73223. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  73224. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  73225. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  73226. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  73227. var VirtualJoystick = /** @class */ (function () {
  73228. function VirtualJoystick(leftJoystick) {
  73229. var _this = this;
  73230. if (leftJoystick) {
  73231. this._leftJoystick = true;
  73232. }
  73233. else {
  73234. this._leftJoystick = false;
  73235. }
  73236. VirtualJoystick._globalJoystickIndex++;
  73237. // By default left & right arrow keys are moving the X
  73238. // and up & down keys are moving the Y
  73239. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73240. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73241. this.reverseLeftRight = false;
  73242. this.reverseUpDown = false;
  73243. // collections of pointers
  73244. this._touches = new BABYLON.StringDictionary();
  73245. this.deltaPosition = BABYLON.Vector3.Zero();
  73246. this._joystickSensibility = 25;
  73247. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73248. this._onResize = function (evt) {
  73249. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73250. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73251. if (VirtualJoystick.vjCanvas) {
  73252. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  73253. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  73254. }
  73255. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  73256. };
  73257. // injecting a canvas element on top of the canvas 3D game
  73258. if (!VirtualJoystick.vjCanvas) {
  73259. window.addEventListener("resize", this._onResize, false);
  73260. VirtualJoystick.vjCanvas = document.createElement("canvas");
  73261. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73262. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73263. VirtualJoystick.vjCanvas.width = window.innerWidth;
  73264. VirtualJoystick.vjCanvas.height = window.innerHeight;
  73265. VirtualJoystick.vjCanvas.style.width = "100%";
  73266. VirtualJoystick.vjCanvas.style.height = "100%";
  73267. VirtualJoystick.vjCanvas.style.position = "absolute";
  73268. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  73269. VirtualJoystick.vjCanvas.style.top = "0px";
  73270. VirtualJoystick.vjCanvas.style.left = "0px";
  73271. VirtualJoystick.vjCanvas.style.zIndex = "5";
  73272. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  73273. // Support for jQuery PEP polyfill
  73274. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  73275. var context = VirtualJoystick.vjCanvas.getContext('2d');
  73276. if (!context) {
  73277. throw new Error("Unable to create canvas for virtual joystick");
  73278. }
  73279. VirtualJoystick.vjCanvasContext = context;
  73280. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  73281. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73282. document.body.appendChild(VirtualJoystick.vjCanvas);
  73283. }
  73284. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  73285. this.pressed = false;
  73286. // default joystick color
  73287. this._joystickColor = "cyan";
  73288. this._joystickPointerID = -1;
  73289. // current joystick position
  73290. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  73291. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  73292. // origin joystick position
  73293. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  73294. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  73295. this._onPointerDownHandlerRef = function (evt) {
  73296. _this._onPointerDown(evt);
  73297. };
  73298. this._onPointerMoveHandlerRef = function (evt) {
  73299. _this._onPointerMove(evt);
  73300. };
  73301. this._onPointerUpHandlerRef = function (evt) {
  73302. _this._onPointerUp(evt);
  73303. };
  73304. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  73305. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  73306. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  73307. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  73308. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  73309. evt.preventDefault(); // Disables system menu
  73310. }, false);
  73311. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73312. }
  73313. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  73314. this._joystickSensibility = newJoystickSensibility;
  73315. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73316. };
  73317. VirtualJoystick.prototype._onPointerDown = function (e) {
  73318. var positionOnScreenCondition;
  73319. e.preventDefault();
  73320. if (this._leftJoystick === true) {
  73321. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  73322. }
  73323. else {
  73324. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  73325. }
  73326. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  73327. // First contact will be dedicated to the virtual joystick
  73328. this._joystickPointerID = e.pointerId;
  73329. this._joystickPointerStartPos.x = e.clientX;
  73330. this._joystickPointerStartPos.y = e.clientY;
  73331. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  73332. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  73333. this._deltaJoystickVector.x = 0;
  73334. this._deltaJoystickVector.y = 0;
  73335. this.pressed = true;
  73336. this._touches.add(e.pointerId.toString(), e);
  73337. }
  73338. else {
  73339. // You can only trigger the action buttons with a joystick declared
  73340. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  73341. this._action();
  73342. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  73343. }
  73344. }
  73345. };
  73346. VirtualJoystick.prototype._onPointerMove = function (e) {
  73347. // If the current pointer is the one associated to the joystick (first touch contact)
  73348. if (this._joystickPointerID == e.pointerId) {
  73349. this._joystickPointerPos.x = e.clientX;
  73350. this._joystickPointerPos.y = e.clientY;
  73351. this._deltaJoystickVector = this._joystickPointerPos.clone();
  73352. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  73353. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  73354. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  73355. switch (this._axisTargetedByLeftAndRight) {
  73356. case JoystickAxis.X:
  73357. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  73358. break;
  73359. case JoystickAxis.Y:
  73360. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  73361. break;
  73362. case JoystickAxis.Z:
  73363. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  73364. break;
  73365. }
  73366. var directionUpDown = this.reverseUpDown ? 1 : -1;
  73367. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  73368. switch (this._axisTargetedByUpAndDown) {
  73369. case JoystickAxis.X:
  73370. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  73371. break;
  73372. case JoystickAxis.Y:
  73373. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  73374. break;
  73375. case JoystickAxis.Z:
  73376. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  73377. break;
  73378. }
  73379. }
  73380. else {
  73381. var data = this._touches.get(e.pointerId.toString());
  73382. if (data) {
  73383. data.x = e.clientX;
  73384. data.y = e.clientY;
  73385. }
  73386. }
  73387. };
  73388. VirtualJoystick.prototype._onPointerUp = function (e) {
  73389. if (this._joystickPointerID == e.pointerId) {
  73390. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  73391. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  73392. this._joystickPointerID = -1;
  73393. this.pressed = false;
  73394. }
  73395. else {
  73396. var touch = this._touches.get(e.pointerId.toString());
  73397. if (touch) {
  73398. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73399. }
  73400. }
  73401. this._deltaJoystickVector.x = 0;
  73402. this._deltaJoystickVector.y = 0;
  73403. this._touches.remove(e.pointerId.toString());
  73404. };
  73405. /**
  73406. * Change the color of the virtual joystick
  73407. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  73408. */
  73409. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  73410. this._joystickColor = newColor;
  73411. };
  73412. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  73413. this._action = action;
  73414. };
  73415. // Define which axis you'd like to control for left & right
  73416. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  73417. switch (axis) {
  73418. case JoystickAxis.X:
  73419. case JoystickAxis.Y:
  73420. case JoystickAxis.Z:
  73421. this._axisTargetedByLeftAndRight = axis;
  73422. break;
  73423. default:
  73424. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73425. break;
  73426. }
  73427. };
  73428. // Define which axis you'd like to control for up & down
  73429. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  73430. switch (axis) {
  73431. case JoystickAxis.X:
  73432. case JoystickAxis.Y:
  73433. case JoystickAxis.Z:
  73434. this._axisTargetedByUpAndDown = axis;
  73435. break;
  73436. default:
  73437. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73438. break;
  73439. }
  73440. };
  73441. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  73442. var _this = this;
  73443. if (this.pressed) {
  73444. this._touches.forEach(function (key, touch) {
  73445. if (touch.pointerId === _this._joystickPointerID) {
  73446. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  73447. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  73448. VirtualJoystick.vjCanvasContext.beginPath();
  73449. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73450. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73451. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  73452. VirtualJoystick.vjCanvasContext.stroke();
  73453. VirtualJoystick.vjCanvasContext.closePath();
  73454. VirtualJoystick.vjCanvasContext.beginPath();
  73455. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73456. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73457. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  73458. VirtualJoystick.vjCanvasContext.stroke();
  73459. VirtualJoystick.vjCanvasContext.closePath();
  73460. VirtualJoystick.vjCanvasContext.beginPath();
  73461. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73462. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  73463. VirtualJoystick.vjCanvasContext.stroke();
  73464. VirtualJoystick.vjCanvasContext.closePath();
  73465. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  73466. }
  73467. else {
  73468. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73469. VirtualJoystick.vjCanvasContext.beginPath();
  73470. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  73471. VirtualJoystick.vjCanvasContext.beginPath();
  73472. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  73473. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73474. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  73475. VirtualJoystick.vjCanvasContext.stroke();
  73476. VirtualJoystick.vjCanvasContext.closePath();
  73477. touch.prevX = touch.x;
  73478. touch.prevY = touch.y;
  73479. }
  73480. ;
  73481. });
  73482. }
  73483. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73484. };
  73485. VirtualJoystick.prototype.releaseCanvas = function () {
  73486. if (VirtualJoystick.vjCanvas) {
  73487. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  73488. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  73489. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  73490. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  73491. window.removeEventListener("resize", this._onResize);
  73492. document.body.removeChild(VirtualJoystick.vjCanvas);
  73493. VirtualJoystick.vjCanvas = null;
  73494. }
  73495. };
  73496. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  73497. VirtualJoystick._globalJoystickIndex = 0;
  73498. return VirtualJoystick;
  73499. }());
  73500. BABYLON.VirtualJoystick = VirtualJoystick;
  73501. })(BABYLON || (BABYLON = {}));
  73502. //# sourceMappingURL=babylon.virtualJoystick.js.map
  73503. var BABYLON;
  73504. (function (BABYLON) {
  73505. // We're mainly based on the logic defined into the FreeCamera code
  73506. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  73507. __extends(VirtualJoysticksCamera, _super);
  73508. function VirtualJoysticksCamera(name, position, scene) {
  73509. var _this = _super.call(this, name, position, scene) || this;
  73510. _this.inputs.addVirtualJoystick();
  73511. return _this;
  73512. }
  73513. VirtualJoysticksCamera.prototype.getClassName = function () {
  73514. return "VirtualJoysticksCamera";
  73515. };
  73516. return VirtualJoysticksCamera;
  73517. }(BABYLON.FreeCamera));
  73518. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  73519. })(BABYLON || (BABYLON = {}));
  73520. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  73521. var BABYLON;
  73522. (function (BABYLON) {
  73523. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  73524. function FreeCameraVirtualJoystickInput() {
  73525. }
  73526. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  73527. return this._leftjoystick;
  73528. };
  73529. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  73530. return this._rightjoystick;
  73531. };
  73532. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  73533. if (this._leftjoystick) {
  73534. var camera = this.camera;
  73535. var speed = camera._computeLocalCameraSpeed() * 50;
  73536. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  73537. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  73538. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  73539. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  73540. if (!this._leftjoystick.pressed) {
  73541. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  73542. }
  73543. if (!this._rightjoystick.pressed) {
  73544. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  73545. }
  73546. }
  73547. };
  73548. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  73549. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  73550. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  73551. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  73552. this._leftjoystick.setJoystickSensibility(0.15);
  73553. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  73554. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  73555. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  73556. this._rightjoystick.reverseUpDown = true;
  73557. this._rightjoystick.setJoystickSensibility(0.05);
  73558. this._rightjoystick.setJoystickColor("yellow");
  73559. };
  73560. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  73561. this._leftjoystick.releaseCanvas();
  73562. this._rightjoystick.releaseCanvas();
  73563. };
  73564. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  73565. return "FreeCameraVirtualJoystickInput";
  73566. };
  73567. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  73568. return "virtualJoystick";
  73569. };
  73570. return FreeCameraVirtualJoystickInput;
  73571. }());
  73572. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  73573. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  73574. })(BABYLON || (BABYLON = {}));
  73575. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  73576. var BABYLON;
  73577. (function (BABYLON) {
  73578. var SimplificationSettings = /** @class */ (function () {
  73579. function SimplificationSettings(quality, distance, optimizeMesh) {
  73580. this.quality = quality;
  73581. this.distance = distance;
  73582. this.optimizeMesh = optimizeMesh;
  73583. }
  73584. return SimplificationSettings;
  73585. }());
  73586. BABYLON.SimplificationSettings = SimplificationSettings;
  73587. var SimplificationQueue = /** @class */ (function () {
  73588. function SimplificationQueue() {
  73589. this.running = false;
  73590. this._simplificationArray = [];
  73591. }
  73592. SimplificationQueue.prototype.addTask = function (task) {
  73593. this._simplificationArray.push(task);
  73594. };
  73595. SimplificationQueue.prototype.executeNext = function () {
  73596. var task = this._simplificationArray.pop();
  73597. if (task) {
  73598. this.running = true;
  73599. this.runSimplification(task);
  73600. }
  73601. else {
  73602. this.running = false;
  73603. }
  73604. };
  73605. SimplificationQueue.prototype.runSimplification = function (task) {
  73606. var _this = this;
  73607. if (task.parallelProcessing) {
  73608. //parallel simplifier
  73609. task.settings.forEach(function (setting) {
  73610. var simplifier = _this.getSimplifier(task);
  73611. simplifier.simplify(setting, function (newMesh) {
  73612. task.mesh.addLODLevel(setting.distance, newMesh);
  73613. newMesh.isVisible = true;
  73614. //check if it is the last
  73615. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  73616. //all done, run the success callback.
  73617. task.successCallback();
  73618. }
  73619. _this.executeNext();
  73620. });
  73621. });
  73622. }
  73623. else {
  73624. //single simplifier.
  73625. var simplifier = this.getSimplifier(task);
  73626. var runDecimation = function (setting, callback) {
  73627. simplifier.simplify(setting, function (newMesh) {
  73628. task.mesh.addLODLevel(setting.distance, newMesh);
  73629. newMesh.isVisible = true;
  73630. //run the next quality level
  73631. callback();
  73632. });
  73633. };
  73634. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  73635. runDecimation(task.settings[loop.index], function () {
  73636. loop.executeNext();
  73637. });
  73638. }, function () {
  73639. //execution ended, run the success callback.
  73640. if (task.successCallback) {
  73641. task.successCallback();
  73642. }
  73643. _this.executeNext();
  73644. });
  73645. }
  73646. };
  73647. SimplificationQueue.prototype.getSimplifier = function (task) {
  73648. switch (task.simplificationType) {
  73649. case SimplificationType.QUADRATIC:
  73650. default:
  73651. return new QuadraticErrorSimplification(task.mesh);
  73652. }
  73653. };
  73654. return SimplificationQueue;
  73655. }());
  73656. BABYLON.SimplificationQueue = SimplificationQueue;
  73657. /**
  73658. * The implemented types of simplification.
  73659. * At the moment only Quadratic Error Decimation is implemented.
  73660. */
  73661. var SimplificationType;
  73662. (function (SimplificationType) {
  73663. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  73664. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  73665. var DecimationTriangle = /** @class */ (function () {
  73666. function DecimationTriangle(vertices) {
  73667. this.vertices = vertices;
  73668. this.error = new Array(4);
  73669. this.deleted = false;
  73670. this.isDirty = false;
  73671. this.deletePending = false;
  73672. this.borderFactor = 0;
  73673. }
  73674. return DecimationTriangle;
  73675. }());
  73676. BABYLON.DecimationTriangle = DecimationTriangle;
  73677. var DecimationVertex = /** @class */ (function () {
  73678. function DecimationVertex(position, id) {
  73679. this.position = position;
  73680. this.id = id;
  73681. this.isBorder = true;
  73682. this.q = new QuadraticMatrix();
  73683. this.triangleCount = 0;
  73684. this.triangleStart = 0;
  73685. this.originalOffsets = [];
  73686. }
  73687. DecimationVertex.prototype.updatePosition = function (newPosition) {
  73688. this.position.copyFrom(newPosition);
  73689. };
  73690. return DecimationVertex;
  73691. }());
  73692. BABYLON.DecimationVertex = DecimationVertex;
  73693. var QuadraticMatrix = /** @class */ (function () {
  73694. function QuadraticMatrix(data) {
  73695. this.data = new Array(10);
  73696. for (var i = 0; i < 10; ++i) {
  73697. if (data && data[i]) {
  73698. this.data[i] = data[i];
  73699. }
  73700. else {
  73701. this.data[i] = 0;
  73702. }
  73703. }
  73704. }
  73705. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  73706. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  73707. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  73708. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  73709. return det;
  73710. };
  73711. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  73712. for (var i = 0; i < 10; ++i) {
  73713. this.data[i] += matrix.data[i];
  73714. }
  73715. };
  73716. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  73717. for (var i = 0; i < 10; ++i) {
  73718. this.data[i] += data[i];
  73719. }
  73720. };
  73721. QuadraticMatrix.prototype.add = function (matrix) {
  73722. var m = new QuadraticMatrix();
  73723. for (var i = 0; i < 10; ++i) {
  73724. m.data[i] = this.data[i] + matrix.data[i];
  73725. }
  73726. return m;
  73727. };
  73728. QuadraticMatrix.FromData = function (a, b, c, d) {
  73729. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  73730. };
  73731. //returning an array to avoid garbage collection
  73732. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  73733. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  73734. };
  73735. return QuadraticMatrix;
  73736. }());
  73737. BABYLON.QuadraticMatrix = QuadraticMatrix;
  73738. var Reference = /** @class */ (function () {
  73739. function Reference(vertexId, triangleId) {
  73740. this.vertexId = vertexId;
  73741. this.triangleId = triangleId;
  73742. }
  73743. return Reference;
  73744. }());
  73745. BABYLON.Reference = Reference;
  73746. /**
  73747. * An implementation of the Quadratic Error simplification algorithm.
  73748. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  73749. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  73750. * @author RaananW
  73751. */
  73752. var QuadraticErrorSimplification = /** @class */ (function () {
  73753. function QuadraticErrorSimplification(_mesh) {
  73754. this._mesh = _mesh;
  73755. this.syncIterations = 5000;
  73756. this.aggressiveness = 7;
  73757. this.decimationIterations = 100;
  73758. this.boundingBoxEpsilon = BABYLON.Epsilon;
  73759. }
  73760. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  73761. var _this = this;
  73762. this.initDecimatedMesh();
  73763. //iterating through the submeshes array, one after the other.
  73764. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  73765. _this.initWithMesh(loop.index, function () {
  73766. _this.runDecimation(settings, loop.index, function () {
  73767. loop.executeNext();
  73768. });
  73769. }, settings.optimizeMesh);
  73770. }, function () {
  73771. setTimeout(function () {
  73772. successCallback(_this._reconstructedMesh);
  73773. }, 0);
  73774. });
  73775. };
  73776. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  73777. var _this = this;
  73778. var targetCount = ~~(this.triangles.length * settings.quality);
  73779. var deletedTriangles = 0;
  73780. var triangleCount = this.triangles.length;
  73781. var iterationFunction = function (iteration, callback) {
  73782. setTimeout(function () {
  73783. if (iteration % 5 === 0) {
  73784. _this.updateMesh(iteration === 0);
  73785. }
  73786. for (var i = 0; i < _this.triangles.length; ++i) {
  73787. _this.triangles[i].isDirty = false;
  73788. }
  73789. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  73790. var trianglesIterator = function (i) {
  73791. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  73792. var t = _this.triangles[tIdx];
  73793. if (!t)
  73794. return;
  73795. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  73796. return;
  73797. }
  73798. for (var j = 0; j < 3; ++j) {
  73799. if (t.error[j] < threshold) {
  73800. var deleted0 = [];
  73801. var deleted1 = [];
  73802. var v0 = t.vertices[j];
  73803. var v1 = t.vertices[(j + 1) % 3];
  73804. if (v0.isBorder || v1.isBorder)
  73805. continue;
  73806. var p = BABYLON.Vector3.Zero();
  73807. var n = BABYLON.Vector3.Zero();
  73808. var uv = BABYLON.Vector2.Zero();
  73809. var color = new BABYLON.Color4(0, 0, 0, 1);
  73810. _this.calculateError(v0, v1, p, n, uv, color);
  73811. var delTr = new Array();
  73812. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  73813. continue;
  73814. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  73815. continue;
  73816. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  73817. continue;
  73818. var uniqueArray = new Array();
  73819. delTr.forEach(function (deletedT) {
  73820. if (uniqueArray.indexOf(deletedT) === -1) {
  73821. deletedT.deletePending = true;
  73822. uniqueArray.push(deletedT);
  73823. }
  73824. });
  73825. if (uniqueArray.length % 2 !== 0) {
  73826. continue;
  73827. }
  73828. v0.q = v1.q.add(v0.q);
  73829. v0.updatePosition(p);
  73830. var tStart = _this.references.length;
  73831. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  73832. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  73833. var tCount = _this.references.length - tStart;
  73834. if (tCount <= v0.triangleCount) {
  73835. if (tCount) {
  73836. for (var c = 0; c < tCount; c++) {
  73837. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  73838. }
  73839. }
  73840. }
  73841. else {
  73842. v0.triangleStart = tStart;
  73843. }
  73844. v0.triangleCount = tCount;
  73845. break;
  73846. }
  73847. }
  73848. };
  73849. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  73850. }, 0);
  73851. };
  73852. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  73853. if (triangleCount - deletedTriangles <= targetCount)
  73854. loop.breakLoop();
  73855. else {
  73856. iterationFunction(loop.index, function () {
  73857. loop.executeNext();
  73858. });
  73859. }
  73860. }, function () {
  73861. setTimeout(function () {
  73862. //reconstruct this part of the mesh
  73863. _this.reconstructMesh(submeshIndex);
  73864. successCallback();
  73865. }, 0);
  73866. });
  73867. };
  73868. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  73869. var _this = this;
  73870. this.vertices = [];
  73871. this.triangles = [];
  73872. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73873. var indices = this._mesh.getIndices();
  73874. var submesh = this._mesh.subMeshes[submeshIndex];
  73875. var findInVertices = function (positionToSearch) {
  73876. if (optimizeMesh) {
  73877. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  73878. if (_this.vertices[ii].position.equals(positionToSearch)) {
  73879. return _this.vertices[ii];
  73880. }
  73881. }
  73882. }
  73883. return null;
  73884. };
  73885. var vertexReferences = [];
  73886. var vertexInit = function (i) {
  73887. if (!positionData) {
  73888. return;
  73889. }
  73890. var offset = i + submesh.verticesStart;
  73891. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  73892. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  73893. vertex.originalOffsets.push(offset);
  73894. if (vertex.id === _this.vertices.length) {
  73895. _this.vertices.push(vertex);
  73896. }
  73897. vertexReferences.push(vertex.id);
  73898. };
  73899. //var totalVertices = mesh.getTotalVertices();
  73900. var totalVertices = submesh.verticesCount;
  73901. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  73902. var indicesInit = function (i) {
  73903. if (!indices) {
  73904. return;
  73905. }
  73906. var offset = (submesh.indexStart / 3) + i;
  73907. var pos = (offset * 3);
  73908. var i0 = indices[pos + 0];
  73909. var i1 = indices[pos + 1];
  73910. var i2 = indices[pos + 2];
  73911. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  73912. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  73913. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  73914. var triangle = new DecimationTriangle([v0, v1, v2]);
  73915. triangle.originalOffset = pos;
  73916. _this.triangles.push(triangle);
  73917. };
  73918. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  73919. _this.init(callback);
  73920. });
  73921. });
  73922. };
  73923. QuadraticErrorSimplification.prototype.init = function (callback) {
  73924. var _this = this;
  73925. var triangleInit1 = function (i) {
  73926. var t = _this.triangles[i];
  73927. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  73928. for (var j = 0; j < 3; j++) {
  73929. 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))));
  73930. }
  73931. };
  73932. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  73933. var triangleInit2 = function (i) {
  73934. var t = _this.triangles[i];
  73935. for (var j = 0; j < 3; ++j) {
  73936. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  73937. }
  73938. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73939. };
  73940. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  73941. callback();
  73942. });
  73943. });
  73944. };
  73945. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  73946. var newTriangles = [];
  73947. var i;
  73948. for (i = 0; i < this.vertices.length; ++i) {
  73949. this.vertices[i].triangleCount = 0;
  73950. }
  73951. var t;
  73952. var j;
  73953. for (i = 0; i < this.triangles.length; ++i) {
  73954. if (!this.triangles[i].deleted) {
  73955. t = this.triangles[i];
  73956. for (j = 0; j < 3; ++j) {
  73957. t.vertices[j].triangleCount = 1;
  73958. }
  73959. newTriangles.push(t);
  73960. }
  73961. }
  73962. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  73963. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  73964. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  73965. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  73966. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  73967. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73968. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  73969. var vertexCount = 0;
  73970. for (i = 0; i < this.vertices.length; ++i) {
  73971. var vertex = this.vertices[i];
  73972. vertex.id = vertexCount;
  73973. if (vertex.triangleCount) {
  73974. vertex.originalOffsets.forEach(function (originalOffset) {
  73975. if (!normalData) {
  73976. return;
  73977. }
  73978. newPositionData.push(vertex.position.x);
  73979. newPositionData.push(vertex.position.y);
  73980. newPositionData.push(vertex.position.z);
  73981. newNormalData.push(normalData[originalOffset * 3]);
  73982. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  73983. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  73984. if (uvs && uvs.length) {
  73985. newUVsData.push(uvs[(originalOffset * 2)]);
  73986. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  73987. }
  73988. else if (colorsData && colorsData.length) {
  73989. newColorsData.push(colorsData[(originalOffset * 4)]);
  73990. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  73991. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  73992. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  73993. }
  73994. ++vertexCount;
  73995. });
  73996. }
  73997. }
  73998. var startingIndex = this._reconstructedMesh.getTotalIndices();
  73999. var startingVertex = this._reconstructedMesh.getTotalVertices();
  74000. var submeshesArray = this._reconstructedMesh.subMeshes;
  74001. this._reconstructedMesh.subMeshes = [];
  74002. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  74003. var originalIndices = this._mesh.getIndices();
  74004. for (i = 0; i < newTriangles.length; ++i) {
  74005. t = newTriangles[i]; //now get the new referencing point for each vertex
  74006. [0, 1, 2].forEach(function (idx) {
  74007. var id = originalIndices[t.originalOffset + idx];
  74008. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  74009. if (offset < 0)
  74010. offset = 0;
  74011. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  74012. });
  74013. }
  74014. //overwriting the old vertex buffers and indices.
  74015. this._reconstructedMesh.setIndices(newIndicesArray);
  74016. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  74017. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  74018. if (newUVsData.length > 0)
  74019. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  74020. if (newColorsData.length > 0)
  74021. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  74022. //create submesh
  74023. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  74024. if (submeshIndex > 0) {
  74025. this._reconstructedMesh.subMeshes = [];
  74026. submeshesArray.forEach(function (submesh) {
  74027. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  74028. });
  74029. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  74030. }
  74031. };
  74032. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  74033. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  74034. this._reconstructedMesh.material = this._mesh.material;
  74035. this._reconstructedMesh.parent = this._mesh.parent;
  74036. this._reconstructedMesh.isVisible = false;
  74037. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  74038. };
  74039. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  74040. for (var i = 0; i < vertex1.triangleCount; ++i) {
  74041. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  74042. if (t.deleted)
  74043. continue;
  74044. var s = this.references[vertex1.triangleStart + i].vertexId;
  74045. var v1 = t.vertices[(s + 1) % 3];
  74046. var v2 = t.vertices[(s + 2) % 3];
  74047. if ((v1 === vertex2 || v2 === vertex2)) {
  74048. deletedArray[i] = true;
  74049. delTr.push(t);
  74050. continue;
  74051. }
  74052. var d1 = v1.position.subtract(point);
  74053. d1 = d1.normalize();
  74054. var d2 = v2.position.subtract(point);
  74055. d2 = d2.normalize();
  74056. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  74057. return true;
  74058. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  74059. deletedArray[i] = false;
  74060. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  74061. return true;
  74062. }
  74063. return false;
  74064. };
  74065. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  74066. var newDeleted = deletedTriangles;
  74067. for (var i = 0; i < vertex.triangleCount; ++i) {
  74068. var ref = this.references[vertex.triangleStart + i];
  74069. var t = this.triangles[ref.triangleId];
  74070. if (t.deleted)
  74071. continue;
  74072. if (deletedArray[i] && t.deletePending) {
  74073. t.deleted = true;
  74074. newDeleted++;
  74075. continue;
  74076. }
  74077. t.vertices[ref.vertexId] = origVertex;
  74078. t.isDirty = true;
  74079. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  74080. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  74081. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  74082. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74083. this.references.push(ref);
  74084. }
  74085. return newDeleted;
  74086. };
  74087. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  74088. for (var i = 0; i < this.vertices.length; ++i) {
  74089. var vCount = [];
  74090. var vId = [];
  74091. var v = this.vertices[i];
  74092. var j;
  74093. for (j = 0; j < v.triangleCount; ++j) {
  74094. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  74095. for (var ii = 0; ii < 3; ii++) {
  74096. var ofs = 0;
  74097. var vv = triangle.vertices[ii];
  74098. while (ofs < vCount.length) {
  74099. if (vId[ofs] === vv.id)
  74100. break;
  74101. ++ofs;
  74102. }
  74103. if (ofs === vCount.length) {
  74104. vCount.push(1);
  74105. vId.push(vv.id);
  74106. }
  74107. else {
  74108. vCount[ofs]++;
  74109. }
  74110. }
  74111. }
  74112. for (j = 0; j < vCount.length; ++j) {
  74113. if (vCount[j] === 1) {
  74114. this.vertices[vId[j]].isBorder = true;
  74115. }
  74116. else {
  74117. this.vertices[vId[j]].isBorder = false;
  74118. }
  74119. }
  74120. }
  74121. };
  74122. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  74123. if (identifyBorders === void 0) { identifyBorders = false; }
  74124. var i;
  74125. if (!identifyBorders) {
  74126. var newTrianglesVector = [];
  74127. for (i = 0; i < this.triangles.length; ++i) {
  74128. if (!this.triangles[i].deleted) {
  74129. newTrianglesVector.push(this.triangles[i]);
  74130. }
  74131. }
  74132. this.triangles = newTrianglesVector;
  74133. }
  74134. for (i = 0; i < this.vertices.length; ++i) {
  74135. this.vertices[i].triangleCount = 0;
  74136. this.vertices[i].triangleStart = 0;
  74137. }
  74138. var t;
  74139. var j;
  74140. var v;
  74141. for (i = 0; i < this.triangles.length; ++i) {
  74142. t = this.triangles[i];
  74143. for (j = 0; j < 3; ++j) {
  74144. v = t.vertices[j];
  74145. v.triangleCount++;
  74146. }
  74147. }
  74148. var tStart = 0;
  74149. for (i = 0; i < this.vertices.length; ++i) {
  74150. this.vertices[i].triangleStart = tStart;
  74151. tStart += this.vertices[i].triangleCount;
  74152. this.vertices[i].triangleCount = 0;
  74153. }
  74154. var newReferences = new Array(this.triangles.length * 3);
  74155. for (i = 0; i < this.triangles.length; ++i) {
  74156. t = this.triangles[i];
  74157. for (j = 0; j < 3; ++j) {
  74158. v = t.vertices[j];
  74159. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  74160. v.triangleCount++;
  74161. }
  74162. }
  74163. this.references = newReferences;
  74164. if (identifyBorders) {
  74165. this.identifyBorder();
  74166. }
  74167. };
  74168. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  74169. var x = point.x;
  74170. var y = point.y;
  74171. var z = point.z;
  74172. 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
  74173. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  74174. };
  74175. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  74176. var q = vertex1.q.add(vertex2.q);
  74177. var border = vertex1.isBorder && vertex2.isBorder;
  74178. var error = 0;
  74179. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  74180. if (qDet !== 0 && !border) {
  74181. if (!pointResult) {
  74182. pointResult = BABYLON.Vector3.Zero();
  74183. }
  74184. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  74185. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  74186. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  74187. error = this.vertexError(q, pointResult);
  74188. }
  74189. else {
  74190. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  74191. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  74192. var error1 = this.vertexError(q, vertex1.position);
  74193. var error2 = this.vertexError(q, vertex2.position);
  74194. var error3 = this.vertexError(q, p3);
  74195. error = Math.min(error1, error2, error3);
  74196. if (error === error1) {
  74197. if (pointResult) {
  74198. pointResult.copyFrom(vertex1.position);
  74199. }
  74200. }
  74201. else if (error === error2) {
  74202. if (pointResult) {
  74203. pointResult.copyFrom(vertex2.position);
  74204. }
  74205. }
  74206. else {
  74207. if (pointResult) {
  74208. pointResult.copyFrom(p3);
  74209. }
  74210. }
  74211. }
  74212. return error;
  74213. };
  74214. return QuadraticErrorSimplification;
  74215. }());
  74216. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  74217. })(BABYLON || (BABYLON = {}));
  74218. //# sourceMappingURL=babylon.meshSimplification.js.map
  74219. var BABYLON;
  74220. (function (BABYLON) {
  74221. var Internals;
  74222. (function (Internals) {
  74223. var MeshLODLevel = /** @class */ (function () {
  74224. function MeshLODLevel(distance, mesh) {
  74225. this.distance = distance;
  74226. this.mesh = mesh;
  74227. }
  74228. return MeshLODLevel;
  74229. }());
  74230. Internals.MeshLODLevel = MeshLODLevel;
  74231. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  74232. })(BABYLON || (BABYLON = {}));
  74233. //# sourceMappingURL=babylon.meshLODLevel.js.map
  74234. var BABYLON;
  74235. (function (BABYLON) {
  74236. // Standard optimizations
  74237. var SceneOptimization = /** @class */ (function () {
  74238. function SceneOptimization(priority) {
  74239. if (priority === void 0) { priority = 0; }
  74240. this.priority = priority;
  74241. this.apply = function (scene) {
  74242. return true; // Return true if everything that can be done was applied
  74243. };
  74244. }
  74245. return SceneOptimization;
  74246. }());
  74247. BABYLON.SceneOptimization = SceneOptimization;
  74248. var TextureOptimization = /** @class */ (function (_super) {
  74249. __extends(TextureOptimization, _super);
  74250. function TextureOptimization(priority, maximumSize) {
  74251. if (priority === void 0) { priority = 0; }
  74252. if (maximumSize === void 0) { maximumSize = 1024; }
  74253. var _this = _super.call(this, priority) || this;
  74254. _this.priority = priority;
  74255. _this.maximumSize = maximumSize;
  74256. _this.apply = function (scene) {
  74257. var allDone = true;
  74258. for (var index = 0; index < scene.textures.length; index++) {
  74259. var texture = scene.textures[index];
  74260. if (!texture.canRescale || texture.getContext) {
  74261. continue;
  74262. }
  74263. var currentSize = texture.getSize();
  74264. var maxDimension = Math.max(currentSize.width, currentSize.height);
  74265. if (maxDimension > _this.maximumSize) {
  74266. texture.scale(0.5);
  74267. allDone = false;
  74268. }
  74269. }
  74270. return allDone;
  74271. };
  74272. return _this;
  74273. }
  74274. return TextureOptimization;
  74275. }(SceneOptimization));
  74276. BABYLON.TextureOptimization = TextureOptimization;
  74277. var HardwareScalingOptimization = /** @class */ (function (_super) {
  74278. __extends(HardwareScalingOptimization, _super);
  74279. function HardwareScalingOptimization(priority, maximumScale) {
  74280. if (priority === void 0) { priority = 0; }
  74281. if (maximumScale === void 0) { maximumScale = 2; }
  74282. var _this = _super.call(this, priority) || this;
  74283. _this.priority = priority;
  74284. _this.maximumScale = maximumScale;
  74285. _this._currentScale = 1;
  74286. _this.apply = function (scene) {
  74287. _this._currentScale++;
  74288. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  74289. return _this._currentScale >= _this.maximumScale;
  74290. };
  74291. return _this;
  74292. }
  74293. return HardwareScalingOptimization;
  74294. }(SceneOptimization));
  74295. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  74296. var ShadowsOptimization = /** @class */ (function (_super) {
  74297. __extends(ShadowsOptimization, _super);
  74298. function ShadowsOptimization() {
  74299. var _this = _super !== null && _super.apply(this, arguments) || this;
  74300. _this.apply = function (scene) {
  74301. scene.shadowsEnabled = false;
  74302. return true;
  74303. };
  74304. return _this;
  74305. }
  74306. return ShadowsOptimization;
  74307. }(SceneOptimization));
  74308. BABYLON.ShadowsOptimization = ShadowsOptimization;
  74309. var PostProcessesOptimization = /** @class */ (function (_super) {
  74310. __extends(PostProcessesOptimization, _super);
  74311. function PostProcessesOptimization() {
  74312. var _this = _super !== null && _super.apply(this, arguments) || this;
  74313. _this.apply = function (scene) {
  74314. scene.postProcessesEnabled = false;
  74315. return true;
  74316. };
  74317. return _this;
  74318. }
  74319. return PostProcessesOptimization;
  74320. }(SceneOptimization));
  74321. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  74322. var LensFlaresOptimization = /** @class */ (function (_super) {
  74323. __extends(LensFlaresOptimization, _super);
  74324. function LensFlaresOptimization() {
  74325. var _this = _super !== null && _super.apply(this, arguments) || this;
  74326. _this.apply = function (scene) {
  74327. scene.lensFlaresEnabled = false;
  74328. return true;
  74329. };
  74330. return _this;
  74331. }
  74332. return LensFlaresOptimization;
  74333. }(SceneOptimization));
  74334. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  74335. var ParticlesOptimization = /** @class */ (function (_super) {
  74336. __extends(ParticlesOptimization, _super);
  74337. function ParticlesOptimization() {
  74338. var _this = _super !== null && _super.apply(this, arguments) || this;
  74339. _this.apply = function (scene) {
  74340. scene.particlesEnabled = false;
  74341. return true;
  74342. };
  74343. return _this;
  74344. }
  74345. return ParticlesOptimization;
  74346. }(SceneOptimization));
  74347. BABYLON.ParticlesOptimization = ParticlesOptimization;
  74348. var RenderTargetsOptimization = /** @class */ (function (_super) {
  74349. __extends(RenderTargetsOptimization, _super);
  74350. function RenderTargetsOptimization() {
  74351. var _this = _super !== null && _super.apply(this, arguments) || this;
  74352. _this.apply = function (scene) {
  74353. scene.renderTargetsEnabled = false;
  74354. return true;
  74355. };
  74356. return _this;
  74357. }
  74358. return RenderTargetsOptimization;
  74359. }(SceneOptimization));
  74360. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  74361. var MergeMeshesOptimization = /** @class */ (function (_super) {
  74362. __extends(MergeMeshesOptimization, _super);
  74363. function MergeMeshesOptimization() {
  74364. var _this = _super !== null && _super.apply(this, arguments) || this;
  74365. _this._canBeMerged = function (abstractMesh) {
  74366. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  74367. return false;
  74368. }
  74369. var mesh = abstractMesh;
  74370. if (!mesh.isVisible || !mesh.isEnabled()) {
  74371. return false;
  74372. }
  74373. if (mesh.instances.length > 0) {
  74374. return false;
  74375. }
  74376. if (mesh.skeleton || mesh.hasLODLevels) {
  74377. return false;
  74378. }
  74379. if (mesh.parent) {
  74380. return false;
  74381. }
  74382. return true;
  74383. };
  74384. _this.apply = function (scene, updateSelectionTree) {
  74385. var globalPool = scene.meshes.slice(0);
  74386. var globalLength = globalPool.length;
  74387. for (var index = 0; index < globalLength; index++) {
  74388. var currentPool = new Array();
  74389. var current = globalPool[index];
  74390. // Checks
  74391. if (!_this._canBeMerged(current)) {
  74392. continue;
  74393. }
  74394. currentPool.push(current);
  74395. // Find compatible meshes
  74396. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  74397. var otherMesh = globalPool[subIndex];
  74398. if (!_this._canBeMerged(otherMesh)) {
  74399. continue;
  74400. }
  74401. if (otherMesh.material !== current.material) {
  74402. continue;
  74403. }
  74404. if (otherMesh.checkCollisions !== current.checkCollisions) {
  74405. continue;
  74406. }
  74407. currentPool.push(otherMesh);
  74408. globalLength--;
  74409. globalPool.splice(subIndex, 1);
  74410. subIndex--;
  74411. }
  74412. if (currentPool.length < 2) {
  74413. continue;
  74414. }
  74415. // Merge meshes
  74416. BABYLON.Mesh.MergeMeshes(currentPool);
  74417. }
  74418. if (updateSelectionTree != undefined) {
  74419. if (updateSelectionTree) {
  74420. scene.createOrUpdateSelectionOctree();
  74421. }
  74422. }
  74423. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  74424. scene.createOrUpdateSelectionOctree();
  74425. }
  74426. return true;
  74427. };
  74428. return _this;
  74429. }
  74430. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  74431. get: function () {
  74432. return MergeMeshesOptimization._UpdateSelectionTree;
  74433. },
  74434. set: function (value) {
  74435. MergeMeshesOptimization._UpdateSelectionTree = value;
  74436. },
  74437. enumerable: true,
  74438. configurable: true
  74439. });
  74440. MergeMeshesOptimization._UpdateSelectionTree = false;
  74441. return MergeMeshesOptimization;
  74442. }(SceneOptimization));
  74443. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  74444. // Options
  74445. var SceneOptimizerOptions = /** @class */ (function () {
  74446. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  74447. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  74448. if (trackerDuration === void 0) { trackerDuration = 2000; }
  74449. this.targetFrameRate = targetFrameRate;
  74450. this.trackerDuration = trackerDuration;
  74451. this.optimizations = new Array();
  74452. }
  74453. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  74454. var result = new SceneOptimizerOptions(targetFrameRate);
  74455. var priority = 0;
  74456. result.optimizations.push(new MergeMeshesOptimization(priority));
  74457. result.optimizations.push(new ShadowsOptimization(priority));
  74458. result.optimizations.push(new LensFlaresOptimization(priority));
  74459. // Next priority
  74460. priority++;
  74461. result.optimizations.push(new PostProcessesOptimization(priority));
  74462. result.optimizations.push(new ParticlesOptimization(priority));
  74463. // Next priority
  74464. priority++;
  74465. result.optimizations.push(new TextureOptimization(priority, 1024));
  74466. return result;
  74467. };
  74468. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  74469. var result = new SceneOptimizerOptions(targetFrameRate);
  74470. var priority = 0;
  74471. result.optimizations.push(new MergeMeshesOptimization(priority));
  74472. result.optimizations.push(new ShadowsOptimization(priority));
  74473. result.optimizations.push(new LensFlaresOptimization(priority));
  74474. // Next priority
  74475. priority++;
  74476. result.optimizations.push(new PostProcessesOptimization(priority));
  74477. result.optimizations.push(new ParticlesOptimization(priority));
  74478. // Next priority
  74479. priority++;
  74480. result.optimizations.push(new TextureOptimization(priority, 512));
  74481. // Next priority
  74482. priority++;
  74483. result.optimizations.push(new RenderTargetsOptimization(priority));
  74484. // Next priority
  74485. priority++;
  74486. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  74487. return result;
  74488. };
  74489. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  74490. var result = new SceneOptimizerOptions(targetFrameRate);
  74491. var priority = 0;
  74492. result.optimizations.push(new MergeMeshesOptimization(priority));
  74493. result.optimizations.push(new ShadowsOptimization(priority));
  74494. result.optimizations.push(new LensFlaresOptimization(priority));
  74495. // Next priority
  74496. priority++;
  74497. result.optimizations.push(new PostProcessesOptimization(priority));
  74498. result.optimizations.push(new ParticlesOptimization(priority));
  74499. // Next priority
  74500. priority++;
  74501. result.optimizations.push(new TextureOptimization(priority, 256));
  74502. // Next priority
  74503. priority++;
  74504. result.optimizations.push(new RenderTargetsOptimization(priority));
  74505. // Next priority
  74506. priority++;
  74507. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  74508. return result;
  74509. };
  74510. return SceneOptimizerOptions;
  74511. }());
  74512. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  74513. // Scene optimizer tool
  74514. var SceneOptimizer = /** @class */ (function () {
  74515. function SceneOptimizer() {
  74516. }
  74517. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  74518. // TODO: add an epsilon
  74519. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  74520. if (onSuccess) {
  74521. onSuccess();
  74522. }
  74523. return;
  74524. }
  74525. // Apply current level of optimizations
  74526. var allDone = true;
  74527. var noOptimizationApplied = true;
  74528. for (var index = 0; index < options.optimizations.length; index++) {
  74529. var optimization = options.optimizations[index];
  74530. if (optimization.priority === currentPriorityLevel) {
  74531. noOptimizationApplied = false;
  74532. allDone = allDone && optimization.apply(scene);
  74533. }
  74534. }
  74535. // If no optimization was applied, this is a failure :(
  74536. if (noOptimizationApplied) {
  74537. if (onFailure) {
  74538. onFailure();
  74539. }
  74540. return;
  74541. }
  74542. // If all optimizations were done, move to next level
  74543. if (allDone) {
  74544. currentPriorityLevel++;
  74545. }
  74546. // Let's the system running for a specific amount of time before checking FPS
  74547. scene.executeWhenReady(function () {
  74548. setTimeout(function () {
  74549. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  74550. }, options.trackerDuration);
  74551. });
  74552. };
  74553. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  74554. if (!options) {
  74555. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  74556. }
  74557. // Let's the system running for a specific amount of time before checking FPS
  74558. scene.executeWhenReady(function () {
  74559. setTimeout(function () {
  74560. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  74561. }, options.trackerDuration);
  74562. });
  74563. };
  74564. return SceneOptimizer;
  74565. }());
  74566. BABYLON.SceneOptimizer = SceneOptimizer;
  74567. })(BABYLON || (BABYLON = {}));
  74568. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  74569. var BABYLON;
  74570. (function (BABYLON) {
  74571. var OutlineRenderer = /** @class */ (function () {
  74572. function OutlineRenderer(scene) {
  74573. this.zOffset = 1;
  74574. this._scene = scene;
  74575. }
  74576. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  74577. var _this = this;
  74578. if (useOverlay === void 0) { useOverlay = false; }
  74579. var scene = this._scene;
  74580. var engine = this._scene.getEngine();
  74581. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74582. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  74583. return;
  74584. }
  74585. var mesh = subMesh.getRenderingMesh();
  74586. var material = subMesh.getMaterial();
  74587. if (!material || !scene.activeCamera) {
  74588. return;
  74589. }
  74590. engine.enableEffect(this._effect);
  74591. // Logarithmic depth
  74592. if (material.useLogarithmicDepth) {
  74593. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  74594. }
  74595. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  74596. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  74597. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74598. // Bones
  74599. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74600. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74601. }
  74602. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74603. // Alpha test
  74604. if (material && material.needAlphaTesting()) {
  74605. var alphaTexture = material.getAlphaTestTexture();
  74606. if (alphaTexture) {
  74607. this._effect.setTexture("diffuseSampler", alphaTexture);
  74608. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74609. }
  74610. }
  74611. engine.setZOffset(-this.zOffset);
  74612. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  74613. engine.setZOffset(0);
  74614. };
  74615. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  74616. var defines = [];
  74617. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74618. var mesh = subMesh.getMesh();
  74619. var material = subMesh.getMaterial();
  74620. if (material) {
  74621. // Alpha test
  74622. if (material.needAlphaTesting()) {
  74623. defines.push("#define ALPHATEST");
  74624. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74625. attribs.push(BABYLON.VertexBuffer.UVKind);
  74626. defines.push("#define UV1");
  74627. }
  74628. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74630. defines.push("#define UV2");
  74631. }
  74632. }
  74633. //Logarithmic depth
  74634. if (material.useLogarithmicDepth) {
  74635. defines.push("#define LOGARITHMICDEPTH");
  74636. }
  74637. }
  74638. // Bones
  74639. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74642. if (mesh.numBoneInfluencers > 4) {
  74643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74645. }
  74646. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74647. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74648. }
  74649. else {
  74650. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74651. }
  74652. // Instances
  74653. if (useInstances) {
  74654. defines.push("#define INSTANCES");
  74655. attribs.push("world0");
  74656. attribs.push("world1");
  74657. attribs.push("world2");
  74658. attribs.push("world3");
  74659. }
  74660. // Get correct effect
  74661. var join = defines.join("\n");
  74662. if (this._cachedDefines !== join) {
  74663. this._cachedDefines = join;
  74664. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  74665. }
  74666. return this._effect.isReady();
  74667. };
  74668. return OutlineRenderer;
  74669. }());
  74670. BABYLON.OutlineRenderer = OutlineRenderer;
  74671. })(BABYLON || (BABYLON = {}));
  74672. //# sourceMappingURL=babylon.outlineRenderer.js.map
  74673. var BABYLON;
  74674. (function (BABYLON) {
  74675. var FaceAdjacencies = /** @class */ (function () {
  74676. function FaceAdjacencies() {
  74677. this.edges = new Array();
  74678. this.edgesConnectedCount = 0;
  74679. }
  74680. return FaceAdjacencies;
  74681. }());
  74682. var EdgesRenderer = /** @class */ (function () {
  74683. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  74684. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  74685. if (epsilon === void 0) { epsilon = 0.95; }
  74686. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  74687. this.edgesWidthScalerForOrthographic = 1000.0;
  74688. this.edgesWidthScalerForPerspective = 50.0;
  74689. this._linesPositions = new Array();
  74690. this._linesNormals = new Array();
  74691. this._linesIndices = new Array();
  74692. this._buffers = {};
  74693. this._checkVerticesInsteadOfIndices = false;
  74694. this._source = source;
  74695. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  74696. this._epsilon = epsilon;
  74697. this._prepareRessources();
  74698. this._generateEdgesLines();
  74699. }
  74700. EdgesRenderer.prototype._prepareRessources = function () {
  74701. if (this._lineShader) {
  74702. return;
  74703. }
  74704. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  74705. attributes: ["position", "normal"],
  74706. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  74707. });
  74708. this._lineShader.disableDepthWrite = true;
  74709. this._lineShader.backFaceCulling = false;
  74710. };
  74711. EdgesRenderer.prototype._rebuild = function () {
  74712. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  74713. if (buffer) {
  74714. buffer._rebuild();
  74715. }
  74716. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  74717. if (buffer) {
  74718. buffer._rebuild();
  74719. }
  74720. var scene = this._source.getScene();
  74721. var engine = scene.getEngine();
  74722. this._ib = engine.createIndexBuffer(this._linesIndices);
  74723. };
  74724. EdgesRenderer.prototype.dispose = function () {
  74725. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  74726. if (buffer) {
  74727. buffer.dispose();
  74728. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  74729. }
  74730. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  74731. if (buffer) {
  74732. buffer.dispose();
  74733. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  74734. }
  74735. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  74736. this._lineShader.dispose();
  74737. };
  74738. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  74739. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  74740. return 0;
  74741. }
  74742. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  74743. return 1;
  74744. }
  74745. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  74746. return 2;
  74747. }
  74748. return -1;
  74749. };
  74750. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  74751. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  74752. return 0;
  74753. }
  74754. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  74755. return 1;
  74756. }
  74757. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  74758. return 2;
  74759. }
  74760. return -1;
  74761. };
  74762. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  74763. var needToCreateLine;
  74764. if (edge === undefined) {
  74765. needToCreateLine = true;
  74766. }
  74767. else {
  74768. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  74769. needToCreateLine = dotProduct < this._epsilon;
  74770. }
  74771. if (needToCreateLine) {
  74772. var offset = this._linesPositions.length / 3;
  74773. var normal = p0.subtract(p1);
  74774. normal.normalize();
  74775. // Positions
  74776. this._linesPositions.push(p0.x);
  74777. this._linesPositions.push(p0.y);
  74778. this._linesPositions.push(p0.z);
  74779. this._linesPositions.push(p0.x);
  74780. this._linesPositions.push(p0.y);
  74781. this._linesPositions.push(p0.z);
  74782. this._linesPositions.push(p1.x);
  74783. this._linesPositions.push(p1.y);
  74784. this._linesPositions.push(p1.z);
  74785. this._linesPositions.push(p1.x);
  74786. this._linesPositions.push(p1.y);
  74787. this._linesPositions.push(p1.z);
  74788. // Normals
  74789. this._linesNormals.push(p1.x);
  74790. this._linesNormals.push(p1.y);
  74791. this._linesNormals.push(p1.z);
  74792. this._linesNormals.push(-1);
  74793. this._linesNormals.push(p1.x);
  74794. this._linesNormals.push(p1.y);
  74795. this._linesNormals.push(p1.z);
  74796. this._linesNormals.push(1);
  74797. this._linesNormals.push(p0.x);
  74798. this._linesNormals.push(p0.y);
  74799. this._linesNormals.push(p0.z);
  74800. this._linesNormals.push(-1);
  74801. this._linesNormals.push(p0.x);
  74802. this._linesNormals.push(p0.y);
  74803. this._linesNormals.push(p0.z);
  74804. this._linesNormals.push(1);
  74805. // Indices
  74806. this._linesIndices.push(offset);
  74807. this._linesIndices.push(offset + 1);
  74808. this._linesIndices.push(offset + 2);
  74809. this._linesIndices.push(offset);
  74810. this._linesIndices.push(offset + 2);
  74811. this._linesIndices.push(offset + 3);
  74812. }
  74813. };
  74814. EdgesRenderer.prototype._generateEdgesLines = function () {
  74815. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74816. var indices = this._source.getIndices();
  74817. if (!indices || !positions) {
  74818. return;
  74819. }
  74820. // First let's find adjacencies
  74821. var adjacencies = new Array();
  74822. var faceNormals = new Array();
  74823. var index;
  74824. var faceAdjacencies;
  74825. // Prepare faces
  74826. for (index = 0; index < indices.length; index += 3) {
  74827. faceAdjacencies = new FaceAdjacencies();
  74828. var p0Index = indices[index];
  74829. var p1Index = indices[index + 1];
  74830. var p2Index = indices[index + 2];
  74831. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  74832. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  74833. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  74834. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  74835. faceNormal.normalize();
  74836. faceNormals.push(faceNormal);
  74837. adjacencies.push(faceAdjacencies);
  74838. }
  74839. // Scan
  74840. for (index = 0; index < adjacencies.length; index++) {
  74841. faceAdjacencies = adjacencies[index];
  74842. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  74843. var otherFaceAdjacencies = adjacencies[otherIndex];
  74844. if (faceAdjacencies.edgesConnectedCount === 3) {
  74845. break;
  74846. }
  74847. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  74848. continue;
  74849. }
  74850. var otherP0 = indices[otherIndex * 3];
  74851. var otherP1 = indices[otherIndex * 3 + 1];
  74852. var otherP2 = indices[otherIndex * 3 + 2];
  74853. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  74854. var otherEdgeIndex = 0;
  74855. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  74856. continue;
  74857. }
  74858. switch (edgeIndex) {
  74859. case 0:
  74860. if (this._checkVerticesInsteadOfIndices) {
  74861. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74862. }
  74863. else {
  74864. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  74865. }
  74866. break;
  74867. case 1:
  74868. if (this._checkVerticesInsteadOfIndices) {
  74869. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74870. }
  74871. else {
  74872. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  74873. }
  74874. break;
  74875. case 2:
  74876. if (this._checkVerticesInsteadOfIndices) {
  74877. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74878. }
  74879. else {
  74880. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  74881. }
  74882. break;
  74883. }
  74884. if (otherEdgeIndex === -1) {
  74885. continue;
  74886. }
  74887. faceAdjacencies.edges[edgeIndex] = otherIndex;
  74888. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  74889. faceAdjacencies.edgesConnectedCount++;
  74890. otherFaceAdjacencies.edgesConnectedCount++;
  74891. if (faceAdjacencies.edgesConnectedCount === 3) {
  74892. break;
  74893. }
  74894. }
  74895. }
  74896. }
  74897. // Create lines
  74898. for (index = 0; index < adjacencies.length; index++) {
  74899. // 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
  74900. var current = adjacencies[index];
  74901. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  74902. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  74903. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  74904. }
  74905. // Merge into a single mesh
  74906. var engine = this._source.getScene().getEngine();
  74907. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  74908. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  74909. this._ib = engine.createIndexBuffer(this._linesIndices);
  74910. this._indicesCount = this._linesIndices.length;
  74911. };
  74912. EdgesRenderer.prototype.render = function () {
  74913. var scene = this._source.getScene();
  74914. if (!this._lineShader.isReady() || !scene.activeCamera) {
  74915. return;
  74916. }
  74917. var engine = scene.getEngine();
  74918. this._lineShader._preBind();
  74919. // VBOs
  74920. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  74921. scene.resetCachedMaterial();
  74922. this._lineShader.setColor4("color", this._source.edgesColor);
  74923. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  74924. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  74925. }
  74926. else {
  74927. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  74928. }
  74929. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  74930. this._lineShader.bind(this._source.getWorldMatrix());
  74931. // Draw order
  74932. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  74933. this._lineShader.unbind();
  74934. engine.setDepthWrite(true);
  74935. };
  74936. return EdgesRenderer;
  74937. }());
  74938. BABYLON.EdgesRenderer = EdgesRenderer;
  74939. })(BABYLON || (BABYLON = {}));
  74940. //# sourceMappingURL=babylon.edgesRenderer.js.map
  74941. var BABYLON;
  74942. (function (BABYLON) {
  74943. /**
  74944. * Special Glow Blur post process only blurring the alpha channel
  74945. * It enforces keeping the most luminous color in the color channel.
  74946. */
  74947. var GlowBlurPostProcess = /** @class */ (function (_super) {
  74948. __extends(GlowBlurPostProcess, _super);
  74949. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  74950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74951. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  74952. _this.direction = direction;
  74953. _this.kernel = kernel;
  74954. _this.onApplyObservable.add(function (effect) {
  74955. effect.setFloat2("screenSize", _this.width, _this.height);
  74956. effect.setVector2("direction", _this.direction);
  74957. effect.setFloat("blurWidth", _this.kernel);
  74958. });
  74959. return _this;
  74960. }
  74961. return GlowBlurPostProcess;
  74962. }(BABYLON.PostProcess));
  74963. /**
  74964. * The highlight layer Helps adding a glow effect around a mesh.
  74965. *
  74966. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  74967. * glowy meshes to your scene.
  74968. *
  74969. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  74970. */
  74971. var HighlightLayer = /** @class */ (function () {
  74972. /**
  74973. * Instantiates a new highlight Layer and references it to the scene..
  74974. * @param name The name of the layer
  74975. * @param scene The scene to use the layer in
  74976. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  74977. */
  74978. function HighlightLayer(name, scene, options) {
  74979. this.name = name;
  74980. this._vertexBuffers = {};
  74981. this._mainTextureDesiredSize = { width: 0, height: 0 };
  74982. this._meshes = {};
  74983. this._maxSize = 0;
  74984. this._shouldRender = false;
  74985. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  74986. this._excludedMeshes = {};
  74987. /**
  74988. * Specifies whether or not the inner glow is ACTIVE in the layer.
  74989. */
  74990. this.innerGlow = true;
  74991. /**
  74992. * Specifies whether or not the outer glow is ACTIVE in the layer.
  74993. */
  74994. this.outerGlow = true;
  74995. /**
  74996. * Specifies wether the highlight layer is enabled or not.
  74997. */
  74998. this.isEnabled = true;
  74999. /**
  75000. * An event triggered when the highlight layer has been disposed.
  75001. * @type {BABYLON.Observable}
  75002. */
  75003. this.onDisposeObservable = new BABYLON.Observable();
  75004. /**
  75005. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  75006. * @type {BABYLON.Observable}
  75007. */
  75008. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  75009. /**
  75010. * An event triggered when the highlight layer is being blurred.
  75011. * @type {BABYLON.Observable}
  75012. */
  75013. this.onBeforeBlurObservable = new BABYLON.Observable();
  75014. /**
  75015. * An event triggered when the highlight layer has been blurred.
  75016. * @type {BABYLON.Observable}
  75017. */
  75018. this.onAfterBlurObservable = new BABYLON.Observable();
  75019. /**
  75020. * An event triggered when the glowing blurred texture is being merged in the scene.
  75021. * @type {BABYLON.Observable}
  75022. */
  75023. this.onBeforeComposeObservable = new BABYLON.Observable();
  75024. /**
  75025. * An event triggered when the glowing blurred texture has been merged in the scene.
  75026. * @type {BABYLON.Observable}
  75027. */
  75028. this.onAfterComposeObservable = new BABYLON.Observable();
  75029. /**
  75030. * An event triggered when the highlight layer changes its size.
  75031. * @type {BABYLON.Observable}
  75032. */
  75033. this.onSizeChangedObservable = new BABYLON.Observable();
  75034. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75035. var engine = scene.getEngine();
  75036. this._engine = engine;
  75037. this._maxSize = this._engine.getCaps().maxTextureSize;
  75038. this._scene.highlightLayers.push(this);
  75039. // Warn on stencil.
  75040. if (!this._engine.isStencilEnable) {
  75041. 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 }");
  75042. }
  75043. // Adapt options
  75044. this._options = options || {
  75045. mainTextureRatio: 0.5,
  75046. blurTextureSizeRatio: 0.5,
  75047. blurHorizontalSize: 1.0,
  75048. blurVerticalSize: 1.0,
  75049. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  75050. camera: null
  75051. };
  75052. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  75053. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  75054. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  75055. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  75056. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  75057. // VBO
  75058. var vertices = [];
  75059. vertices.push(1, 1);
  75060. vertices.push(-1, 1);
  75061. vertices.push(-1, -1);
  75062. vertices.push(1, -1);
  75063. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75065. this._createIndexBuffer();
  75066. // Effect
  75067. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  75068. // Render target
  75069. this.setMainTextureSize();
  75070. // Create Textures and post processes
  75071. this.createTextureAndPostProcesses();
  75072. }
  75073. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  75074. /**
  75075. * Gets the horizontal size of the blur.
  75076. */
  75077. get: function () {
  75078. return this._horizontalBlurPostprocess.kernel;
  75079. },
  75080. /**
  75081. * Specifies the horizontal size of the blur.
  75082. */
  75083. set: function (value) {
  75084. this._horizontalBlurPostprocess.kernel = value;
  75085. },
  75086. enumerable: true,
  75087. configurable: true
  75088. });
  75089. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  75090. /**
  75091. * Gets the vertical size of the blur.
  75092. */
  75093. get: function () {
  75094. return this._verticalBlurPostprocess.kernel;
  75095. },
  75096. /**
  75097. * Specifies the vertical size of the blur.
  75098. */
  75099. set: function (value) {
  75100. this._verticalBlurPostprocess.kernel = value;
  75101. },
  75102. enumerable: true,
  75103. configurable: true
  75104. });
  75105. Object.defineProperty(HighlightLayer.prototype, "camera", {
  75106. /**
  75107. * Gets the camera attached to the layer.
  75108. */
  75109. get: function () {
  75110. return this._options.camera;
  75111. },
  75112. enumerable: true,
  75113. configurable: true
  75114. });
  75115. HighlightLayer.prototype._createIndexBuffer = function () {
  75116. var engine = this._scene.getEngine();
  75117. // Indices
  75118. var indices = [];
  75119. indices.push(0);
  75120. indices.push(1);
  75121. indices.push(2);
  75122. indices.push(0);
  75123. indices.push(2);
  75124. indices.push(3);
  75125. this._indexBuffer = engine.createIndexBuffer(indices);
  75126. };
  75127. HighlightLayer.prototype._rebuild = function () {
  75128. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75129. if (vb) {
  75130. vb._rebuild();
  75131. }
  75132. this._createIndexBuffer();
  75133. };
  75134. /**
  75135. * Creates the render target textures and post processes used in the highlight layer.
  75136. */
  75137. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  75138. var _this = this;
  75139. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  75140. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  75141. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  75142. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  75143. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  75144. width: this._mainTextureDesiredSize.width,
  75145. height: this._mainTextureDesiredSize.height
  75146. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75147. this._mainTexture.activeCamera = this._options.camera;
  75148. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75149. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75150. this._mainTexture.anisotropicFilteringLevel = 1;
  75151. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75152. this._mainTexture.renderParticles = false;
  75153. this._mainTexture.renderList = null;
  75154. this._mainTexture.ignoreCameraViewport = true;
  75155. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  75156. width: blurTextureWidth,
  75157. height: blurTextureHeight
  75158. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75159. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75160. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75161. this._blurTexture.anisotropicFilteringLevel = 16;
  75162. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75163. this._blurTexture.renderParticles = false;
  75164. this._blurTexture.ignoreCameraViewport = true;
  75165. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75166. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  75167. effect.setTexture("textureSampler", _this._mainTexture);
  75168. });
  75169. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  75170. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75171. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75172. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75173. });
  75174. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75175. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75176. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75177. });
  75178. }
  75179. else {
  75180. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75181. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75182. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75183. });
  75184. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75185. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75186. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75187. });
  75188. }
  75189. this._mainTexture.onAfterUnbindObservable.add(function () {
  75190. _this.onBeforeBlurObservable.notifyObservers(_this);
  75191. var internalTexture = _this._blurTexture.getInternalTexture();
  75192. if (internalTexture) {
  75193. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  75194. }
  75195. _this.onAfterBlurObservable.notifyObservers(_this);
  75196. });
  75197. // Custom render function
  75198. var renderSubMesh = function (subMesh) {
  75199. if (!_this._meshes) {
  75200. return;
  75201. }
  75202. var material = subMesh.getMaterial();
  75203. var mesh = subMesh.getRenderingMesh();
  75204. var scene = _this._scene;
  75205. var engine = scene.getEngine();
  75206. if (!material) {
  75207. return;
  75208. }
  75209. // Do not block in blend mode.
  75210. if (material.needAlphaBlendingForMesh(mesh)) {
  75211. return;
  75212. }
  75213. // Culling
  75214. engine.setState(material.backFaceCulling);
  75215. // Managing instances
  75216. var batch = mesh._getInstancesRenderList(subMesh._id);
  75217. if (batch.mustReturn) {
  75218. return;
  75219. }
  75220. // Excluded Mesh
  75221. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75222. return;
  75223. }
  75224. ;
  75225. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75226. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  75227. var emissiveTexture = null;
  75228. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  75229. emissiveTexture = material.emissiveTexture;
  75230. }
  75231. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  75232. engine.enableEffect(_this._glowMapGenerationEffect);
  75233. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  75234. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  75235. if (highlightLayerMesh) {
  75236. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  75237. }
  75238. else {
  75239. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  75240. }
  75241. // Alpha test
  75242. if (material && material.needAlphaTesting()) {
  75243. var alphaTexture = material.getAlphaTestTexture();
  75244. if (alphaTexture) {
  75245. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  75246. var textureMatrix = alphaTexture.getTextureMatrix();
  75247. if (textureMatrix) {
  75248. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  75249. }
  75250. }
  75251. }
  75252. // Glow emissive only
  75253. if (emissiveTexture) {
  75254. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  75255. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  75256. }
  75257. // Bones
  75258. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75259. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75260. }
  75261. // Draw
  75262. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  75263. }
  75264. else {
  75265. // Need to reset refresh rate of the shadowMap
  75266. _this._mainTexture.resetRefreshCounter();
  75267. }
  75268. };
  75269. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75270. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  75271. var index;
  75272. var engine = _this._scene.getEngine();
  75273. if (depthOnlySubMeshes.length) {
  75274. engine.setColorWrite(false);
  75275. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75276. renderSubMesh(depthOnlySubMeshes.data[index]);
  75277. }
  75278. engine.setColorWrite(true);
  75279. }
  75280. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75281. renderSubMesh(opaqueSubMeshes.data[index]);
  75282. }
  75283. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75284. renderSubMesh(alphaTestSubMeshes.data[index]);
  75285. }
  75286. for (index = 0; index < transparentSubMeshes.length; index++) {
  75287. renderSubMesh(transparentSubMeshes.data[index]);
  75288. }
  75289. };
  75290. this._mainTexture.onClearObservable.add(function (engine) {
  75291. engine.clear(HighlightLayer.neutralColor, true, true, true);
  75292. });
  75293. };
  75294. /**
  75295. * Checks for the readiness of the element composing the layer.
  75296. * @param subMesh the mesh to check for
  75297. * @param useInstances specify wether or not to use instances to render the mesh
  75298. * @param emissiveTexture the associated emissive texture used to generate the glow
  75299. * @return true if ready otherwise, false
  75300. */
  75301. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  75302. var material = subMesh.getMaterial();
  75303. if (!material) {
  75304. return false;
  75305. }
  75306. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  75307. return false;
  75308. }
  75309. var defines = [];
  75310. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75311. var mesh = subMesh.getMesh();
  75312. var uv1 = false;
  75313. var uv2 = false;
  75314. // Alpha test
  75315. if (material && material.needAlphaTesting()) {
  75316. var alphaTexture = material.getAlphaTestTexture();
  75317. if (alphaTexture) {
  75318. defines.push("#define ALPHATEST");
  75319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75320. alphaTexture.coordinatesIndex === 1) {
  75321. defines.push("#define DIFFUSEUV2");
  75322. uv2 = true;
  75323. }
  75324. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75325. defines.push("#define DIFFUSEUV1");
  75326. uv1 = true;
  75327. }
  75328. }
  75329. }
  75330. // Emissive
  75331. if (emissiveTexture) {
  75332. defines.push("#define EMISSIVE");
  75333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75334. emissiveTexture.coordinatesIndex === 1) {
  75335. defines.push("#define EMISSIVEUV2");
  75336. uv2 = true;
  75337. }
  75338. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75339. defines.push("#define EMISSIVEUV1");
  75340. uv1 = true;
  75341. }
  75342. }
  75343. if (uv1) {
  75344. attribs.push(BABYLON.VertexBuffer.UVKind);
  75345. defines.push("#define UV1");
  75346. }
  75347. if (uv2) {
  75348. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75349. defines.push("#define UV2");
  75350. }
  75351. // Bones
  75352. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75355. if (mesh.numBoneInfluencers > 4) {
  75356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75358. }
  75359. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75360. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75361. }
  75362. else {
  75363. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75364. }
  75365. // Instances
  75366. if (useInstances) {
  75367. defines.push("#define INSTANCES");
  75368. attribs.push("world0");
  75369. attribs.push("world1");
  75370. attribs.push("world2");
  75371. attribs.push("world3");
  75372. }
  75373. // Get correct effect
  75374. var join = defines.join("\n");
  75375. if (this._cachedDefines !== join) {
  75376. this._cachedDefines = join;
  75377. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  75378. }
  75379. return this._glowMapGenerationEffect.isReady();
  75380. };
  75381. /**
  75382. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  75383. */
  75384. HighlightLayer.prototype.render = function () {
  75385. var currentEffect = this._glowMapMergeEffect;
  75386. // Check
  75387. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  75388. return;
  75389. var engine = this._scene.getEngine();
  75390. this.onBeforeComposeObservable.notifyObservers(this);
  75391. // Render
  75392. engine.enableEffect(currentEffect);
  75393. engine.setState(false);
  75394. // Cache
  75395. var previousStencilBuffer = engine.getStencilBuffer();
  75396. var previousStencilFunction = engine.getStencilFunction();
  75397. var previousStencilMask = engine.getStencilMask();
  75398. var previousStencilOperationPass = engine.getStencilOperationPass();
  75399. var previousStencilOperationFail = engine.getStencilOperationFail();
  75400. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  75401. var previousAlphaMode = engine.getAlphaMode();
  75402. // Texture
  75403. currentEffect.setTexture("textureSampler", this._blurTexture);
  75404. // VBOs
  75405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75406. // Stencil operations
  75407. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  75408. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  75409. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  75410. // Draw order
  75411. engine.setAlphaMode(this._options.alphaBlendingMode);
  75412. engine.setStencilMask(0x00);
  75413. engine.setStencilBuffer(true);
  75414. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  75415. if (this.outerGlow) {
  75416. currentEffect.setFloat("offset", 0);
  75417. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  75418. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75419. }
  75420. if (this.innerGlow) {
  75421. currentEffect.setFloat("offset", 1);
  75422. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  75423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75424. }
  75425. // Restore Cache
  75426. engine.setStencilFunction(previousStencilFunction);
  75427. engine.setStencilMask(previousStencilMask);
  75428. engine.setAlphaMode(previousAlphaMode);
  75429. engine.setStencilBuffer(previousStencilBuffer);
  75430. engine.setStencilOperationPass(previousStencilOperationPass);
  75431. engine.setStencilOperationFail(previousStencilOperationFail);
  75432. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  75433. engine._stencilState.reset();
  75434. this.onAfterComposeObservable.notifyObservers(this);
  75435. // Handle size changes.
  75436. var size = this._mainTexture.getSize();
  75437. this.setMainTextureSize();
  75438. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  75439. // Recreate RTT and post processes on size change.
  75440. this.onSizeChangedObservable.notifyObservers(this);
  75441. this.disposeTextureAndPostProcesses();
  75442. this.createTextureAndPostProcesses();
  75443. }
  75444. };
  75445. /**
  75446. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  75447. * @param mesh The mesh to exclude from the highlight layer
  75448. */
  75449. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  75450. if (!this._excludedMeshes) {
  75451. return;
  75452. }
  75453. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75454. if (!meshExcluded) {
  75455. this._excludedMeshes[mesh.uniqueId] = {
  75456. mesh: mesh,
  75457. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  75458. mesh.getEngine().setStencilBuffer(false);
  75459. }),
  75460. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  75461. mesh.getEngine().setStencilBuffer(true);
  75462. }),
  75463. };
  75464. }
  75465. };
  75466. /**
  75467. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  75468. * @param mesh The mesh to highlight
  75469. */
  75470. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  75471. if (!this._excludedMeshes) {
  75472. return;
  75473. }
  75474. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75475. if (meshExcluded) {
  75476. if (meshExcluded.beforeRender) {
  75477. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  75478. }
  75479. if (meshExcluded.afterRender) {
  75480. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  75481. }
  75482. }
  75483. this._excludedMeshes[mesh.uniqueId] = null;
  75484. };
  75485. /**
  75486. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  75487. * @param mesh The mesh to highlight
  75488. * @param color The color of the highlight
  75489. * @param glowEmissiveOnly Extract the glow from the emissive texture
  75490. */
  75491. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  75492. var _this = this;
  75493. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  75494. if (!this._meshes) {
  75495. return;
  75496. }
  75497. var meshHighlight = this._meshes[mesh.uniqueId];
  75498. if (meshHighlight) {
  75499. meshHighlight.color = color;
  75500. }
  75501. else {
  75502. this._meshes[mesh.uniqueId] = {
  75503. mesh: mesh,
  75504. color: color,
  75505. // Lambda required for capture due to Observable this context
  75506. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  75507. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75508. _this.defaultStencilReference(mesh);
  75509. }
  75510. else {
  75511. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  75512. }
  75513. }),
  75514. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  75515. glowEmissiveOnly: glowEmissiveOnly
  75516. };
  75517. }
  75518. this._shouldRender = true;
  75519. };
  75520. /**
  75521. * Remove a mesh from the highlight layer in order to make it stop glowing.
  75522. * @param mesh The mesh to highlight
  75523. */
  75524. HighlightLayer.prototype.removeMesh = function (mesh) {
  75525. if (!this._meshes) {
  75526. return;
  75527. }
  75528. var meshHighlight = this._meshes[mesh.uniqueId];
  75529. if (meshHighlight) {
  75530. if (meshHighlight.observerHighlight) {
  75531. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75532. }
  75533. if (meshHighlight.observerDefault) {
  75534. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75535. }
  75536. delete this._meshes[mesh.uniqueId];
  75537. }
  75538. this._shouldRender = false;
  75539. for (var meshHighlightToCheck in this._meshes) {
  75540. if (this._meshes[meshHighlightToCheck]) {
  75541. this._shouldRender = true;
  75542. break;
  75543. }
  75544. }
  75545. };
  75546. /**
  75547. * Returns true if the layer contains information to display, otherwise false.
  75548. */
  75549. HighlightLayer.prototype.shouldRender = function () {
  75550. return this.isEnabled && this._shouldRender;
  75551. };
  75552. /**
  75553. * Sets the main texture desired size which is the closest power of two
  75554. * of the engine canvas size.
  75555. */
  75556. HighlightLayer.prototype.setMainTextureSize = function () {
  75557. if (this._options.mainTextureFixedSize) {
  75558. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  75559. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  75560. }
  75561. else {
  75562. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  75563. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  75564. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  75565. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  75566. }
  75567. };
  75568. /**
  75569. * Force the stencil to the normal expected value for none glowing parts
  75570. */
  75571. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  75572. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  75573. };
  75574. /**
  75575. * Dispose only the render target textures and post process.
  75576. */
  75577. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  75578. this._blurTexture.dispose();
  75579. this._mainTexture.dispose();
  75580. this._downSamplePostprocess.dispose();
  75581. this._horizontalBlurPostprocess.dispose();
  75582. this._verticalBlurPostprocess.dispose();
  75583. };
  75584. /**
  75585. * Dispose the highlight layer and free resources.
  75586. */
  75587. HighlightLayer.prototype.dispose = function () {
  75588. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75589. if (vertexBuffer) {
  75590. vertexBuffer.dispose();
  75591. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75592. }
  75593. if (this._indexBuffer) {
  75594. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75595. this._indexBuffer = null;
  75596. }
  75597. // Clean textures and post processes
  75598. this.disposeTextureAndPostProcesses();
  75599. if (this._meshes) {
  75600. // Clean mesh references
  75601. for (var id in this._meshes) {
  75602. var meshHighlight = this._meshes[id];
  75603. if (meshHighlight && meshHighlight.mesh) {
  75604. if (meshHighlight.observerHighlight) {
  75605. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75606. }
  75607. if (meshHighlight.observerDefault) {
  75608. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75609. }
  75610. }
  75611. }
  75612. this._meshes = null;
  75613. }
  75614. if (this._excludedMeshes) {
  75615. for (var id in this._excludedMeshes) {
  75616. var meshHighlight = this._excludedMeshes[id];
  75617. if (meshHighlight) {
  75618. if (meshHighlight.beforeRender) {
  75619. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  75620. }
  75621. if (meshHighlight.afterRender) {
  75622. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  75623. }
  75624. }
  75625. }
  75626. this._excludedMeshes = null;
  75627. }
  75628. // Remove from scene
  75629. var index = this._scene.highlightLayers.indexOf(this, 0);
  75630. if (index > -1) {
  75631. this._scene.highlightLayers.splice(index, 1);
  75632. }
  75633. // Callback
  75634. this.onDisposeObservable.notifyObservers(this);
  75635. this.onDisposeObservable.clear();
  75636. this.onBeforeRenderMainTextureObservable.clear();
  75637. this.onBeforeBlurObservable.clear();
  75638. this.onBeforeComposeObservable.clear();
  75639. this.onAfterComposeObservable.clear();
  75640. this.onSizeChangedObservable.clear();
  75641. };
  75642. /**
  75643. * The neutral color used during the preparation of the glow effect.
  75644. * This is black by default as the blend operation is a blend operation.
  75645. */
  75646. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  75647. /**
  75648. * Stencil value used for glowing meshes.
  75649. */
  75650. HighlightLayer.glowingMeshStencilReference = 0x02;
  75651. /**
  75652. * Stencil value used for the other meshes in the scene.
  75653. */
  75654. HighlightLayer.normalMeshStencilReference = 0x01;
  75655. return HighlightLayer;
  75656. }());
  75657. BABYLON.HighlightLayer = HighlightLayer;
  75658. })(BABYLON || (BABYLON = {}));
  75659. //# sourceMappingURL=babylon.highlightlayer.js.map
  75660. var BABYLON;
  75661. (function (BABYLON) {
  75662. var AssetTaskState;
  75663. (function (AssetTaskState) {
  75664. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  75665. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  75666. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  75667. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  75668. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  75669. var AbstractAssetTask = /** @class */ (function () {
  75670. function AbstractAssetTask(name) {
  75671. this.name = name;
  75672. this.isCompleted = false;
  75673. this.taskState = AssetTaskState.INIT;
  75674. }
  75675. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75676. var _this = this;
  75677. this.taskState = AssetTaskState.RUNNING;
  75678. this.runTask(scene, function () {
  75679. _this.onDoneCallback(onSuccess, onError);
  75680. }, function (msg, exception) {
  75681. _this.onErrorCallback(onError, msg, exception);
  75682. });
  75683. };
  75684. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75685. throw new Error("runTask is not implemented");
  75686. };
  75687. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  75688. this.taskState = AssetTaskState.ERROR;
  75689. this.errorObject = {
  75690. message: message,
  75691. exception: exception
  75692. };
  75693. if (this.onError) {
  75694. this.onError(this, message, exception);
  75695. }
  75696. onError();
  75697. };
  75698. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  75699. try {
  75700. this.taskState = AssetTaskState.DONE;
  75701. this.isCompleted = true;
  75702. if (this.onSuccess) {
  75703. this.onSuccess(this);
  75704. }
  75705. onSuccess();
  75706. }
  75707. catch (e) {
  75708. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  75709. }
  75710. };
  75711. return AbstractAssetTask;
  75712. }());
  75713. BABYLON.AbstractAssetTask = AbstractAssetTask;
  75714. var AssetsProgressEvent = /** @class */ (function () {
  75715. function AssetsProgressEvent(remainingCount, totalCount, task) {
  75716. this.remainingCount = remainingCount;
  75717. this.totalCount = totalCount;
  75718. this.task = task;
  75719. }
  75720. return AssetsProgressEvent;
  75721. }());
  75722. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  75723. var MeshAssetTask = /** @class */ (function (_super) {
  75724. __extends(MeshAssetTask, _super);
  75725. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  75726. var _this = _super.call(this, name) || this;
  75727. _this.name = name;
  75728. _this.meshesNames = meshesNames;
  75729. _this.rootUrl = rootUrl;
  75730. _this.sceneFilename = sceneFilename;
  75731. return _this;
  75732. }
  75733. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75734. var _this = this;
  75735. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  75736. _this.loadedMeshes = meshes;
  75737. _this.loadedParticleSystems = particleSystems;
  75738. _this.loadedSkeletons = skeletons;
  75739. onSuccess();
  75740. }, null, function (scene, message, exception) {
  75741. onError(message, exception);
  75742. });
  75743. };
  75744. return MeshAssetTask;
  75745. }(AbstractAssetTask));
  75746. BABYLON.MeshAssetTask = MeshAssetTask;
  75747. var TextFileAssetTask = /** @class */ (function (_super) {
  75748. __extends(TextFileAssetTask, _super);
  75749. function TextFileAssetTask(name, url) {
  75750. var _this = _super.call(this, name) || this;
  75751. _this.name = name;
  75752. _this.url = url;
  75753. return _this;
  75754. }
  75755. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75756. var _this = this;
  75757. BABYLON.Tools.LoadFile(this.url, function (data) {
  75758. _this.text = data;
  75759. onSuccess();
  75760. }, undefined, scene.database, false, function (request, exception) {
  75761. if (request) {
  75762. onError(request.status + " " + request.statusText, exception);
  75763. }
  75764. });
  75765. };
  75766. return TextFileAssetTask;
  75767. }(AbstractAssetTask));
  75768. BABYLON.TextFileAssetTask = TextFileAssetTask;
  75769. var BinaryFileAssetTask = /** @class */ (function (_super) {
  75770. __extends(BinaryFileAssetTask, _super);
  75771. function BinaryFileAssetTask(name, url) {
  75772. var _this = _super.call(this, name) || this;
  75773. _this.name = name;
  75774. _this.url = url;
  75775. return _this;
  75776. }
  75777. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75778. var _this = this;
  75779. BABYLON.Tools.LoadFile(this.url, function (data) {
  75780. _this.data = data;
  75781. onSuccess();
  75782. }, undefined, scene.database, true, function (request, exception) {
  75783. if (request) {
  75784. onError(request.status + " " + request.statusText, exception);
  75785. }
  75786. });
  75787. };
  75788. return BinaryFileAssetTask;
  75789. }(AbstractAssetTask));
  75790. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  75791. var ImageAssetTask = /** @class */ (function (_super) {
  75792. __extends(ImageAssetTask, _super);
  75793. function ImageAssetTask(name, url) {
  75794. var _this = _super.call(this, name) || this;
  75795. _this.name = name;
  75796. _this.url = url;
  75797. return _this;
  75798. }
  75799. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75800. var _this = this;
  75801. var img = new Image();
  75802. BABYLON.Tools.SetCorsBehavior(this.url, img);
  75803. img.onload = function () {
  75804. _this.image = img;
  75805. onSuccess();
  75806. };
  75807. img.onerror = function (err) {
  75808. onError("Error loading image", err);
  75809. };
  75810. img.src = this.url;
  75811. };
  75812. return ImageAssetTask;
  75813. }(AbstractAssetTask));
  75814. BABYLON.ImageAssetTask = ImageAssetTask;
  75815. var TextureAssetTask = /** @class */ (function (_super) {
  75816. __extends(TextureAssetTask, _super);
  75817. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  75818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75819. var _this = _super.call(this, name) || this;
  75820. _this.name = name;
  75821. _this.url = url;
  75822. _this.noMipmap = noMipmap;
  75823. _this.invertY = invertY;
  75824. _this.samplingMode = samplingMode;
  75825. return _this;
  75826. }
  75827. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75828. var onload = function () {
  75829. onSuccess();
  75830. };
  75831. var onerror = function (message, exception) {
  75832. onError(message, exception);
  75833. };
  75834. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  75835. };
  75836. return TextureAssetTask;
  75837. }(AbstractAssetTask));
  75838. BABYLON.TextureAssetTask = TextureAssetTask;
  75839. var CubeTextureAssetTask = /** @class */ (function (_super) {
  75840. __extends(CubeTextureAssetTask, _super);
  75841. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  75842. var _this = _super.call(this, name) || this;
  75843. _this.name = name;
  75844. _this.url = url;
  75845. _this.extensions = extensions;
  75846. _this.noMipmap = noMipmap;
  75847. _this.files = files;
  75848. return _this;
  75849. }
  75850. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75851. var onload = function () {
  75852. onSuccess();
  75853. };
  75854. var onerror = function (message, exception) {
  75855. onError(message, exception);
  75856. };
  75857. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  75858. };
  75859. return CubeTextureAssetTask;
  75860. }(AbstractAssetTask));
  75861. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  75862. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  75863. __extends(HDRCubeTextureAssetTask, _super);
  75864. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75865. if (noMipmap === void 0) { noMipmap = false; }
  75866. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75867. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75868. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75869. var _this = _super.call(this, name) || this;
  75870. _this.name = name;
  75871. _this.url = url;
  75872. _this.size = size;
  75873. _this.noMipmap = noMipmap;
  75874. _this.generateHarmonics = generateHarmonics;
  75875. _this.useInGammaSpace = useInGammaSpace;
  75876. _this.usePMREMGenerator = usePMREMGenerator;
  75877. return _this;
  75878. }
  75879. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75880. var onload = function () {
  75881. onSuccess();
  75882. };
  75883. var onerror = function (message, exception) {
  75884. onError(message, exception);
  75885. };
  75886. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  75887. };
  75888. return HDRCubeTextureAssetTask;
  75889. }(AbstractAssetTask));
  75890. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  75891. var AssetsManager = /** @class */ (function () {
  75892. function AssetsManager(scene) {
  75893. this.tasks = new Array();
  75894. this.waitingTasksCount = 0;
  75895. //Observables
  75896. this.onTaskSuccessObservable = new BABYLON.Observable();
  75897. this.onTaskErrorObservable = new BABYLON.Observable();
  75898. this.onTasksDoneObservable = new BABYLON.Observable();
  75899. this.onProgressObservable = new BABYLON.Observable();
  75900. this.useDefaultLoadingScreen = true;
  75901. this._scene = scene;
  75902. }
  75903. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  75904. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  75905. this.tasks.push(task);
  75906. return task;
  75907. };
  75908. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  75909. var task = new TextFileAssetTask(taskName, url);
  75910. this.tasks.push(task);
  75911. return task;
  75912. };
  75913. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  75914. var task = new BinaryFileAssetTask(taskName, url);
  75915. this.tasks.push(task);
  75916. return task;
  75917. };
  75918. AssetsManager.prototype.addImageTask = function (taskName, url) {
  75919. var task = new ImageAssetTask(taskName, url);
  75920. this.tasks.push(task);
  75921. return task;
  75922. };
  75923. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  75924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75925. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  75926. this.tasks.push(task);
  75927. return task;
  75928. };
  75929. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  75930. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  75931. this.tasks.push(task);
  75932. return task;
  75933. };
  75934. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75935. if (noMipmap === void 0) { noMipmap = false; }
  75936. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75937. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75938. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75939. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  75940. this.tasks.push(task);
  75941. return task;
  75942. };
  75943. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  75944. this.waitingTasksCount--;
  75945. try {
  75946. if (this.onProgress) {
  75947. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  75948. }
  75949. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  75950. }
  75951. catch (e) {
  75952. BABYLON.Tools.Error("Error running progress callbacks.");
  75953. console.log(e);
  75954. }
  75955. if (this.waitingTasksCount === 0) {
  75956. try {
  75957. if (this.onFinish) {
  75958. this.onFinish(this.tasks);
  75959. }
  75960. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75961. }
  75962. catch (e) {
  75963. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  75964. console.log(e);
  75965. }
  75966. this._scene.getEngine().hideLoadingUI();
  75967. }
  75968. };
  75969. AssetsManager.prototype._runTask = function (task) {
  75970. var _this = this;
  75971. var done = function () {
  75972. try {
  75973. if (_this.onTaskSuccess) {
  75974. _this.onTaskSuccess(task);
  75975. }
  75976. _this.onTaskSuccessObservable.notifyObservers(task);
  75977. _this._decreaseWaitingTasksCount(task);
  75978. }
  75979. catch (e) {
  75980. error("Error executing task success callbacks", e);
  75981. }
  75982. };
  75983. var error = function (message, exception) {
  75984. task.errorObject = task.errorObject || {
  75985. message: message,
  75986. exception: exception
  75987. };
  75988. if (_this.onTaskError) {
  75989. _this.onTaskError(task);
  75990. }
  75991. _this.onTaskErrorObservable.notifyObservers(task);
  75992. _this._decreaseWaitingTasksCount(task);
  75993. };
  75994. task.run(this._scene, done, error);
  75995. };
  75996. AssetsManager.prototype.reset = function () {
  75997. this.tasks = new Array();
  75998. return this;
  75999. };
  76000. AssetsManager.prototype.load = function () {
  76001. this.waitingTasksCount = this.tasks.length;
  76002. if (this.waitingTasksCount === 0) {
  76003. if (this.onFinish) {
  76004. this.onFinish(this.tasks);
  76005. }
  76006. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76007. return this;
  76008. }
  76009. if (this.useDefaultLoadingScreen) {
  76010. this._scene.getEngine().displayLoadingUI();
  76011. }
  76012. for (var index = 0; index < this.tasks.length; index++) {
  76013. var task = this.tasks[index];
  76014. this._runTask(task);
  76015. }
  76016. return this;
  76017. };
  76018. return AssetsManager;
  76019. }());
  76020. BABYLON.AssetsManager = AssetsManager;
  76021. })(BABYLON || (BABYLON = {}));
  76022. //# sourceMappingURL=babylon.assetsManager.js.map
  76023. var BABYLON;
  76024. (function (BABYLON) {
  76025. var serializedGeometries = [];
  76026. var serializeGeometry = function (geometry, serializationGeometries) {
  76027. if (serializedGeometries[geometry.id]) {
  76028. return;
  76029. }
  76030. if (geometry.doNotSerialize) {
  76031. return;
  76032. }
  76033. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  76034. serializationGeometries.boxes.push(geometry.serialize());
  76035. }
  76036. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  76037. serializationGeometries.spheres.push(geometry.serialize());
  76038. }
  76039. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  76040. serializationGeometries.cylinders.push(geometry.serialize());
  76041. }
  76042. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  76043. serializationGeometries.toruses.push(geometry.serialize());
  76044. }
  76045. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  76046. serializationGeometries.grounds.push(geometry.serialize());
  76047. }
  76048. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  76049. serializationGeometries.planes.push(geometry.serialize());
  76050. }
  76051. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  76052. serializationGeometries.torusKnots.push(geometry.serialize());
  76053. }
  76054. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  76055. throw new Error("Unknown primitive type");
  76056. }
  76057. else {
  76058. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  76059. }
  76060. serializedGeometries[geometry.id] = true;
  76061. };
  76062. var serializeMesh = function (mesh, serializationScene) {
  76063. var serializationObject = {};
  76064. // Geometry
  76065. var geometry = mesh._geometry;
  76066. if (geometry) {
  76067. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  76068. // 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
  76069. serializeGeometry(geometry, serializationScene.geometries);
  76070. }
  76071. }
  76072. // Custom
  76073. if (mesh.serialize) {
  76074. mesh.serialize(serializationObject);
  76075. }
  76076. return serializationObject;
  76077. };
  76078. var finalizeSingleMesh = function (mesh, serializationObject) {
  76079. //only works if the mesh is already loaded
  76080. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76081. //serialize material
  76082. if (mesh.material) {
  76083. if (mesh.material instanceof BABYLON.StandardMaterial) {
  76084. serializationObject.materials = serializationObject.materials || [];
  76085. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76086. serializationObject.materials.push(mesh.material.serialize());
  76087. }
  76088. }
  76089. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  76090. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  76091. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76092. serializationObject.multiMaterials.push(mesh.material.serialize());
  76093. }
  76094. }
  76095. }
  76096. //serialize geometry
  76097. var geometry = mesh._geometry;
  76098. if (geometry) {
  76099. if (!serializationObject.geometries) {
  76100. serializationObject.geometries = {};
  76101. serializationObject.geometries.boxes = [];
  76102. serializationObject.geometries.spheres = [];
  76103. serializationObject.geometries.cylinders = [];
  76104. serializationObject.geometries.toruses = [];
  76105. serializationObject.geometries.grounds = [];
  76106. serializationObject.geometries.planes = [];
  76107. serializationObject.geometries.torusKnots = [];
  76108. serializationObject.geometries.vertexData = [];
  76109. }
  76110. serializeGeometry(geometry, serializationObject.geometries);
  76111. }
  76112. // Skeletons
  76113. if (mesh.skeleton) {
  76114. serializationObject.skeletons = serializationObject.skeletons || [];
  76115. serializationObject.skeletons.push(mesh.skeleton.serialize());
  76116. }
  76117. //serialize the actual mesh
  76118. serializationObject.meshes = serializationObject.meshes || [];
  76119. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76120. }
  76121. };
  76122. var SceneSerializer = /** @class */ (function () {
  76123. function SceneSerializer() {
  76124. }
  76125. SceneSerializer.ClearCache = function () {
  76126. serializedGeometries = [];
  76127. };
  76128. SceneSerializer.Serialize = function (scene) {
  76129. var serializationObject = {};
  76130. SceneSerializer.ClearCache();
  76131. // Scene
  76132. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  76133. serializationObject.autoClear = scene.autoClear;
  76134. serializationObject.clearColor = scene.clearColor.asArray();
  76135. serializationObject.ambientColor = scene.ambientColor.asArray();
  76136. serializationObject.gravity = scene.gravity.asArray();
  76137. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  76138. serializationObject.workerCollisions = scene.workerCollisions;
  76139. // Fog
  76140. if (scene.fogMode && scene.fogMode !== 0) {
  76141. serializationObject.fogMode = scene.fogMode;
  76142. serializationObject.fogColor = scene.fogColor.asArray();
  76143. serializationObject.fogStart = scene.fogStart;
  76144. serializationObject.fogEnd = scene.fogEnd;
  76145. serializationObject.fogDensity = scene.fogDensity;
  76146. }
  76147. //Physics
  76148. if (scene.isPhysicsEnabled()) {
  76149. var physicEngine = scene.getPhysicsEngine();
  76150. if (physicEngine) {
  76151. serializationObject.physicsEnabled = true;
  76152. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  76153. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  76154. }
  76155. }
  76156. // Metadata
  76157. if (scene.metadata) {
  76158. serializationObject.metadata = scene.metadata;
  76159. }
  76160. // Morph targets
  76161. serializationObject.morphTargetManagers = [];
  76162. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  76163. var abstractMesh = _a[_i];
  76164. var manager = abstractMesh.morphTargetManager;
  76165. if (manager) {
  76166. serializationObject.morphTargetManagers.push(manager.serialize());
  76167. }
  76168. }
  76169. // Lights
  76170. serializationObject.lights = [];
  76171. var index;
  76172. var light;
  76173. for (index = 0; index < scene.lights.length; index++) {
  76174. light = scene.lights[index];
  76175. if (!light.doNotSerialize) {
  76176. serializationObject.lights.push(light.serialize());
  76177. }
  76178. }
  76179. // Cameras
  76180. serializationObject.cameras = [];
  76181. for (index = 0; index < scene.cameras.length; index++) {
  76182. var camera = scene.cameras[index];
  76183. if (!camera.doNotSerialize) {
  76184. serializationObject.cameras.push(camera.serialize());
  76185. }
  76186. }
  76187. if (scene.activeCamera) {
  76188. serializationObject.activeCameraID = scene.activeCamera.id;
  76189. }
  76190. // Animations
  76191. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  76192. // Materials
  76193. serializationObject.materials = [];
  76194. serializationObject.multiMaterials = [];
  76195. var material;
  76196. for (index = 0; index < scene.materials.length; index++) {
  76197. material = scene.materials[index];
  76198. if (!material.doNotSerialize) {
  76199. serializationObject.materials.push(material.serialize());
  76200. }
  76201. }
  76202. // MultiMaterials
  76203. serializationObject.multiMaterials = [];
  76204. for (index = 0; index < scene.multiMaterials.length; index++) {
  76205. var multiMaterial = scene.multiMaterials[index];
  76206. serializationObject.multiMaterials.push(multiMaterial.serialize());
  76207. }
  76208. // Skeletons
  76209. serializationObject.skeletons = [];
  76210. for (index = 0; index < scene.skeletons.length; index++) {
  76211. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  76212. }
  76213. // Transform nodes
  76214. serializationObject.transformNodes = [];
  76215. for (index = 0; index < scene.transformNodes.length; index++) {
  76216. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  76217. }
  76218. // Geometries
  76219. serializationObject.geometries = {};
  76220. serializationObject.geometries.boxes = [];
  76221. serializationObject.geometries.spheres = [];
  76222. serializationObject.geometries.cylinders = [];
  76223. serializationObject.geometries.toruses = [];
  76224. serializationObject.geometries.grounds = [];
  76225. serializationObject.geometries.planes = [];
  76226. serializationObject.geometries.torusKnots = [];
  76227. serializationObject.geometries.vertexData = [];
  76228. serializedGeometries = [];
  76229. var geometries = scene.getGeometries();
  76230. for (index = 0; index < geometries.length; index++) {
  76231. var geometry = geometries[index];
  76232. if (geometry.isReady()) {
  76233. serializeGeometry(geometry, serializationObject.geometries);
  76234. }
  76235. }
  76236. // Meshes
  76237. serializationObject.meshes = [];
  76238. for (index = 0; index < scene.meshes.length; index++) {
  76239. var abstractMesh = scene.meshes[index];
  76240. if (abstractMesh instanceof BABYLON.Mesh) {
  76241. var mesh = abstractMesh;
  76242. if (!mesh.doNotSerialize) {
  76243. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76244. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76245. }
  76246. }
  76247. }
  76248. }
  76249. // Particles Systems
  76250. serializationObject.particleSystems = [];
  76251. for (index = 0; index < scene.particleSystems.length; index++) {
  76252. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  76253. }
  76254. // Lens flares
  76255. serializationObject.lensFlareSystems = [];
  76256. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  76257. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  76258. }
  76259. // Shadows
  76260. serializationObject.shadowGenerators = [];
  76261. for (index = 0; index < scene.lights.length; index++) {
  76262. light = scene.lights[index];
  76263. var shadowGenerator = light.getShadowGenerator();
  76264. if (shadowGenerator) {
  76265. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76266. }
  76267. }
  76268. // Action Manager
  76269. if (scene.actionManager) {
  76270. serializationObject.actions = scene.actionManager.serialize("scene");
  76271. }
  76272. // Audio
  76273. serializationObject.sounds = [];
  76274. for (index = 0; index < scene.soundTracks.length; index++) {
  76275. var soundtrack = scene.soundTracks[index];
  76276. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  76277. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  76278. }
  76279. }
  76280. return serializationObject;
  76281. };
  76282. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  76283. if (withParents === void 0) { withParents = false; }
  76284. if (withChildren === void 0) { withChildren = false; }
  76285. var serializationObject = {};
  76286. SceneSerializer.ClearCache();
  76287. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  76288. if (withParents || withChildren) {
  76289. //deliberate for loop! not for each, appended should be processed as well.
  76290. for (var i = 0; i < toSerialize.length; ++i) {
  76291. if (withChildren) {
  76292. toSerialize[i].getDescendants().forEach(function (node) {
  76293. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  76294. toSerialize.push(node);
  76295. }
  76296. });
  76297. }
  76298. //make sure the array doesn't contain the object already
  76299. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  76300. toSerialize.push(toSerialize[i].parent);
  76301. }
  76302. }
  76303. }
  76304. toSerialize.forEach(function (mesh) {
  76305. finalizeSingleMesh(mesh, serializationObject);
  76306. });
  76307. return serializationObject;
  76308. };
  76309. return SceneSerializer;
  76310. }());
  76311. BABYLON.SceneSerializer = SceneSerializer;
  76312. })(BABYLON || (BABYLON = {}));
  76313. //# sourceMappingURL=babylon.sceneSerializer.js.map
  76314. var BABYLON;
  76315. (function (BABYLON) {
  76316. var ReflectionProbe = /** @class */ (function () {
  76317. function ReflectionProbe(name, size, scene, generateMipMaps) {
  76318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76319. var _this = this;
  76320. this.name = name;
  76321. this._viewMatrix = BABYLON.Matrix.Identity();
  76322. this._target = BABYLON.Vector3.Zero();
  76323. this._add = BABYLON.Vector3.Zero();
  76324. this.invertYAxis = false;
  76325. this.position = BABYLON.Vector3.Zero();
  76326. this._scene = scene;
  76327. this._scene.reflectionProbes.push(this);
  76328. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  76329. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  76330. switch (faceIndex) {
  76331. case 0:
  76332. _this._add.copyFromFloats(1, 0, 0);
  76333. break;
  76334. case 1:
  76335. _this._add.copyFromFloats(-1, 0, 0);
  76336. break;
  76337. case 2:
  76338. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  76339. break;
  76340. case 3:
  76341. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  76342. break;
  76343. case 4:
  76344. _this._add.copyFromFloats(0, 0, 1);
  76345. break;
  76346. case 5:
  76347. _this._add.copyFromFloats(0, 0, -1);
  76348. break;
  76349. }
  76350. if (_this._attachedMesh) {
  76351. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  76352. }
  76353. _this.position.addToRef(_this._add, _this._target);
  76354. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  76355. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  76356. scene._forcedViewPosition = _this.position;
  76357. });
  76358. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  76359. scene._forcedViewPosition = null;
  76360. scene.updateTransformMatrix(true);
  76361. });
  76362. if (scene.activeCamera) {
  76363. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76364. }
  76365. }
  76366. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  76367. get: function () {
  76368. return this._renderTargetTexture.samples;
  76369. },
  76370. set: function (value) {
  76371. this._renderTargetTexture.samples = value;
  76372. },
  76373. enumerable: true,
  76374. configurable: true
  76375. });
  76376. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  76377. get: function () {
  76378. return this._renderTargetTexture.refreshRate;
  76379. },
  76380. set: function (value) {
  76381. this._renderTargetTexture.refreshRate = value;
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. ReflectionProbe.prototype.getScene = function () {
  76387. return this._scene;
  76388. };
  76389. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  76390. get: function () {
  76391. return this._renderTargetTexture;
  76392. },
  76393. enumerable: true,
  76394. configurable: true
  76395. });
  76396. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  76397. get: function () {
  76398. return this._renderTargetTexture.renderList;
  76399. },
  76400. enumerable: true,
  76401. configurable: true
  76402. });
  76403. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  76404. this._attachedMesh = mesh;
  76405. };
  76406. /**
  76407. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  76408. *
  76409. * @param renderingGroupId The rendering group id corresponding to its index
  76410. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  76411. */
  76412. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  76413. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  76414. };
  76415. ReflectionProbe.prototype.dispose = function () {
  76416. var index = this._scene.reflectionProbes.indexOf(this);
  76417. if (index !== -1) {
  76418. // Remove from the scene if found
  76419. this._scene.reflectionProbes.splice(index, 1);
  76420. }
  76421. if (this._renderTargetTexture) {
  76422. this._renderTargetTexture.dispose();
  76423. this._renderTargetTexture = null;
  76424. }
  76425. };
  76426. return ReflectionProbe;
  76427. }());
  76428. BABYLON.ReflectionProbe = ReflectionProbe;
  76429. })(BABYLON || (BABYLON = {}));
  76430. //# sourceMappingURL=babylon.reflectionProbe.js.map
  76431. var BABYLON;
  76432. (function (BABYLON) {
  76433. var Layer = /** @class */ (function () {
  76434. function Layer(name, imgUrl, scene, isBackground, color) {
  76435. this.name = name;
  76436. this.scale = new BABYLON.Vector2(1, 1);
  76437. this.offset = new BABYLON.Vector2(0, 0);
  76438. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  76439. this.layerMask = 0x0FFFFFFF;
  76440. this._vertexBuffers = {};
  76441. // Events
  76442. /**
  76443. * An event triggered when the layer is disposed.
  76444. * @type {BABYLON.Observable}
  76445. */
  76446. this.onDisposeObservable = new BABYLON.Observable();
  76447. /**
  76448. * An event triggered before rendering the scene
  76449. * @type {BABYLON.Observable}
  76450. */
  76451. this.onBeforeRenderObservable = new BABYLON.Observable();
  76452. /**
  76453. * An event triggered after rendering the scene
  76454. * @type {BABYLON.Observable}
  76455. */
  76456. this.onAfterRenderObservable = new BABYLON.Observable();
  76457. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  76458. this.isBackground = isBackground === undefined ? true : isBackground;
  76459. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  76460. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  76461. this._scene.layers.push(this);
  76462. var engine = this._scene.getEngine();
  76463. // VBO
  76464. var vertices = [];
  76465. vertices.push(1, 1);
  76466. vertices.push(-1, 1);
  76467. vertices.push(-1, -1);
  76468. vertices.push(1, -1);
  76469. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76470. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76471. this._createIndexBuffer();
  76472. // Effects
  76473. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  76474. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  76475. }
  76476. Object.defineProperty(Layer.prototype, "onDispose", {
  76477. set: function (callback) {
  76478. if (this._onDisposeObserver) {
  76479. this.onDisposeObservable.remove(this._onDisposeObserver);
  76480. }
  76481. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  76482. },
  76483. enumerable: true,
  76484. configurable: true
  76485. });
  76486. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  76487. set: function (callback) {
  76488. if (this._onBeforeRenderObserver) {
  76489. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  76490. }
  76491. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  76492. },
  76493. enumerable: true,
  76494. configurable: true
  76495. });
  76496. Object.defineProperty(Layer.prototype, "onAfterRender", {
  76497. set: function (callback) {
  76498. if (this._onAfterRenderObserver) {
  76499. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76500. }
  76501. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  76502. },
  76503. enumerable: true,
  76504. configurable: true
  76505. });
  76506. Layer.prototype._createIndexBuffer = function () {
  76507. var engine = this._scene.getEngine();
  76508. // Indices
  76509. var indices = [];
  76510. indices.push(0);
  76511. indices.push(1);
  76512. indices.push(2);
  76513. indices.push(0);
  76514. indices.push(2);
  76515. indices.push(3);
  76516. this._indexBuffer = engine.createIndexBuffer(indices);
  76517. };
  76518. Layer.prototype._rebuild = function () {
  76519. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76520. if (vb) {
  76521. vb._rebuild();
  76522. }
  76523. this._createIndexBuffer();
  76524. };
  76525. Layer.prototype.render = function () {
  76526. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  76527. // Check
  76528. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  76529. return;
  76530. var engine = this._scene.getEngine();
  76531. this.onBeforeRenderObservable.notifyObservers(this);
  76532. // Render
  76533. engine.enableEffect(currentEffect);
  76534. engine.setState(false);
  76535. // Texture
  76536. currentEffect.setTexture("textureSampler", this.texture);
  76537. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  76538. // Color
  76539. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  76540. // Scale / offset
  76541. currentEffect.setVector2("offset", this.offset);
  76542. currentEffect.setVector2("scale", this.scale);
  76543. // VBOs
  76544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76545. // Draw order
  76546. if (!this.alphaTest) {
  76547. engine.setAlphaMode(this.alphaBlendingMode);
  76548. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76549. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76550. }
  76551. else {
  76552. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76553. }
  76554. this.onAfterRenderObservable.notifyObservers(this);
  76555. };
  76556. Layer.prototype.dispose = function () {
  76557. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76558. if (vertexBuffer) {
  76559. vertexBuffer.dispose();
  76560. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76561. }
  76562. if (this._indexBuffer) {
  76563. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76564. this._indexBuffer = null;
  76565. }
  76566. if (this.texture) {
  76567. this.texture.dispose();
  76568. this.texture = null;
  76569. }
  76570. // Remove from scene
  76571. var index = this._scene.layers.indexOf(this);
  76572. this._scene.layers.splice(index, 1);
  76573. // Callback
  76574. this.onDisposeObservable.notifyObservers(this);
  76575. this.onDisposeObservable.clear();
  76576. this.onAfterRenderObservable.clear();
  76577. this.onBeforeRenderObservable.clear();
  76578. };
  76579. return Layer;
  76580. }());
  76581. BABYLON.Layer = Layer;
  76582. })(BABYLON || (BABYLON = {}));
  76583. //# sourceMappingURL=babylon.layer.js.map
  76584. var BABYLON;
  76585. (function (BABYLON) {
  76586. var TextureTools = /** @class */ (function () {
  76587. function TextureTools() {
  76588. }
  76589. /**
  76590. * Uses the GPU to create a copy texture rescaled at a given size
  76591. * @param texture Texture to copy from
  76592. * @param width Desired width
  76593. * @param height Desired height
  76594. * @return Generated texture
  76595. */
  76596. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  76597. if (useBilinearMode === void 0) { useBilinearMode = true; }
  76598. var scene = texture.getScene();
  76599. var engine = scene.getEngine();
  76600. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  76601. rtt.wrapU = texture.wrapU;
  76602. rtt.wrapV = texture.wrapV;
  76603. rtt.uOffset = texture.uOffset;
  76604. rtt.vOffset = texture.vOffset;
  76605. rtt.uScale = texture.uScale;
  76606. rtt.vScale = texture.vScale;
  76607. rtt.uAng = texture.uAng;
  76608. rtt.vAng = texture.vAng;
  76609. rtt.wAng = texture.wAng;
  76610. rtt.coordinatesIndex = texture.coordinatesIndex;
  76611. rtt.level = texture.level;
  76612. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  76613. rtt._texture.isReady = false;
  76614. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76615. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76616. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76617. passPostProcess.getEffect().executeWhenCompiled(function () {
  76618. passPostProcess.onApply = function (effect) {
  76619. effect.setTexture("textureSampler", texture);
  76620. };
  76621. var internalTexture = rtt.getInternalTexture();
  76622. if (internalTexture) {
  76623. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  76624. engine.unBindFramebuffer(internalTexture);
  76625. rtt.disposeFramebufferObjects();
  76626. passPostProcess.dispose();
  76627. internalTexture.isReady = true;
  76628. }
  76629. });
  76630. return rtt;
  76631. };
  76632. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  76633. if (!scene._environmentBRDFTexture) {
  76634. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76635. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76636. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76637. scene._environmentBRDFTexture = texture;
  76638. }
  76639. return scene._environmentBRDFTexture;
  76640. };
  76641. 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=";
  76642. return TextureTools;
  76643. }());
  76644. BABYLON.TextureTools = TextureTools;
  76645. })(BABYLON || (BABYLON = {}));
  76646. //# sourceMappingURL=babylon.textureTools.js.map
  76647. var BABYLON;
  76648. (function (BABYLON) {
  76649. var FramingBehavior = /** @class */ (function () {
  76650. function FramingBehavior() {
  76651. this._mode = FramingBehavior.FitFrustumSidesMode;
  76652. this._radiusScale = 1.0;
  76653. this._positionScale = 0.5;
  76654. this._defaultElevation = 0.3;
  76655. this._elevationReturnTime = 1500;
  76656. this._elevationReturnWaitTime = 1000;
  76657. this._zoomStopsAnimation = false;
  76658. this._framingTime = 1500;
  76659. this._isPointerDown = false;
  76660. this._lastInteractionTime = -Infinity;
  76661. // Framing control
  76662. this._animatables = new Array();
  76663. this._betaIsAnimating = false;
  76664. }
  76665. Object.defineProperty(FramingBehavior.prototype, "name", {
  76666. get: function () {
  76667. return "Framing";
  76668. },
  76669. enumerable: true,
  76670. configurable: true
  76671. });
  76672. Object.defineProperty(FramingBehavior.prototype, "mode", {
  76673. /**
  76674. * Gets current mode used by the behavior.
  76675. */
  76676. get: function () {
  76677. return this._mode;
  76678. },
  76679. /**
  76680. * Sets the current mode used by the behavior
  76681. */
  76682. set: function (mode) {
  76683. this._mode = mode;
  76684. },
  76685. enumerable: true,
  76686. configurable: true
  76687. });
  76688. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  76689. /**
  76690. * Gets the scale applied to the radius
  76691. */
  76692. get: function () {
  76693. return this._radiusScale;
  76694. },
  76695. /**
  76696. * Sets the scale applied to the radius (1 by default)
  76697. */
  76698. set: function (radius) {
  76699. this._radiusScale = radius;
  76700. },
  76701. enumerable: true,
  76702. configurable: true
  76703. });
  76704. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  76705. /**
  76706. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  76707. */
  76708. get: function () {
  76709. return this._positionScale;
  76710. },
  76711. /**
  76712. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  76713. */
  76714. set: function (scale) {
  76715. this._positionScale = scale;
  76716. },
  76717. enumerable: true,
  76718. configurable: true
  76719. });
  76720. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  76721. /**
  76722. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  76723. * behaviour is triggered, in radians.
  76724. */
  76725. get: function () {
  76726. return this._defaultElevation;
  76727. },
  76728. /**
  76729. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  76730. * behaviour is triggered, in radians.
  76731. */
  76732. set: function (elevation) {
  76733. this._defaultElevation = elevation;
  76734. },
  76735. enumerable: true,
  76736. configurable: true
  76737. });
  76738. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  76739. /**
  76740. * Gets the time (in milliseconds) taken to return to the default beta position.
  76741. * Negative value indicates camera should not return to default.
  76742. */
  76743. get: function () {
  76744. return this._elevationReturnTime;
  76745. },
  76746. /**
  76747. * Sets the time (in milliseconds) taken to return to the default beta position.
  76748. * Negative value indicates camera should not return to default.
  76749. */
  76750. set: function (speed) {
  76751. this._elevationReturnTime = speed;
  76752. },
  76753. enumerable: true,
  76754. configurable: true
  76755. });
  76756. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  76757. /**
  76758. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  76759. */
  76760. get: function () {
  76761. return this._elevationReturnWaitTime;
  76762. },
  76763. /**
  76764. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  76765. */
  76766. set: function (time) {
  76767. this._elevationReturnWaitTime = time;
  76768. },
  76769. enumerable: true,
  76770. configurable: true
  76771. });
  76772. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  76773. /**
  76774. * Gets the flag that indicates if user zooming should stop animation.
  76775. */
  76776. get: function () {
  76777. return this._zoomStopsAnimation;
  76778. },
  76779. /**
  76780. * Sets the flag that indicates if user zooming should stop animation.
  76781. */
  76782. set: function (flag) {
  76783. this._zoomStopsAnimation = flag;
  76784. },
  76785. enumerable: true,
  76786. configurable: true
  76787. });
  76788. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  76789. /**
  76790. * Gets the transition time when framing the mesh, in milliseconds
  76791. */
  76792. get: function () {
  76793. return this._framingTime;
  76794. },
  76795. /**
  76796. * Sets the transition time when framing the mesh, in milliseconds
  76797. */
  76798. set: function (time) {
  76799. this._framingTime = time;
  76800. },
  76801. enumerable: true,
  76802. configurable: true
  76803. });
  76804. FramingBehavior.prototype.init = function () {
  76805. // Do notihng
  76806. };
  76807. FramingBehavior.prototype.attach = function (camera) {
  76808. var _this = this;
  76809. this._attachedCamera = camera;
  76810. var scene = this._attachedCamera.getScene();
  76811. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  76812. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76813. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76814. _this._isPointerDown = true;
  76815. return;
  76816. }
  76817. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76818. _this._isPointerDown = false;
  76819. }
  76820. });
  76821. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76822. if (mesh) {
  76823. _this.zoomOnMesh(mesh);
  76824. }
  76825. });
  76826. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76827. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76828. _this._applyUserInteraction();
  76829. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  76830. // back to the default position after a given timeout
  76831. _this._maintainCameraAboveGround();
  76832. });
  76833. };
  76834. FramingBehavior.prototype.detach = function () {
  76835. if (!this._attachedCamera) {
  76836. return;
  76837. }
  76838. var scene = this._attachedCamera.getScene();
  76839. if (this._onPrePointerObservableObserver) {
  76840. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76841. }
  76842. if (this._onAfterCheckInputsObserver) {
  76843. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76844. }
  76845. if (this._onMeshTargetChangedObserver) {
  76846. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76847. }
  76848. this._attachedCamera = null;
  76849. };
  76850. /**
  76851. * Targets the given mesh and updates zoom level accordingly.
  76852. * @param mesh The mesh to target.
  76853. * @param radius Optional. If a cached radius position already exists, overrides default.
  76854. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76855. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76856. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76857. */
  76858. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76859. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76860. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76861. mesh.computeWorldMatrix(true);
  76862. var boundingBox = mesh.getBoundingInfo().boundingBox;
  76863. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  76864. };
  76865. /**
  76866. * Targets the given mesh with its children and updates zoom level accordingly.
  76867. * @param mesh The mesh to target.
  76868. * @param radius Optional. If a cached radius position already exists, overrides default.
  76869. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76870. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76871. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76872. */
  76873. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76874. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76875. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76876. mesh.computeWorldMatrix(true);
  76877. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  76878. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  76879. };
  76880. /**
  76881. * Targets the given meshes with their children and updates zoom level accordingly.
  76882. * @param meshes The mesh to target.
  76883. * @param radius Optional. If a cached radius position already exists, overrides default.
  76884. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76885. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76886. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76887. */
  76888. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  76889. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76890. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76891. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76892. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  76893. for (var i = 0; i < meshes.length; i++) {
  76894. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  76895. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  76896. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  76897. }
  76898. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  76899. };
  76900. /**
  76901. * Targets the given mesh and updates zoom level accordingly.
  76902. * @param mesh The mesh to target.
  76903. * @param radius Optional. If a cached radius position already exists, overrides default.
  76904. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76905. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76906. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76907. */
  76908. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  76909. var _this = this;
  76910. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76911. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76912. var zoomTarget;
  76913. if (!this._attachedCamera) {
  76914. return;
  76915. }
  76916. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  76917. var bottom = minimumWorld.y;
  76918. var top = maximumWorld.y;
  76919. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  76920. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  76921. if (focusOnOriginXZ) {
  76922. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  76923. }
  76924. else {
  76925. var centerWorld = minimumWorld.add(radiusWorld);
  76926. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  76927. }
  76928. if (!this._vectorTransition) {
  76929. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  76930. }
  76931. this._betaIsAnimating = true;
  76932. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  76933. if (animatable) {
  76934. this._animatables.push(animatable);
  76935. }
  76936. // sets the radius and lower radius bounds
  76937. // Small delta ensures camera is not always at lower zoom limit.
  76938. var radius = 0;
  76939. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  76940. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76941. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  76942. radius = position;
  76943. }
  76944. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76945. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76946. if (this._attachedCamera.lowerRadiusLimit === null) {
  76947. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  76948. }
  76949. }
  76950. // Set sensibilities
  76951. var extend = maximumWorld.subtract(minimumWorld).length();
  76952. this._attachedCamera.panningSensibility = 5000 / extend;
  76953. this._attachedCamera.wheelPrecision = 100 / radius;
  76954. // transition to new radius
  76955. if (!this._radiusTransition) {
  76956. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76957. }
  76958. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  76959. if (onAnimationEnd) {
  76960. onAnimationEnd();
  76961. }
  76962. if (_this._attachedCamera) {
  76963. _this._attachedCamera.storeState();
  76964. }
  76965. });
  76966. if (animatable) {
  76967. this._animatables.push(animatable);
  76968. }
  76969. };
  76970. /**
  76971. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  76972. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  76973. * frustum width.
  76974. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  76975. * to fully enclose the mesh in the viewing frustum.
  76976. */
  76977. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  76978. var size = maximumWorld.subtract(minimumWorld);
  76979. var boxVectorGlobalDiagonal = size.length();
  76980. var frustumSlope = this._getFrustumSlope();
  76981. // Formula for setting distance
  76982. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  76983. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  76984. // Horizon distance
  76985. var radius = radiusWithoutFraming * this._radiusScale;
  76986. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  76987. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  76988. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  76989. var camera = this._attachedCamera;
  76990. if (!camera) {
  76991. return 0;
  76992. }
  76993. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76994. // Don't exceed the requested limit
  76995. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  76996. }
  76997. // Don't exceed the upper radius limit
  76998. if (camera.upperRadiusLimit) {
  76999. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  77000. }
  77001. return distance;
  77002. };
  77003. /**
  77004. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  77005. * is automatically returned to its default position (expected to be above ground plane).
  77006. */
  77007. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  77008. var _this = this;
  77009. if (this._elevationReturnTime < 0) {
  77010. return;
  77011. }
  77012. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  77013. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  77014. var limitBeta = Math.PI * 0.5;
  77015. // Bring the camera back up if below the ground plane
  77016. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  77017. this._betaIsAnimating = true;
  77018. //Transition to new position
  77019. this.stopAllAnimations();
  77020. if (!this._betaTransition) {
  77021. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77022. }
  77023. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  77024. _this._clearAnimationLocks();
  77025. _this.stopAllAnimations();
  77026. });
  77027. if (animatabe) {
  77028. this._animatables.push(animatabe);
  77029. }
  77030. }
  77031. };
  77032. /**
  77033. * Returns the frustum slope based on the canvas ratio and camera FOV
  77034. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  77035. */
  77036. FramingBehavior.prototype._getFrustumSlope = function () {
  77037. // Calculate the viewport ratio
  77038. // Aspect Ratio is Height/Width.
  77039. var camera = this._attachedCamera;
  77040. if (!camera) {
  77041. return BABYLON.Vector2.Zero();
  77042. }
  77043. var engine = camera.getScene().getEngine();
  77044. var aspectRatio = engine.getAspectRatio(camera);
  77045. // Camera FOV is the vertical field of view (top-bottom) in radians.
  77046. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  77047. var frustumSlopeY = Math.tan(camera.fov / 2);
  77048. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  77049. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  77050. // along the forward vector.
  77051. var frustumSlopeX = frustumSlopeY * aspectRatio;
  77052. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  77053. };
  77054. /**
  77055. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  77056. */
  77057. FramingBehavior.prototype._clearAnimationLocks = function () {
  77058. this._betaIsAnimating = false;
  77059. };
  77060. /**
  77061. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77062. */
  77063. FramingBehavior.prototype._applyUserInteraction = function () {
  77064. if (this.isUserIsMoving) {
  77065. this._lastInteractionTime = BABYLON.Tools.Now;
  77066. this.stopAllAnimations();
  77067. this._clearAnimationLocks();
  77068. }
  77069. };
  77070. /**
  77071. * Stops and removes all animations that have been applied to the camera
  77072. */
  77073. FramingBehavior.prototype.stopAllAnimations = function () {
  77074. if (this._attachedCamera) {
  77075. this._attachedCamera.animations = [];
  77076. }
  77077. while (this._animatables.length) {
  77078. if (this._animatables[0]) {
  77079. this._animatables[0].onAnimationEnd = null;
  77080. this._animatables[0].stop();
  77081. }
  77082. this._animatables.shift();
  77083. }
  77084. };
  77085. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  77086. /**
  77087. * Gets a value indicating if the user is moving the camera
  77088. */
  77089. get: function () {
  77090. if (!this._attachedCamera) {
  77091. return false;
  77092. }
  77093. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77094. this._attachedCamera.inertialBetaOffset !== 0 ||
  77095. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77096. this._attachedCamera.inertialPanningX !== 0 ||
  77097. this._attachedCamera.inertialPanningY !== 0 ||
  77098. this._isPointerDown;
  77099. },
  77100. enumerable: true,
  77101. configurable: true
  77102. });
  77103. /**
  77104. * The easing function used by animations
  77105. */
  77106. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  77107. /**
  77108. * The easing mode used by animations
  77109. */
  77110. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  77111. // Statics
  77112. /**
  77113. * The camera can move all the way towards the mesh.
  77114. */
  77115. FramingBehavior.IgnoreBoundsSizeMode = 0;
  77116. /**
  77117. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  77118. */
  77119. FramingBehavior.FitFrustumSidesMode = 1;
  77120. return FramingBehavior;
  77121. }());
  77122. BABYLON.FramingBehavior = FramingBehavior;
  77123. })(BABYLON || (BABYLON = {}));
  77124. //# sourceMappingURL=babylon.framingBehavior.js.map
  77125. var BABYLON;
  77126. (function (BABYLON) {
  77127. /**
  77128. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  77129. */
  77130. var BouncingBehavior = /** @class */ (function () {
  77131. function BouncingBehavior() {
  77132. /**
  77133. * The duration of the animation, in milliseconds
  77134. */
  77135. this.transitionDuration = 450;
  77136. /**
  77137. * Length of the distance animated by the transition when lower radius is reached
  77138. */
  77139. this.lowerRadiusTransitionRange = 2;
  77140. /**
  77141. * Length of the distance animated by the transition when upper radius is reached
  77142. */
  77143. this.upperRadiusTransitionRange = -2;
  77144. this._autoTransitionRange = false;
  77145. // Animations
  77146. this._radiusIsAnimating = false;
  77147. this._radiusBounceTransition = null;
  77148. this._animatables = new Array();
  77149. }
  77150. Object.defineProperty(BouncingBehavior.prototype, "name", {
  77151. get: function () {
  77152. return "Bouncing";
  77153. },
  77154. enumerable: true,
  77155. configurable: true
  77156. });
  77157. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  77158. /**
  77159. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77160. */
  77161. get: function () {
  77162. return this._autoTransitionRange;
  77163. },
  77164. /**
  77165. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77166. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  77167. */
  77168. set: function (value) {
  77169. var _this = this;
  77170. if (this._autoTransitionRange === value) {
  77171. return;
  77172. }
  77173. this._autoTransitionRange = value;
  77174. var camera = this._attachedCamera;
  77175. if (!camera) {
  77176. return;
  77177. }
  77178. if (value) {
  77179. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77180. if (!mesh) {
  77181. return;
  77182. }
  77183. mesh.computeWorldMatrix(true);
  77184. var diagonal = mesh.getBoundingInfo().diagonalLength;
  77185. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  77186. _this.upperRadiusTransitionRange = diagonal * 0.05;
  77187. });
  77188. }
  77189. else if (this._onMeshTargetChangedObserver) {
  77190. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77191. }
  77192. },
  77193. enumerable: true,
  77194. configurable: true
  77195. });
  77196. BouncingBehavior.prototype.init = function () {
  77197. // Do notihng
  77198. };
  77199. BouncingBehavior.prototype.attach = function (camera) {
  77200. var _this = this;
  77201. this._attachedCamera = camera;
  77202. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77203. if (!_this._attachedCamera) {
  77204. return;
  77205. }
  77206. // Add the bounce animation to the lower radius limit
  77207. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  77208. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  77209. }
  77210. // Add the bounce animation to the upper radius limit
  77211. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  77212. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  77213. }
  77214. });
  77215. };
  77216. BouncingBehavior.prototype.detach = function () {
  77217. if (!this._attachedCamera) {
  77218. return;
  77219. }
  77220. if (this._onAfterCheckInputsObserver) {
  77221. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77222. }
  77223. if (this._onMeshTargetChangedObserver) {
  77224. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77225. }
  77226. this._attachedCamera = null;
  77227. };
  77228. /**
  77229. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  77230. * @param radiusLimit The limit to check against.
  77231. * @return Bool to indicate if at limit.
  77232. */
  77233. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  77234. if (!this._attachedCamera) {
  77235. return false;
  77236. }
  77237. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  77238. return true;
  77239. }
  77240. return false;
  77241. };
  77242. /**
  77243. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  77244. * @param radiusDelta The delta by which to animate to. Can be negative.
  77245. */
  77246. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  77247. var _this = this;
  77248. if (!this._attachedCamera) {
  77249. return;
  77250. }
  77251. if (!this._radiusBounceTransition) {
  77252. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  77253. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  77254. }
  77255. // Prevent zoom until bounce has completed
  77256. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  77257. this._attachedCamera.wheelPrecision = Infinity;
  77258. this._attachedCamera.inertialRadiusOffset = 0;
  77259. // Animate to the radius limit
  77260. this.stopAllAnimations();
  77261. this._radiusIsAnimating = true;
  77262. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  77263. if (animatable) {
  77264. this._animatables.push(animatable);
  77265. }
  77266. };
  77267. /**
  77268. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  77269. */
  77270. BouncingBehavior.prototype._clearAnimationLocks = function () {
  77271. this._radiusIsAnimating = false;
  77272. if (this._attachedCamera) {
  77273. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  77274. }
  77275. };
  77276. /**
  77277. * Stops and removes all animations that have been applied to the camera
  77278. */
  77279. BouncingBehavior.prototype.stopAllAnimations = function () {
  77280. if (this._attachedCamera) {
  77281. this._attachedCamera.animations = [];
  77282. }
  77283. while (this._animatables.length) {
  77284. this._animatables[0].onAnimationEnd = null;
  77285. this._animatables[0].stop();
  77286. this._animatables.shift();
  77287. }
  77288. };
  77289. /**
  77290. * The easing function used by animations
  77291. */
  77292. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  77293. /**
  77294. * The easing mode used by animations
  77295. */
  77296. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  77297. return BouncingBehavior;
  77298. }());
  77299. BABYLON.BouncingBehavior = BouncingBehavior;
  77300. })(BABYLON || (BABYLON = {}));
  77301. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  77302. var BABYLON;
  77303. (function (BABYLON) {
  77304. var AutoRotationBehavior = /** @class */ (function () {
  77305. function AutoRotationBehavior() {
  77306. this._zoomStopsAnimation = false;
  77307. this._idleRotationSpeed = 0.05;
  77308. this._idleRotationWaitTime = 2000;
  77309. this._idleRotationSpinupTime = 2000;
  77310. this._isPointerDown = false;
  77311. this._lastFrameTime = null;
  77312. this._lastInteractionTime = -Infinity;
  77313. this._cameraRotationSpeed = 0;
  77314. this._lastFrameRadius = 0;
  77315. }
  77316. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  77317. get: function () {
  77318. return "AutoRotation";
  77319. },
  77320. enumerable: true,
  77321. configurable: true
  77322. });
  77323. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  77324. /**
  77325. * Gets the flag that indicates if user zooming should stop animation.
  77326. */
  77327. get: function () {
  77328. return this._zoomStopsAnimation;
  77329. },
  77330. /**
  77331. * Sets the flag that indicates if user zooming should stop animation.
  77332. */
  77333. set: function (flag) {
  77334. this._zoomStopsAnimation = flag;
  77335. },
  77336. enumerable: true,
  77337. configurable: true
  77338. });
  77339. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  77340. /**
  77341. * Gets the default speed at which the camera rotates around the model.
  77342. */
  77343. get: function () {
  77344. return this._idleRotationSpeed;
  77345. },
  77346. /**
  77347. * Sets the default speed at which the camera rotates around the model.
  77348. */
  77349. set: function (speed) {
  77350. this._idleRotationSpeed = speed;
  77351. },
  77352. enumerable: true,
  77353. configurable: true
  77354. });
  77355. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  77356. /**
  77357. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  77358. */
  77359. get: function () {
  77360. return this._idleRotationWaitTime;
  77361. },
  77362. /**
  77363. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  77364. */
  77365. set: function (time) {
  77366. this._idleRotationWaitTime = time;
  77367. },
  77368. enumerable: true,
  77369. configurable: true
  77370. });
  77371. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  77372. /**
  77373. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77374. */
  77375. get: function () {
  77376. return this._idleRotationSpinupTime;
  77377. },
  77378. /**
  77379. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77380. */
  77381. set: function (time) {
  77382. this._idleRotationSpinupTime = time;
  77383. },
  77384. enumerable: true,
  77385. configurable: true
  77386. });
  77387. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  77388. /**
  77389. * Gets a value indicating if the camera is currently rotating because of this behavior
  77390. */
  77391. get: function () {
  77392. return Math.abs(this._cameraRotationSpeed) > 0;
  77393. },
  77394. enumerable: true,
  77395. configurable: true
  77396. });
  77397. AutoRotationBehavior.prototype.init = function () {
  77398. // Do notihng
  77399. };
  77400. AutoRotationBehavior.prototype.attach = function (camera) {
  77401. var _this = this;
  77402. this._attachedCamera = camera;
  77403. var scene = this._attachedCamera.getScene();
  77404. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77405. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77406. _this._isPointerDown = true;
  77407. return;
  77408. }
  77409. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77410. _this._isPointerDown = false;
  77411. }
  77412. });
  77413. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77414. var now = BABYLON.Tools.Now;
  77415. var dt = 0;
  77416. if (_this._lastFrameTime != null) {
  77417. dt = now - _this._lastFrameTime;
  77418. }
  77419. _this._lastFrameTime = now;
  77420. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77421. _this._applyUserInteraction();
  77422. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  77423. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  77424. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  77425. // Step camera rotation by rotation speed
  77426. if (_this._attachedCamera) {
  77427. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  77428. }
  77429. });
  77430. };
  77431. AutoRotationBehavior.prototype.detach = function () {
  77432. if (!this._attachedCamera) {
  77433. return;
  77434. }
  77435. var scene = this._attachedCamera.getScene();
  77436. if (this._onPrePointerObservableObserver) {
  77437. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77438. }
  77439. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77440. this._attachedCamera = null;
  77441. };
  77442. /**
  77443. * Returns true if user is scrolling.
  77444. * @return true if user is scrolling.
  77445. */
  77446. AutoRotationBehavior.prototype._userIsZooming = function () {
  77447. if (!this._attachedCamera) {
  77448. return false;
  77449. }
  77450. return this._attachedCamera.inertialRadiusOffset !== 0;
  77451. };
  77452. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  77453. if (!this._attachedCamera) {
  77454. return false;
  77455. }
  77456. var zoomHasHitLimit = false;
  77457. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  77458. zoomHasHitLimit = true;
  77459. }
  77460. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  77461. this._lastFrameRadius = this._attachedCamera.radius;
  77462. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  77463. };
  77464. /**
  77465. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77466. */
  77467. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  77468. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  77469. this._lastInteractionTime = BABYLON.Tools.Now;
  77470. }
  77471. };
  77472. // Tools
  77473. AutoRotationBehavior.prototype._userIsMoving = function () {
  77474. if (!this._attachedCamera) {
  77475. return false;
  77476. }
  77477. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77478. this._attachedCamera.inertialBetaOffset !== 0 ||
  77479. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77480. this._attachedCamera.inertialPanningX !== 0 ||
  77481. this._attachedCamera.inertialPanningY !== 0 ||
  77482. this._isPointerDown;
  77483. };
  77484. return AutoRotationBehavior;
  77485. }());
  77486. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  77487. })(BABYLON || (BABYLON = {}));
  77488. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  77489. var BABYLON;
  77490. (function (BABYLON) {
  77491. var NullEngineOptions = /** @class */ (function () {
  77492. function NullEngineOptions() {
  77493. this.renderWidth = 512;
  77494. this.renderHeight = 256;
  77495. this.textureSize = 512;
  77496. this.deterministicLockstep = false;
  77497. this.lockstepMaxSteps = 4;
  77498. }
  77499. return NullEngineOptions;
  77500. }());
  77501. BABYLON.NullEngineOptions = NullEngineOptions;
  77502. /**
  77503. * The null engine class provides support for headless version of babylon.js.
  77504. * This can be used in server side scenario or for testing purposes
  77505. */
  77506. var NullEngine = /** @class */ (function (_super) {
  77507. __extends(NullEngine, _super);
  77508. function NullEngine(options) {
  77509. if (options === void 0) { options = new NullEngineOptions(); }
  77510. var _this = _super.call(this, null) || this;
  77511. if (options.deterministicLockstep === undefined) {
  77512. options.deterministicLockstep = false;
  77513. }
  77514. if (options.lockstepMaxSteps === undefined) {
  77515. options.lockstepMaxSteps = 4;
  77516. }
  77517. _this._options = options;
  77518. // Init caps
  77519. // We consider we are on a webgl1 capable device
  77520. _this._caps = new BABYLON.EngineCapabilities();
  77521. _this._caps.maxTexturesImageUnits = 16;
  77522. _this._caps.maxVertexTextureImageUnits = 16;
  77523. _this._caps.maxTextureSize = 512;
  77524. _this._caps.maxCubemapTextureSize = 512;
  77525. _this._caps.maxRenderTextureSize = 512;
  77526. _this._caps.maxVertexAttribs = 16;
  77527. _this._caps.maxVaryingVectors = 16;
  77528. _this._caps.maxFragmentUniformVectors = 16;
  77529. _this._caps.maxVertexUniformVectors = 16;
  77530. // Extensions
  77531. _this._caps.standardDerivatives = false;
  77532. _this._caps.astc = null;
  77533. _this._caps.s3tc = null;
  77534. _this._caps.pvrtc = null;
  77535. _this._caps.etc1 = null;
  77536. _this._caps.etc2 = null;
  77537. _this._caps.textureAnisotropicFilterExtension = null;
  77538. _this._caps.maxAnisotropy = 0;
  77539. _this._caps.uintIndices = false;
  77540. _this._caps.fragmentDepthSupported = false;
  77541. _this._caps.highPrecisionShaderSupported = true;
  77542. _this._caps.colorBufferFloat = false;
  77543. _this._caps.textureFloat = false;
  77544. _this._caps.textureFloatLinearFiltering = false;
  77545. _this._caps.textureFloatRender = false;
  77546. _this._caps.textureHalfFloat = false;
  77547. _this._caps.textureHalfFloatLinearFiltering = false;
  77548. _this._caps.textureHalfFloatRender = false;
  77549. _this._caps.textureLOD = false;
  77550. _this._caps.drawBuffersExtension = false;
  77551. _this._caps.depthTextureExtension = false;
  77552. _this._caps.vertexArrayObject = false;
  77553. _this._caps.instancedArrays = false;
  77554. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  77555. // Wrappers
  77556. if (typeof URL === "undefined") {
  77557. URL = {
  77558. createObjectURL: function () { },
  77559. revokeObjectURL: function () { }
  77560. };
  77561. }
  77562. if (typeof Blob === "undefined") {
  77563. Blob = function () { };
  77564. }
  77565. return _this;
  77566. }
  77567. NullEngine.prototype.isDeterministicLockStep = function () {
  77568. return this._options.deterministicLockstep;
  77569. };
  77570. NullEngine.prototype.getLockstepMaxSteps = function () {
  77571. return this._options.lockstepMaxSteps;
  77572. };
  77573. NullEngine.prototype.createVertexBuffer = function (vertices) {
  77574. return {
  77575. capacity: 0,
  77576. references: 1,
  77577. is32Bits: false
  77578. };
  77579. };
  77580. NullEngine.prototype.createIndexBuffer = function (indices) {
  77581. return {
  77582. capacity: 0,
  77583. references: 1,
  77584. is32Bits: false
  77585. };
  77586. };
  77587. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  77588. if (stencil === void 0) { stencil = false; }
  77589. };
  77590. NullEngine.prototype.getRenderWidth = function (useScreen) {
  77591. if (useScreen === void 0) { useScreen = false; }
  77592. if (!useScreen && this._currentRenderTarget) {
  77593. return this._currentRenderTarget.width;
  77594. }
  77595. return this._options.renderWidth;
  77596. };
  77597. NullEngine.prototype.getRenderHeight = function (useScreen) {
  77598. if (useScreen === void 0) { useScreen = false; }
  77599. if (!useScreen && this._currentRenderTarget) {
  77600. return this._currentRenderTarget.height;
  77601. }
  77602. return this._options.renderHeight;
  77603. };
  77604. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  77605. this._cachedViewport = viewport;
  77606. };
  77607. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  77608. return {
  77609. transformFeedback: null,
  77610. __SPECTOR_rebuildProgram: null
  77611. };
  77612. };
  77613. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  77614. return [];
  77615. };
  77616. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  77617. return [];
  77618. };
  77619. NullEngine.prototype.bindSamplers = function (effect) {
  77620. this._currentEffect = null;
  77621. };
  77622. NullEngine.prototype.enableEffect = function (effect) {
  77623. this._currentEffect = effect;
  77624. if (effect.onBind) {
  77625. effect.onBind(effect);
  77626. }
  77627. effect.onBindObservable.notifyObservers(effect);
  77628. };
  77629. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  77630. if (zOffset === void 0) { zOffset = 0; }
  77631. if (reverseSide === void 0) { reverseSide = false; }
  77632. };
  77633. NullEngine.prototype.setIntArray = function (uniform, array) {
  77634. };
  77635. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  77636. };
  77637. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  77638. };
  77639. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  77640. };
  77641. NullEngine.prototype.setFloatArray = function (uniform, array) {
  77642. };
  77643. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  77644. };
  77645. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  77646. };
  77647. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  77648. };
  77649. NullEngine.prototype.setArray = function (uniform, array) {
  77650. };
  77651. NullEngine.prototype.setArray2 = function (uniform, array) {
  77652. };
  77653. NullEngine.prototype.setArray3 = function (uniform, array) {
  77654. };
  77655. NullEngine.prototype.setArray4 = function (uniform, array) {
  77656. };
  77657. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  77658. };
  77659. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  77660. };
  77661. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  77662. };
  77663. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  77664. };
  77665. NullEngine.prototype.setFloat = function (uniform, value) {
  77666. };
  77667. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  77668. };
  77669. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  77670. };
  77671. NullEngine.prototype.setBool = function (uniform, bool) {
  77672. };
  77673. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  77674. };
  77675. NullEngine.prototype.setColor3 = function (uniform, color3) {
  77676. };
  77677. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  77678. };
  77679. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  77680. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  77681. if (this._alphaMode === mode) {
  77682. return;
  77683. }
  77684. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  77685. if (!noDepthWriteChange) {
  77686. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  77687. }
  77688. this._alphaMode = mode;
  77689. };
  77690. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  77691. };
  77692. NullEngine.prototype.wipeCaches = function (bruteForce) {
  77693. if (this.preventCacheWipeBetweenFrames) {
  77694. return;
  77695. }
  77696. this.resetTextureCache();
  77697. this._currentEffect = null;
  77698. if (bruteForce) {
  77699. this._currentProgram = null;
  77700. this._stencilState.reset();
  77701. this._depthCullingState.reset();
  77702. this.setDepthFunctionToLessOrEqual();
  77703. this._alphaState.reset();
  77704. }
  77705. this._cachedVertexBuffers = null;
  77706. this._cachedIndexBuffer = null;
  77707. this._cachedEffectForVertexBuffers = null;
  77708. };
  77709. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  77710. };
  77711. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  77712. };
  77713. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  77714. };
  77715. NullEngine.prototype._createTexture = function () {
  77716. return {};
  77717. };
  77718. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  77719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77720. if (onLoad === void 0) { onLoad = null; }
  77721. if (onError === void 0) { onError = null; }
  77722. if (buffer === void 0) { buffer = null; }
  77723. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  77724. var url = String(urlArg);
  77725. texture.url = url;
  77726. texture.generateMipMaps = !noMipmap;
  77727. texture.samplingMode = samplingMode;
  77728. texture.invertY = invertY;
  77729. texture.baseWidth = this._options.textureSize;
  77730. texture.baseHeight = this._options.textureSize;
  77731. texture.width = this._options.textureSize;
  77732. texture.height = this._options.textureSize;
  77733. if (format) {
  77734. texture.format = format;
  77735. }
  77736. texture.isReady = true;
  77737. if (onLoad) {
  77738. onLoad();
  77739. }
  77740. return texture;
  77741. };
  77742. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  77743. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  77744. if (options !== undefined && typeof options === "object") {
  77745. fullOptions.generateMipMaps = options.generateMipMaps;
  77746. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  77747. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  77748. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  77749. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  77750. }
  77751. else {
  77752. fullOptions.generateMipMaps = options;
  77753. fullOptions.generateDepthBuffer = true;
  77754. fullOptions.generateStencilBuffer = false;
  77755. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77756. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77757. }
  77758. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  77759. var width = size.width || size;
  77760. var height = size.height || size;
  77761. texture._depthStencilBuffer = {};
  77762. texture._framebuffer = {};
  77763. texture.baseWidth = width;
  77764. texture.baseHeight = height;
  77765. texture.width = width;
  77766. texture.height = height;
  77767. texture.isReady = true;
  77768. texture.samples = 1;
  77769. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  77770. texture.samplingMode = fullOptions.samplingMode;
  77771. texture.type = fullOptions.type;
  77772. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  77773. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  77774. return texture;
  77775. };
  77776. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  77777. texture.samplingMode = samplingMode;
  77778. };
  77779. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  77780. if (this._currentRenderTarget) {
  77781. this.unBindFramebuffer(this._currentRenderTarget);
  77782. }
  77783. this._currentRenderTarget = texture;
  77784. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  77785. if (this._cachedViewport && !forceFullscreenViewport) {
  77786. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  77787. }
  77788. };
  77789. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  77790. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  77791. this._currentRenderTarget = null;
  77792. if (onBeforeUnbind) {
  77793. if (texture._MSAAFramebuffer) {
  77794. this._currentFramebuffer = texture._framebuffer;
  77795. }
  77796. onBeforeUnbind();
  77797. }
  77798. this._currentFramebuffer = null;
  77799. };
  77800. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  77801. var vbo = {
  77802. capacity: 1,
  77803. references: 1,
  77804. is32Bits: false
  77805. };
  77806. return vbo;
  77807. };
  77808. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  77809. if (offset === void 0) { offset = 0; }
  77810. };
  77811. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  77812. };
  77813. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  77814. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  77815. this._boundTexturesCache[this._activeChannel] = texture;
  77816. }
  77817. };
  77818. NullEngine.prototype._bindTexture = function (channel, texture) {
  77819. if (channel < 0) {
  77820. return;
  77821. }
  77822. this._bindTextureDirectly(0, texture);
  77823. };
  77824. NullEngine.prototype._releaseBuffer = function (buffer) {
  77825. buffer.references--;
  77826. if (buffer.references === 0) {
  77827. return true;
  77828. }
  77829. return false;
  77830. };
  77831. return NullEngine;
  77832. }(BABYLON.Engine));
  77833. BABYLON.NullEngine = NullEngine;
  77834. })(BABYLON || (BABYLON = {}));
  77835. //# sourceMappingURL=babylon.nullEngine.js.map
  77836. var BABYLON;
  77837. (function (BABYLON) {
  77838. /**
  77839. * This class can be used to get instrumentation data from a Babylon engine
  77840. */
  77841. var EngineInstrumentation = /** @class */ (function () {
  77842. function EngineInstrumentation(engine) {
  77843. this.engine = engine;
  77844. this._captureGPUFrameTime = false;
  77845. this._gpuFrameTime = new BABYLON.PerfCounter();
  77846. this._captureShaderCompilationTime = false;
  77847. this._shaderCompilationTime = new BABYLON.PerfCounter();
  77848. // Observers
  77849. this._onBeginFrameObserver = null;
  77850. this._onEndFrameObserver = null;
  77851. this._onBeforeShaderCompilationObserver = null;
  77852. this._onAfterShaderCompilationObserver = null;
  77853. }
  77854. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  77855. // Properties
  77856. /**
  77857. * Gets the perf counter used for GPU frame time
  77858. */
  77859. get: function () {
  77860. return this._gpuFrameTime;
  77861. },
  77862. enumerable: true,
  77863. configurable: true
  77864. });
  77865. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  77866. /**
  77867. * Gets the GPU frame time capture status
  77868. */
  77869. get: function () {
  77870. return this._captureGPUFrameTime;
  77871. },
  77872. /**
  77873. * Enable or disable the GPU frame time capture
  77874. */
  77875. set: function (value) {
  77876. var _this = this;
  77877. if (value === this._captureGPUFrameTime) {
  77878. return;
  77879. }
  77880. this._captureGPUFrameTime = value;
  77881. if (value) {
  77882. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  77883. if (!_this._gpuFrameTimeToken) {
  77884. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  77885. }
  77886. });
  77887. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  77888. if (!_this._gpuFrameTimeToken) {
  77889. return;
  77890. }
  77891. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  77892. if (time > -1) {
  77893. _this._gpuFrameTimeToken = null;
  77894. _this._gpuFrameTime.fetchNewFrame();
  77895. _this._gpuFrameTime.addCount(time, true);
  77896. }
  77897. });
  77898. }
  77899. else {
  77900. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77901. this._onBeginFrameObserver = null;
  77902. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77903. this._onEndFrameObserver = null;
  77904. }
  77905. },
  77906. enumerable: true,
  77907. configurable: true
  77908. });
  77909. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  77910. /**
  77911. * Gets the perf counter used for shader compilation time
  77912. */
  77913. get: function () {
  77914. return this._shaderCompilationTime;
  77915. },
  77916. enumerable: true,
  77917. configurable: true
  77918. });
  77919. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  77920. /**
  77921. * Gets the shader compilation time capture status
  77922. */
  77923. get: function () {
  77924. return this._captureShaderCompilationTime;
  77925. },
  77926. /**
  77927. * Enable or disable the shader compilation time capture
  77928. */
  77929. set: function (value) {
  77930. var _this = this;
  77931. if (value === this._captureShaderCompilationTime) {
  77932. return;
  77933. }
  77934. this._captureShaderCompilationTime = value;
  77935. if (value) {
  77936. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  77937. _this._shaderCompilationTime.fetchNewFrame();
  77938. _this._shaderCompilationTime.beginMonitoring();
  77939. });
  77940. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  77941. _this._shaderCompilationTime.endMonitoring();
  77942. });
  77943. }
  77944. else {
  77945. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77946. this._onBeforeShaderCompilationObserver = null;
  77947. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77948. this._onAfterShaderCompilationObserver = null;
  77949. }
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. EngineInstrumentation.prototype.dispose = function () {
  77955. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77956. this._onBeginFrameObserver = null;
  77957. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77958. this._onEndFrameObserver = null;
  77959. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77960. this._onBeforeShaderCompilationObserver = null;
  77961. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77962. this._onAfterShaderCompilationObserver = null;
  77963. this.engine = null;
  77964. };
  77965. return EngineInstrumentation;
  77966. }());
  77967. BABYLON.EngineInstrumentation = EngineInstrumentation;
  77968. })(BABYLON || (BABYLON = {}));
  77969. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  77970. var BABYLON;
  77971. (function (BABYLON) {
  77972. /**
  77973. * This class can be used to get instrumentation data from a Babylon engine
  77974. */
  77975. var SceneInstrumentation = /** @class */ (function () {
  77976. function SceneInstrumentation(scene) {
  77977. var _this = this;
  77978. this.scene = scene;
  77979. this._captureActiveMeshesEvaluationTime = false;
  77980. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  77981. this._captureRenderTargetsRenderTime = false;
  77982. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  77983. this._captureFrameTime = false;
  77984. this._frameTime = new BABYLON.PerfCounter();
  77985. this._captureRenderTime = false;
  77986. this._renderTime = new BABYLON.PerfCounter();
  77987. this._captureInterFrameTime = false;
  77988. this._interFrameTime = new BABYLON.PerfCounter();
  77989. this._captureParticlesRenderTime = false;
  77990. this._particlesRenderTime = new BABYLON.PerfCounter();
  77991. this._captureSpritesRenderTime = false;
  77992. this._spritesRenderTime = new BABYLON.PerfCounter();
  77993. this._capturePhysicsTime = false;
  77994. this._physicsTime = new BABYLON.PerfCounter();
  77995. this._captureAnimationsTime = false;
  77996. this._animationsTime = new BABYLON.PerfCounter();
  77997. // Observers
  77998. this._onBeforeActiveMeshesEvaluationObserver = null;
  77999. this._onAfterActiveMeshesEvaluationObserver = null;
  78000. this._onBeforeRenderTargetsRenderObserver = null;
  78001. this._onAfterRenderTargetsRenderObserver = null;
  78002. this._onAfterRenderObserver = null;
  78003. this._onBeforeDrawPhaseObserver = null;
  78004. this._onAfterDrawPhaseObserver = null;
  78005. this._onBeforeAnimationsObserver = null;
  78006. this._onBeforeParticlesRenderingObserver = null;
  78007. this._onAfterParticlesRenderingObserver = null;
  78008. this._onBeforeSpritesRenderingObserver = null;
  78009. this._onAfterSpritesRenderingObserver = null;
  78010. this._onBeforePhysicsObserver = null;
  78011. this._onAfterPhysicsObserver = null;
  78012. this._onAfterAnimationsObserver = null;
  78013. // Before render
  78014. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  78015. if (_this._captureActiveMeshesEvaluationTime) {
  78016. _this._activeMeshesEvaluationTime.fetchNewFrame();
  78017. }
  78018. if (_this._captureRenderTargetsRenderTime) {
  78019. _this._renderTargetsRenderTime.fetchNewFrame();
  78020. }
  78021. if (_this._captureFrameTime) {
  78022. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  78023. _this._frameTime.beginMonitoring();
  78024. }
  78025. if (_this._captureInterFrameTime) {
  78026. _this._interFrameTime.endMonitoring();
  78027. }
  78028. if (_this._captureParticlesRenderTime) {
  78029. _this._particlesRenderTime.fetchNewFrame();
  78030. }
  78031. if (_this._captureSpritesRenderTime) {
  78032. _this._spritesRenderTime.fetchNewFrame();
  78033. }
  78034. if (_this._captureAnimationsTime) {
  78035. _this._animationsTime.beginMonitoring();
  78036. }
  78037. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  78038. });
  78039. // After render
  78040. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  78041. if (_this._captureFrameTime) {
  78042. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  78043. _this._frameTime.endMonitoring();
  78044. }
  78045. if (_this._captureRenderTime) {
  78046. _this._renderTime.endMonitoring(false);
  78047. }
  78048. if (_this._captureInterFrameTime) {
  78049. _this._interFrameTime.beginMonitoring();
  78050. }
  78051. });
  78052. }
  78053. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  78054. // Properties
  78055. /**
  78056. * Gets the perf counter used for active meshes evaluation time
  78057. */
  78058. get: function () {
  78059. return this._activeMeshesEvaluationTime;
  78060. },
  78061. enumerable: true,
  78062. configurable: true
  78063. });
  78064. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  78065. /**
  78066. * Gets the active meshes evaluation time capture status
  78067. */
  78068. get: function () {
  78069. return this._captureActiveMeshesEvaluationTime;
  78070. },
  78071. /**
  78072. * Enable or disable the active meshes evaluation time capture
  78073. */
  78074. set: function (value) {
  78075. var _this = this;
  78076. if (value === this._captureActiveMeshesEvaluationTime) {
  78077. return;
  78078. }
  78079. this._captureActiveMeshesEvaluationTime = value;
  78080. if (value) {
  78081. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  78082. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  78083. _this._activeMeshesEvaluationTime.beginMonitoring();
  78084. });
  78085. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  78086. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  78087. _this._activeMeshesEvaluationTime.endMonitoring();
  78088. });
  78089. }
  78090. else {
  78091. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78092. this._onBeforeActiveMeshesEvaluationObserver = null;
  78093. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78094. this._onAfterActiveMeshesEvaluationObserver = null;
  78095. }
  78096. },
  78097. enumerable: true,
  78098. configurable: true
  78099. });
  78100. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  78101. /**
  78102. * Gets the perf counter used for render targets render time
  78103. */
  78104. get: function () {
  78105. return this._renderTargetsRenderTime;
  78106. },
  78107. enumerable: true,
  78108. configurable: true
  78109. });
  78110. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  78111. /**
  78112. * Gets the render targets render time capture status
  78113. */
  78114. get: function () {
  78115. return this._captureRenderTargetsRenderTime;
  78116. },
  78117. /**
  78118. * Enable or disable the render targets render time capture
  78119. */
  78120. set: function (value) {
  78121. var _this = this;
  78122. if (value === this._captureRenderTargetsRenderTime) {
  78123. return;
  78124. }
  78125. this._captureRenderTargetsRenderTime = value;
  78126. if (value) {
  78127. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  78128. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  78129. _this._renderTargetsRenderTime.beginMonitoring();
  78130. });
  78131. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  78132. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  78133. _this._renderTargetsRenderTime.endMonitoring(false);
  78134. });
  78135. }
  78136. else {
  78137. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78138. this._onBeforeRenderTargetsRenderObserver = null;
  78139. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78140. this._onAfterRenderTargetsRenderObserver = null;
  78141. }
  78142. },
  78143. enumerable: true,
  78144. configurable: true
  78145. });
  78146. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  78147. /**
  78148. * Gets the perf counter used for particles render time
  78149. */
  78150. get: function () {
  78151. return this._particlesRenderTime;
  78152. },
  78153. enumerable: true,
  78154. configurable: true
  78155. });
  78156. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  78157. /**
  78158. * Gets the particles render time capture status
  78159. */
  78160. get: function () {
  78161. return this._captureParticlesRenderTime;
  78162. },
  78163. /**
  78164. * Enable or disable the particles render time capture
  78165. */
  78166. set: function (value) {
  78167. var _this = this;
  78168. if (value === this._captureParticlesRenderTime) {
  78169. return;
  78170. }
  78171. this._captureParticlesRenderTime = value;
  78172. if (value) {
  78173. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  78174. BABYLON.Tools.StartPerformanceCounter("Particles");
  78175. _this._particlesRenderTime.beginMonitoring();
  78176. });
  78177. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  78178. BABYLON.Tools.EndPerformanceCounter("Particles");
  78179. _this._particlesRenderTime.endMonitoring(false);
  78180. });
  78181. }
  78182. else {
  78183. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78184. this._onBeforeParticlesRenderingObserver = null;
  78185. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78186. this._onAfterParticlesRenderingObserver = null;
  78187. }
  78188. },
  78189. enumerable: true,
  78190. configurable: true
  78191. });
  78192. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  78193. /**
  78194. * Gets the perf counter used for sprites render time
  78195. */
  78196. get: function () {
  78197. return this._spritesRenderTime;
  78198. },
  78199. enumerable: true,
  78200. configurable: true
  78201. });
  78202. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  78203. /**
  78204. * Gets the sprites render time capture status
  78205. */
  78206. get: function () {
  78207. return this._captureSpritesRenderTime;
  78208. },
  78209. /**
  78210. * Enable or disable the sprites render time capture
  78211. */
  78212. set: function (value) {
  78213. var _this = this;
  78214. if (value === this._captureSpritesRenderTime) {
  78215. return;
  78216. }
  78217. this._captureSpritesRenderTime = value;
  78218. if (value) {
  78219. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  78220. BABYLON.Tools.StartPerformanceCounter("Sprites");
  78221. _this._spritesRenderTime.beginMonitoring();
  78222. });
  78223. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  78224. BABYLON.Tools.EndPerformanceCounter("Sprites");
  78225. _this._spritesRenderTime.endMonitoring(false);
  78226. });
  78227. }
  78228. else {
  78229. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78230. this._onBeforeSpritesRenderingObserver = null;
  78231. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78232. this._onAfterSpritesRenderingObserver = null;
  78233. }
  78234. },
  78235. enumerable: true,
  78236. configurable: true
  78237. });
  78238. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  78239. /**
  78240. * Gets the perf counter used for physics time
  78241. */
  78242. get: function () {
  78243. return this._physicsTime;
  78244. },
  78245. enumerable: true,
  78246. configurable: true
  78247. });
  78248. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  78249. /**
  78250. * Gets the physics time capture status
  78251. */
  78252. get: function () {
  78253. return this._capturePhysicsTime;
  78254. },
  78255. /**
  78256. * Enable or disable the physics time capture
  78257. */
  78258. set: function (value) {
  78259. var _this = this;
  78260. if (value === this._capturePhysicsTime) {
  78261. return;
  78262. }
  78263. this._capturePhysicsTime = value;
  78264. if (value) {
  78265. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  78266. BABYLON.Tools.StartPerformanceCounter("Physics");
  78267. _this._physicsTime.beginMonitoring();
  78268. });
  78269. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  78270. BABYLON.Tools.EndPerformanceCounter("Physics");
  78271. _this._physicsTime.endMonitoring();
  78272. });
  78273. }
  78274. else {
  78275. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78276. this._onBeforePhysicsObserver = null;
  78277. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78278. this._onAfterPhysicsObserver = null;
  78279. }
  78280. },
  78281. enumerable: true,
  78282. configurable: true
  78283. });
  78284. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  78285. /**
  78286. * Gets the perf counter used for animations time
  78287. */
  78288. get: function () {
  78289. return this._animationsTime;
  78290. },
  78291. enumerable: true,
  78292. configurable: true
  78293. });
  78294. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  78295. /**
  78296. * Gets the animations time capture status
  78297. */
  78298. get: function () {
  78299. return this._captureAnimationsTime;
  78300. },
  78301. /**
  78302. * Enable or disable the animations time capture
  78303. */
  78304. set: function (value) {
  78305. var _this = this;
  78306. if (value === this._captureAnimationsTime) {
  78307. return;
  78308. }
  78309. this._captureAnimationsTime = value;
  78310. if (value) {
  78311. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  78312. _this._animationsTime.endMonitoring();
  78313. });
  78314. }
  78315. else {
  78316. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78317. this._onAfterAnimationsObserver = null;
  78318. }
  78319. },
  78320. enumerable: true,
  78321. configurable: true
  78322. });
  78323. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  78324. /**
  78325. * Gets the perf counter used for frame time capture
  78326. */
  78327. get: function () {
  78328. return this._frameTime;
  78329. },
  78330. enumerable: true,
  78331. configurable: true
  78332. });
  78333. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  78334. /**
  78335. * Gets the frame time capture status
  78336. */
  78337. get: function () {
  78338. return this._captureFrameTime;
  78339. },
  78340. /**
  78341. * Enable or disable the frame time capture
  78342. */
  78343. set: function (value) {
  78344. this._captureFrameTime = value;
  78345. },
  78346. enumerable: true,
  78347. configurable: true
  78348. });
  78349. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  78350. /**
  78351. * Gets the perf counter used for inter-frames time capture
  78352. */
  78353. get: function () {
  78354. return this._interFrameTime;
  78355. },
  78356. enumerable: true,
  78357. configurable: true
  78358. });
  78359. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  78360. /**
  78361. * Gets the inter-frames time capture status
  78362. */
  78363. get: function () {
  78364. return this._captureInterFrameTime;
  78365. },
  78366. /**
  78367. * Enable or disable the inter-frames time capture
  78368. */
  78369. set: function (value) {
  78370. this._captureInterFrameTime = value;
  78371. },
  78372. enumerable: true,
  78373. configurable: true
  78374. });
  78375. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  78376. /**
  78377. * Gets the perf counter used for render time capture
  78378. */
  78379. get: function () {
  78380. return this._renderTime;
  78381. },
  78382. enumerable: true,
  78383. configurable: true
  78384. });
  78385. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  78386. /**
  78387. * Gets the render time capture status
  78388. */
  78389. get: function () {
  78390. return this._captureRenderTime;
  78391. },
  78392. /**
  78393. * Enable or disable the render time capture
  78394. */
  78395. set: function (value) {
  78396. var _this = this;
  78397. if (value === this._captureRenderTime) {
  78398. return;
  78399. }
  78400. this._captureRenderTime = value;
  78401. if (value) {
  78402. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  78403. _this._renderTime.beginMonitoring();
  78404. BABYLON.Tools.StartPerformanceCounter("Main render");
  78405. });
  78406. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  78407. _this._renderTime.endMonitoring(false);
  78408. BABYLON.Tools.EndPerformanceCounter("Main render");
  78409. });
  78410. }
  78411. else {
  78412. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78413. this._onBeforeDrawPhaseObserver = null;
  78414. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78415. this._onAfterDrawPhaseObserver = null;
  78416. }
  78417. },
  78418. enumerable: true,
  78419. configurable: true
  78420. });
  78421. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  78422. /**
  78423. * Gets the perf counter used for frame time capture
  78424. */
  78425. get: function () {
  78426. return this.scene.getEngine()._drawCalls;
  78427. },
  78428. enumerable: true,
  78429. configurable: true
  78430. });
  78431. SceneInstrumentation.prototype.dispose = function () {
  78432. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78433. this._onAfterRenderObserver = null;
  78434. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78435. this._onBeforeActiveMeshesEvaluationObserver = null;
  78436. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78437. this._onAfterActiveMeshesEvaluationObserver = null;
  78438. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78439. this._onBeforeRenderTargetsRenderObserver = null;
  78440. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78441. this._onAfterRenderTargetsRenderObserver = null;
  78442. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  78443. this._onBeforeAnimationsObserver = null;
  78444. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78445. this._onBeforeParticlesRenderingObserver = null;
  78446. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78447. this._onAfterParticlesRenderingObserver = null;
  78448. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78449. this._onBeforeSpritesRenderingObserver = null;
  78450. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78451. this._onAfterSpritesRenderingObserver = null;
  78452. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78453. this._onBeforeDrawPhaseObserver = null;
  78454. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78455. this._onAfterDrawPhaseObserver = null;
  78456. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78457. this._onBeforePhysicsObserver = null;
  78458. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78459. this._onAfterPhysicsObserver = null;
  78460. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78461. this._onAfterAnimationsObserver = null;
  78462. this.scene = null;
  78463. };
  78464. return SceneInstrumentation;
  78465. }());
  78466. BABYLON.SceneInstrumentation = SceneInstrumentation;
  78467. })(BABYLON || (BABYLON = {}));
  78468. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  78469. var BABYLON;
  78470. (function (BABYLON) {
  78471. var _TimeToken = /** @class */ (function () {
  78472. function _TimeToken() {
  78473. this._timeElapsedQueryEnded = false;
  78474. }
  78475. return _TimeToken;
  78476. }());
  78477. BABYLON._TimeToken = _TimeToken;
  78478. })(BABYLON || (BABYLON = {}));
  78479. //# sourceMappingURL=babylon.timeToken.js.map
  78480. var BABYLON;
  78481. (function (BABYLON) {
  78482. /**
  78483. * Background material defines definition.
  78484. */
  78485. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  78486. __extends(BackgroundMaterialDefines, _super);
  78487. /**
  78488. * Constructor of the defines.
  78489. */
  78490. function BackgroundMaterialDefines() {
  78491. var _this = _super.call(this) || this;
  78492. /**
  78493. * True if the diffuse texture is in use.
  78494. */
  78495. _this.DIFFUSE = false;
  78496. /**
  78497. * The direct UV channel to use.
  78498. */
  78499. _this.DIFFUSEDIRECTUV = 0;
  78500. /**
  78501. * True if the diffuse texture is in gamma space.
  78502. */
  78503. _this.GAMMADIFFUSE = false;
  78504. /**
  78505. * True if the diffuse texture has opacity in the alpha channel.
  78506. */
  78507. _this.DIFFUSEHASALPHA = false;
  78508. /**
  78509. * True if you want the material to fade to transparent at grazing angle.
  78510. */
  78511. _this.OPACITYFRESNEL = false;
  78512. /**
  78513. * True if an extra blur needs to be added in the reflection.
  78514. */
  78515. _this.REFLECTIONBLUR = false;
  78516. /**
  78517. * True if you want the material to fade to reflection at grazing angle.
  78518. */
  78519. _this.REFLECTIONFRESNEL = false;
  78520. /**
  78521. * True if you want the material to falloff as far as you move away from the scene center.
  78522. */
  78523. _this.REFLECTIONFALLOFF = false;
  78524. /**
  78525. * False if the current Webgl implementation does not support the texture lod extension.
  78526. */
  78527. _this.TEXTURELODSUPPORT = false;
  78528. /**
  78529. * True to ensure the data are premultiplied.
  78530. */
  78531. _this.PREMULTIPLYALPHA = false;
  78532. /**
  78533. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  78534. */
  78535. _this.USERGBCOLOR = false;
  78536. /**
  78537. * True to add noise in order to reduce the banding effect.
  78538. */
  78539. _this.NOISE = false;
  78540. // Image Processing Configuration.
  78541. _this.IMAGEPROCESSING = false;
  78542. _this.VIGNETTE = false;
  78543. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  78544. _this.VIGNETTEBLENDMODEOPAQUE = false;
  78545. _this.TONEMAPPING = false;
  78546. _this.CONTRAST = false;
  78547. _this.COLORCURVES = false;
  78548. _this.COLORGRADING = false;
  78549. _this.COLORGRADING3D = false;
  78550. _this.SAMPLER3DGREENDEPTH = false;
  78551. _this.SAMPLER3DBGRMAP = false;
  78552. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  78553. _this.EXPOSURE = false;
  78554. // Reflection.
  78555. _this.REFLECTION = false;
  78556. _this.REFLECTIONMAP_3D = false;
  78557. _this.REFLECTIONMAP_SPHERICAL = false;
  78558. _this.REFLECTIONMAP_PLANAR = false;
  78559. _this.REFLECTIONMAP_CUBIC = false;
  78560. _this.REFLECTIONMAP_PROJECTION = false;
  78561. _this.REFLECTIONMAP_SKYBOX = false;
  78562. _this.REFLECTIONMAP_EXPLICIT = false;
  78563. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78564. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78565. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78566. _this.INVERTCUBICMAP = false;
  78567. _this.REFLECTIONMAP_OPPOSITEZ = false;
  78568. _this.LODINREFLECTIONALPHA = false;
  78569. _this.GAMMAREFLECTION = false;
  78570. // Default BJS.
  78571. _this.MAINUV1 = false;
  78572. _this.MAINUV2 = false;
  78573. _this.UV1 = false;
  78574. _this.UV2 = false;
  78575. _this.CLIPPLANE = false;
  78576. _this.POINTSIZE = false;
  78577. _this.FOG = false;
  78578. _this.NORMAL = false;
  78579. _this.NUM_BONE_INFLUENCERS = 0;
  78580. _this.BonesPerMesh = 0;
  78581. _this.INSTANCES = false;
  78582. _this.SHADOWFLOAT = false;
  78583. _this.rebuild();
  78584. return _this;
  78585. }
  78586. return BackgroundMaterialDefines;
  78587. }(BABYLON.MaterialDefines));
  78588. /**
  78589. * Background material used to create an efficient environement around your scene.
  78590. */
  78591. var BackgroundMaterial = /** @class */ (function (_super) {
  78592. __extends(BackgroundMaterial, _super);
  78593. /**
  78594. * constructor
  78595. * @param name The name of the material
  78596. * @param scene The scene to add the material to
  78597. */
  78598. function BackgroundMaterial(name, scene) {
  78599. var _this = _super.call(this, name, scene) || this;
  78600. _this.primaryColor = BABYLON.Color3.White();
  78601. _this.primaryLevel = 1;
  78602. _this.secondaryColor = BABYLON.Color3.Gray();
  78603. _this.secondaryLevel = 1;
  78604. _this.tertiaryColor = BABYLON.Color3.Black();
  78605. _this.tertiaryLevel = 1;
  78606. _this.reflectionTexture = null;
  78607. _this.reflectionBlur = 0;
  78608. _this.diffuseTexture = null;
  78609. /**
  78610. * Specify the list of lights casting shadow on the material.
  78611. * All scene shadow lights will be included if null.
  78612. */
  78613. _this._shadowLights = null;
  78614. _this.shadowLights = null;
  78615. _this.shadowBlurScale = 1;
  78616. _this.shadowLevel = 0;
  78617. _this.sceneCenter = BABYLON.Vector3.Zero();
  78618. _this.opacityFresnel = true;
  78619. _this.reflectionFresnel = false;
  78620. _this.reflectionFalloffDistance = 0.0;
  78621. _this.reflectionAmount = 1.0;
  78622. _this.reflectionReflectance0 = 0.05;
  78623. _this.reflectionReflectance90 = 0.5;
  78624. _this.useRGBColor = true;
  78625. _this.enableNoise = false;
  78626. /**
  78627. * Number of Simultaneous lights allowed on the material.
  78628. */
  78629. _this._maxSimultaneousLights = 4;
  78630. _this.maxSimultaneousLights = 4;
  78631. /**
  78632. * Keep track of the image processing observer to allow dispose and replace.
  78633. */
  78634. _this._imageProcessingObserver = null;
  78635. // Temp values kept as cache in the material.
  78636. _this._renderTargets = new BABYLON.SmartArray(16);
  78637. _this._reflectionControls = BABYLON.Vector4.Zero();
  78638. // Setup the default processing configuration to the scene.
  78639. _this._attachImageProcessingConfiguration(null);
  78640. _this.getRenderTargetTextures = function () {
  78641. _this._renderTargets.reset();
  78642. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  78643. _this._renderTargets.push(_this._diffuseTexture);
  78644. }
  78645. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  78646. _this._renderTargets.push(_this._reflectionTexture);
  78647. }
  78648. return _this._renderTargets;
  78649. };
  78650. return _this;
  78651. }
  78652. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  78653. /**
  78654. * Sets the reflection reflectance fresnel values according to the default standard
  78655. * empirically know to work well :-)
  78656. */
  78657. set: function (value) {
  78658. var reflectionWeight = value;
  78659. if (reflectionWeight < 0.5) {
  78660. reflectionWeight = reflectionWeight * 2.0;
  78661. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  78662. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  78663. }
  78664. else {
  78665. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  78666. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  78667. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  78668. }
  78669. },
  78670. enumerable: true,
  78671. configurable: true
  78672. });
  78673. /**
  78674. * Attaches a new image processing configuration to the PBR Material.
  78675. * @param configuration (if null the scene configuration will be use)
  78676. */
  78677. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  78678. var _this = this;
  78679. if (configuration === this._imageProcessingConfiguration) {
  78680. return;
  78681. }
  78682. // Detaches observer.
  78683. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78684. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78685. }
  78686. // Pick the scene configuration if needed.
  78687. if (!configuration) {
  78688. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  78689. }
  78690. else {
  78691. this._imageProcessingConfiguration = configuration;
  78692. }
  78693. // Attaches observer.
  78694. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78695. _this._markAllSubMeshesAsImageProcessingDirty();
  78696. });
  78697. };
  78698. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  78699. /**
  78700. * Gets the image processing configuration used either in this material.
  78701. */
  78702. get: function () {
  78703. return this._imageProcessingConfiguration;
  78704. },
  78705. /**
  78706. * Sets the Default image processing configuration used either in the this material.
  78707. *
  78708. * If sets to null, the scene one is in use.
  78709. */
  78710. set: function (value) {
  78711. this._attachImageProcessingConfiguration(value);
  78712. // Ensure the effect will be rebuilt.
  78713. this._markAllSubMeshesAsTexturesDirty();
  78714. },
  78715. enumerable: true,
  78716. configurable: true
  78717. });
  78718. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  78719. /**
  78720. * Gets wether the color curves effect is enabled.
  78721. */
  78722. get: function () {
  78723. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78724. },
  78725. /**
  78726. * Sets wether the color curves effect is enabled.
  78727. */
  78728. set: function (value) {
  78729. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78730. },
  78731. enumerable: true,
  78732. configurable: true
  78733. });
  78734. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  78735. /**
  78736. * Gets wether the color grading effect is enabled.
  78737. */
  78738. get: function () {
  78739. return this.imageProcessingConfiguration.colorGradingEnabled;
  78740. },
  78741. /**
  78742. * Gets wether the color grading effect is enabled.
  78743. */
  78744. set: function (value) {
  78745. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78746. },
  78747. enumerable: true,
  78748. configurable: true
  78749. });
  78750. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  78751. /**
  78752. * Gets wether tonemapping is enabled or not.
  78753. */
  78754. get: function () {
  78755. return this._imageProcessingConfiguration.toneMappingEnabled;
  78756. },
  78757. /**
  78758. * Sets wether tonemapping is enabled or not
  78759. */
  78760. set: function (value) {
  78761. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78762. },
  78763. enumerable: true,
  78764. configurable: true
  78765. });
  78766. ;
  78767. ;
  78768. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  78769. /**
  78770. * The camera exposure used on this material.
  78771. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78772. * This corresponds to a photographic exposure.
  78773. */
  78774. get: function () {
  78775. return this._imageProcessingConfiguration.exposure;
  78776. },
  78777. /**
  78778. * The camera exposure used on this material.
  78779. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78780. * This corresponds to a photographic exposure.
  78781. */
  78782. set: function (value) {
  78783. this._imageProcessingConfiguration.exposure = value;
  78784. },
  78785. enumerable: true,
  78786. configurable: true
  78787. });
  78788. ;
  78789. ;
  78790. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  78791. /**
  78792. * Gets The camera contrast used on this material.
  78793. */
  78794. get: function () {
  78795. return this._imageProcessingConfiguration.contrast;
  78796. },
  78797. /**
  78798. * Sets The camera contrast used on this material.
  78799. */
  78800. set: function (value) {
  78801. this._imageProcessingConfiguration.contrast = value;
  78802. },
  78803. enumerable: true,
  78804. configurable: true
  78805. });
  78806. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  78807. /**
  78808. * Gets the Color Grading 2D Lookup Texture.
  78809. */
  78810. get: function () {
  78811. return this._imageProcessingConfiguration.colorGradingTexture;
  78812. },
  78813. /**
  78814. * Sets the Color Grading 2D Lookup Texture.
  78815. */
  78816. set: function (value) {
  78817. this.imageProcessingConfiguration.colorGradingTexture = value;
  78818. },
  78819. enumerable: true,
  78820. configurable: true
  78821. });
  78822. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  78823. /**
  78824. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78825. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78826. * 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;
  78827. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78828. */
  78829. get: function () {
  78830. return this.imageProcessingConfiguration.colorCurves;
  78831. },
  78832. /**
  78833. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78834. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78835. * 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;
  78836. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78837. */
  78838. set: function (value) {
  78839. this.imageProcessingConfiguration.colorCurves = value;
  78840. },
  78841. enumerable: true,
  78842. configurable: true
  78843. });
  78844. /**
  78845. * The entire material has been created in order to prevent overdraw.
  78846. * @returns false
  78847. */
  78848. BackgroundMaterial.prototype.needAlphaTesting = function () {
  78849. return true;
  78850. };
  78851. /**
  78852. * The entire material has been created in order to prevent overdraw.
  78853. * @returns true if blending is enable
  78854. */
  78855. BackgroundMaterial.prototype.needAlphaBlending = function () {
  78856. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  78857. };
  78858. /**
  78859. * Checks wether the material is ready to be rendered for a given mesh.
  78860. * @param mesh The mesh to render
  78861. * @param subMesh The submesh to check against
  78862. * @param useInstances Specify wether or not the material is used with instances
  78863. */
  78864. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78865. var _this = this;
  78866. if (useInstances === void 0) { useInstances = false; }
  78867. if (subMesh.effect && this.isFrozen) {
  78868. if (this._wasPreviouslyReady) {
  78869. return true;
  78870. }
  78871. }
  78872. if (!subMesh._materialDefines) {
  78873. subMesh._materialDefines = new BackgroundMaterialDefines();
  78874. }
  78875. var scene = this.getScene();
  78876. var defines = subMesh._materialDefines;
  78877. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78878. if (defines._renderId === scene.getRenderId()) {
  78879. return true;
  78880. }
  78881. }
  78882. var engine = scene.getEngine();
  78883. // Lights
  78884. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  78885. defines._needNormals = true;
  78886. // Textures
  78887. if (defines._areTexturesDirty) {
  78888. defines._needUVs = false;
  78889. if (scene.texturesEnabled) {
  78890. if (scene.getEngine().getCaps().textureLOD) {
  78891. defines.TEXTURELODSUPPORT = true;
  78892. }
  78893. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78894. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  78895. return false;
  78896. }
  78897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  78898. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  78899. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  78900. defines.OPACITYFRESNEL = this._opacityFresnel;
  78901. }
  78902. else {
  78903. defines.DIFFUSE = false;
  78904. defines.DIFFUSEHASALPHA = false;
  78905. defines.GAMMADIFFUSE = false;
  78906. defines.OPACITYFRESNEL = false;
  78907. }
  78908. var reflectionTexture = this._reflectionTexture;
  78909. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78910. if (!reflectionTexture.isReadyOrNotBlocking()) {
  78911. return false;
  78912. }
  78913. defines.REFLECTION = true;
  78914. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  78915. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  78916. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  78917. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  78918. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  78919. defines.INVERTCUBICMAP = true;
  78920. }
  78921. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  78922. switch (reflectionTexture.coordinatesMode) {
  78923. case BABYLON.Texture.CUBIC_MODE:
  78924. case BABYLON.Texture.INVCUBIC_MODE:
  78925. defines.REFLECTIONMAP_CUBIC = true;
  78926. break;
  78927. case BABYLON.Texture.EXPLICIT_MODE:
  78928. defines.REFLECTIONMAP_EXPLICIT = true;
  78929. break;
  78930. case BABYLON.Texture.PLANAR_MODE:
  78931. defines.REFLECTIONMAP_PLANAR = true;
  78932. break;
  78933. case BABYLON.Texture.PROJECTION_MODE:
  78934. defines.REFLECTIONMAP_PROJECTION = true;
  78935. break;
  78936. case BABYLON.Texture.SKYBOX_MODE:
  78937. defines.REFLECTIONMAP_SKYBOX = true;
  78938. break;
  78939. case BABYLON.Texture.SPHERICAL_MODE:
  78940. defines.REFLECTIONMAP_SPHERICAL = true;
  78941. break;
  78942. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  78943. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  78944. break;
  78945. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  78946. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  78947. break;
  78948. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  78949. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  78950. break;
  78951. }
  78952. if (this.reflectionFresnel) {
  78953. defines.REFLECTIONFRESNEL = true;
  78954. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  78955. this._reflectionControls.x = this.reflectionAmount;
  78956. this._reflectionControls.y = this.reflectionReflectance0;
  78957. this._reflectionControls.z = this.reflectionReflectance90;
  78958. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  78959. }
  78960. else {
  78961. defines.REFLECTIONFRESNEL = false;
  78962. defines.REFLECTIONFALLOFF = false;
  78963. }
  78964. }
  78965. else {
  78966. defines.REFLECTION = false;
  78967. defines.REFLECTIONFALLOFF = false;
  78968. defines.REFLECTIONBLUR = false;
  78969. defines.REFLECTIONMAP_3D = false;
  78970. defines.REFLECTIONMAP_SPHERICAL = false;
  78971. defines.REFLECTIONMAP_PLANAR = false;
  78972. defines.REFLECTIONMAP_CUBIC = false;
  78973. defines.REFLECTIONMAP_PROJECTION = false;
  78974. defines.REFLECTIONMAP_SKYBOX = false;
  78975. defines.REFLECTIONMAP_EXPLICIT = false;
  78976. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78977. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78978. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78979. defines.INVERTCUBICMAP = false;
  78980. defines.REFLECTIONMAP_OPPOSITEZ = false;
  78981. defines.LODINREFLECTIONALPHA = false;
  78982. defines.GAMMAREFLECTION = false;
  78983. }
  78984. }
  78985. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  78986. defines.USERGBCOLOR = this._useRGBColor;
  78987. defines.NOISE = this._enableNoise;
  78988. }
  78989. if (defines._areImageProcessingDirty) {
  78990. if (!this._imageProcessingConfiguration.isReady()) {
  78991. return false;
  78992. }
  78993. this._imageProcessingConfiguration.prepareDefines(defines);
  78994. }
  78995. // Misc.
  78996. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  78997. // Values that need to be evaluated on every frame
  78998. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  78999. // Attribs
  79000. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  79001. if (mesh) {
  79002. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79003. mesh.createNormals(true);
  79004. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  79005. }
  79006. }
  79007. }
  79008. // Get correct effect
  79009. if (defines.isDirty) {
  79010. defines.markAsProcessed();
  79011. scene.resetCachedMaterial();
  79012. // Fallbacks
  79013. var fallbacks = new BABYLON.EffectFallbacks();
  79014. if (defines.FOG) {
  79015. fallbacks.addFallback(0, "FOG");
  79016. }
  79017. if (defines.POINTSIZE) {
  79018. fallbacks.addFallback(1, "POINTSIZE");
  79019. }
  79020. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  79021. if (defines.NUM_BONE_INFLUENCERS > 0) {
  79022. fallbacks.addCPUSkinningFallback(0, mesh);
  79023. }
  79024. //Attributes
  79025. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79026. if (defines.NORMAL) {
  79027. attribs.push(BABYLON.VertexBuffer.NormalKind);
  79028. }
  79029. if (defines.UV1) {
  79030. attribs.push(BABYLON.VertexBuffer.UVKind);
  79031. }
  79032. if (defines.UV2) {
  79033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79034. }
  79035. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  79036. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  79037. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  79038. "vFogInfos", "vFogColor", "pointSize",
  79039. "vClipPlane", "mBones",
  79040. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  79041. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  79042. "shadowLevel", "alpha",
  79043. "vBackgroundCenter", "vReflectionControl",
  79044. "vDiffuseInfos", "diffuseMatrix",
  79045. ];
  79046. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  79047. var uniformBuffers = ["Material", "Scene"];
  79048. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  79049. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  79050. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  79051. uniformsNames: uniforms,
  79052. uniformBuffersNames: uniformBuffers,
  79053. samplers: samplers,
  79054. defines: defines,
  79055. maxSimultaneousLights: this._maxSimultaneousLights
  79056. });
  79057. var onCompiled = function (effect) {
  79058. if (_this.onCompiled) {
  79059. _this.onCompiled(effect);
  79060. }
  79061. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  79062. };
  79063. var join = defines.toString();
  79064. subMesh.setEffect(scene.getEngine().createEffect("background", {
  79065. attributes: attribs,
  79066. uniformsNames: uniforms,
  79067. uniformBuffersNames: uniformBuffers,
  79068. samplers: samplers,
  79069. defines: join,
  79070. fallbacks: fallbacks,
  79071. onCompiled: onCompiled,
  79072. onError: this.onError,
  79073. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  79074. }, engine), defines);
  79075. this.buildUniformLayout();
  79076. }
  79077. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79078. return false;
  79079. }
  79080. defines._renderId = scene.getRenderId();
  79081. this._wasPreviouslyReady = true;
  79082. return true;
  79083. };
  79084. /**
  79085. * Build the uniform buffer used in the material.
  79086. */
  79087. BackgroundMaterial.prototype.buildUniformLayout = function () {
  79088. // Order is important !
  79089. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  79090. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  79091. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  79092. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  79093. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  79094. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  79095. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  79096. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  79097. this._uniformBuffer.addUniform("pointSize", 1);
  79098. this._uniformBuffer.addUniform("shadowLevel", 1);
  79099. this._uniformBuffer.addUniform("alpha", 1);
  79100. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  79101. this._uniformBuffer.addUniform("vReflectionControl", 4);
  79102. this._uniformBuffer.create();
  79103. };
  79104. /**
  79105. * Unbind the material.
  79106. */
  79107. BackgroundMaterial.prototype.unbind = function () {
  79108. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  79109. this._uniformBuffer.setTexture("diffuseSampler", null);
  79110. }
  79111. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  79112. this._uniformBuffer.setTexture("reflectionSampler", null);
  79113. }
  79114. _super.prototype.unbind.call(this);
  79115. };
  79116. /**
  79117. * Bind only the world matrix to the material.
  79118. * @param world The world matrix to bind.
  79119. */
  79120. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  79121. this._activeEffect.setMatrix("world", world);
  79122. };
  79123. /**
  79124. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  79125. * @param world The world matrix to bind.
  79126. * @param subMesh The submesh to bind for.
  79127. */
  79128. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79129. var scene = this.getScene();
  79130. var defines = subMesh._materialDefines;
  79131. if (!defines) {
  79132. return;
  79133. }
  79134. var effect = subMesh.effect;
  79135. if (!effect) {
  79136. return;
  79137. }
  79138. this._activeEffect = effect;
  79139. // Matrices
  79140. this.bindOnlyWorldMatrix(world);
  79141. // Bones
  79142. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  79143. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  79144. if (mustRebind) {
  79145. this._uniformBuffer.bindToEffect(effect, "Material");
  79146. this.bindViewProjection(effect);
  79147. var reflectionTexture = this._reflectionTexture;
  79148. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  79149. // Texture uniforms
  79150. if (scene.texturesEnabled) {
  79151. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79152. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  79153. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  79154. }
  79155. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79156. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  79157. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  79158. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  79159. }
  79160. }
  79161. if (this.shadowLevel > 0) {
  79162. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  79163. }
  79164. this._uniformBuffer.updateFloat("alpha", this.alpha);
  79165. // Point size
  79166. if (this.pointsCloud) {
  79167. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  79168. }
  79169. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  79170. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  79171. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  79172. }
  79173. // Textures
  79174. if (scene.texturesEnabled) {
  79175. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79176. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  79177. }
  79178. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79179. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  79180. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79181. }
  79182. else if (!defines.REFLECTIONBLUR) {
  79183. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79184. }
  79185. else {
  79186. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  79187. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  79188. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  79189. }
  79190. if (defines.REFLECTIONFRESNEL) {
  79191. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  79192. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  79193. }
  79194. }
  79195. }
  79196. // Clip plane
  79197. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  79198. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  79199. }
  79200. if (mustRebind || !this.isFrozen) {
  79201. if (scene.lightsEnabled) {
  79202. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  79203. }
  79204. // View
  79205. this.bindView(effect);
  79206. // Fog
  79207. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  79208. // image processing
  79209. this._imageProcessingConfiguration.bind(this._activeEffect);
  79210. }
  79211. this._uniformBuffer.update();
  79212. this._afterBind(mesh);
  79213. };
  79214. /**
  79215. * Dispose the material.
  79216. * @forceDisposeEffect Force disposal of the associated effect.
  79217. * @forceDisposeTextures Force disposal of the associated textures.
  79218. */
  79219. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  79220. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  79221. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  79222. if (forceDisposeTextures) {
  79223. if (this.diffuseTexture) {
  79224. this.diffuseTexture.dispose();
  79225. }
  79226. if (this.reflectionTexture) {
  79227. this.reflectionTexture.dispose();
  79228. }
  79229. }
  79230. this._renderTargets.dispose();
  79231. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79232. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79233. }
  79234. _super.prototype.dispose.call(this, forceDisposeEffect);
  79235. };
  79236. /**
  79237. * Clones the material.
  79238. * @name The cloned name.
  79239. * @returns The cloned material.
  79240. */
  79241. BackgroundMaterial.prototype.clone = function (name) {
  79242. var _this = this;
  79243. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  79244. };
  79245. /**
  79246. * Serializes the current material to its JSON representation.
  79247. * @returns The JSON representation.
  79248. */
  79249. BackgroundMaterial.prototype.serialize = function () {
  79250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79251. serializationObject.customType = "BABYLON.BackgroundMaterial";
  79252. return serializationObject;
  79253. };
  79254. /**
  79255. * Gets the class name of the material
  79256. * @returns "BackgroundMaterial"
  79257. */
  79258. BackgroundMaterial.prototype.getClassName = function () {
  79259. return "BackgroundMaterial";
  79260. };
  79261. /**
  79262. * Parse a JSON input to create back a background material.
  79263. * @param source
  79264. * @param scene
  79265. * @param rootUrl
  79266. * @returns the instantiated BackgroundMaterial.
  79267. */
  79268. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  79269. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  79270. };
  79271. /**
  79272. * Standard reflectance value at parallel view angle.
  79273. */
  79274. BackgroundMaterial.standardReflectance0 = 0.05;
  79275. /**
  79276. * Standard reflectance value at grazing angle.
  79277. */
  79278. BackgroundMaterial.standardReflectance90 = 0.5;
  79279. __decorate([
  79280. BABYLON.serializeAsColor3()
  79281. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  79282. __decorate([
  79283. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79284. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  79285. __decorate([
  79286. BABYLON.serialize()
  79287. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  79288. __decorate([
  79289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79290. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  79291. __decorate([
  79292. BABYLON.serializeAsColor3()
  79293. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  79294. __decorate([
  79295. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79296. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  79297. __decorate([
  79298. BABYLON.serialize()
  79299. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  79300. __decorate([
  79301. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79302. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  79303. __decorate([
  79304. BABYLON.serializeAsColor3()
  79305. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  79306. __decorate([
  79307. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79308. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  79309. __decorate([
  79310. BABYLON.serialize()
  79311. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  79312. __decorate([
  79313. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79314. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  79315. __decorate([
  79316. BABYLON.serializeAsTexture()
  79317. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  79318. __decorate([
  79319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79320. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  79321. __decorate([
  79322. BABYLON.serialize()
  79323. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  79324. __decorate([
  79325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79326. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  79327. __decorate([
  79328. BABYLON.serializeAsTexture()
  79329. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  79330. __decorate([
  79331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79332. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  79333. __decorate([
  79334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79335. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  79336. __decorate([
  79337. BABYLON.serialize()
  79338. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  79339. __decorate([
  79340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79341. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  79342. __decorate([
  79343. BABYLON.serialize()
  79344. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  79345. __decorate([
  79346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79347. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  79348. __decorate([
  79349. BABYLON.serializeAsVector3()
  79350. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  79351. __decorate([
  79352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79353. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  79354. __decorate([
  79355. BABYLON.serialize()
  79356. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  79357. __decorate([
  79358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79359. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  79360. __decorate([
  79361. BABYLON.serialize()
  79362. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  79363. __decorate([
  79364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79365. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  79366. __decorate([
  79367. BABYLON.serialize()
  79368. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  79369. __decorate([
  79370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79371. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  79372. __decorate([
  79373. BABYLON.serialize()
  79374. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  79375. __decorate([
  79376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79377. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  79378. __decorate([
  79379. BABYLON.serialize()
  79380. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  79381. __decorate([
  79382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79383. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  79384. __decorate([
  79385. BABYLON.serialize()
  79386. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  79387. __decorate([
  79388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79389. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  79390. __decorate([
  79391. BABYLON.serialize()
  79392. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  79393. __decorate([
  79394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79395. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  79396. __decorate([
  79397. BABYLON.serialize()
  79398. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  79399. __decorate([
  79400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79401. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  79402. __decorate([
  79403. BABYLON.serialize()
  79404. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  79405. __decorate([
  79406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79407. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  79408. __decorate([
  79409. BABYLON.serializeAsImageProcessingConfiguration()
  79410. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  79411. return BackgroundMaterial;
  79412. }(BABYLON.PushMaterial));
  79413. BABYLON.BackgroundMaterial = BackgroundMaterial;
  79414. })(BABYLON || (BABYLON = {}));
  79415. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  79416. var __assign = (this && this.__assign) || Object.assign || function(t) {
  79417. for (var s, i = 1, n = arguments.length; i < n; i++) {
  79418. s = arguments[i];
  79419. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  79420. t[p] = s[p];
  79421. }
  79422. return t;
  79423. };
  79424. var BABYLON;
  79425. (function (BABYLON) {
  79426. /**
  79427. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  79428. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  79429. * It also helps with the default setup of your imageProcessing configuration.
  79430. */
  79431. var EnvironmentHelper = /** @class */ (function () {
  79432. /**
  79433. * constructor
  79434. * @param options
  79435. * @param scene The scene to add the material to
  79436. */
  79437. function EnvironmentHelper(options, scene) {
  79438. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  79439. this._scene = scene;
  79440. this._setupBackground();
  79441. this._setupImageProcessing();
  79442. }
  79443. /**
  79444. * Creates the default options for the helper.
  79445. */
  79446. EnvironmentHelper._getDefaultOptions = function () {
  79447. return {
  79448. createGround: true,
  79449. groundSize: 15,
  79450. groundTexture: this._groundTextureCDNUrl,
  79451. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79452. groundOpacity: 0.9,
  79453. enableGroundShadow: true,
  79454. groundShadowLevel: 0.5,
  79455. enableGroundMirror: false,
  79456. groundMirrorSizeRatio: 0.3,
  79457. groundMirrorBlurKernel: 64,
  79458. groundMirrorAmount: 1,
  79459. groundMirrorFresnelWeight: 1,
  79460. groundMirrorFallOffDistance: 0,
  79461. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  79462. createSkybox: true,
  79463. skyboxSize: 20,
  79464. skyboxTexture: this._skyboxTextureCDNUrl,
  79465. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79466. backgroundYRotation: 0,
  79467. sizeAuto: true,
  79468. rootPosition: BABYLON.Vector3.Zero(),
  79469. setupImageProcessing: true,
  79470. environmentTexture: this._environmentTextureCDNUrl,
  79471. cameraExposure: 0.8,
  79472. cameraContrast: 1.2,
  79473. toneMappingEnabled: true,
  79474. };
  79475. };
  79476. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  79477. /**
  79478. * Gets the root mesh created by the helper.
  79479. */
  79480. get: function () {
  79481. return this._rootMesh;
  79482. },
  79483. enumerable: true,
  79484. configurable: true
  79485. });
  79486. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  79487. /**
  79488. * Gets the skybox created by the helper.
  79489. */
  79490. get: function () {
  79491. return this._skybox;
  79492. },
  79493. enumerable: true,
  79494. configurable: true
  79495. });
  79496. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  79497. /**
  79498. * Gets the skybox texture created by the helper.
  79499. */
  79500. get: function () {
  79501. return this._skyboxTexture;
  79502. },
  79503. enumerable: true,
  79504. configurable: true
  79505. });
  79506. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  79507. /**
  79508. * Gets the skybox material created by the helper.
  79509. */
  79510. get: function () {
  79511. return this._skyboxMaterial;
  79512. },
  79513. enumerable: true,
  79514. configurable: true
  79515. });
  79516. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  79517. /**
  79518. * Gets the ground mesh created by the helper.
  79519. */
  79520. get: function () {
  79521. return this._ground;
  79522. },
  79523. enumerable: true,
  79524. configurable: true
  79525. });
  79526. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  79527. /**
  79528. * Gets the ground texture created by the helper.
  79529. */
  79530. get: function () {
  79531. return this._groundTexture;
  79532. },
  79533. enumerable: true,
  79534. configurable: true
  79535. });
  79536. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  79537. /**
  79538. * Gets the ground mirror created by the helper.
  79539. */
  79540. get: function () {
  79541. return this._groundMirror;
  79542. },
  79543. enumerable: true,
  79544. configurable: true
  79545. });
  79546. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  79547. /**
  79548. * Gets the ground mirror render list to helps pushing the meshes
  79549. * you wish in the ground reflection.
  79550. */
  79551. get: function () {
  79552. if (this._groundMirror) {
  79553. return this._groundMirror.renderList;
  79554. }
  79555. return null;
  79556. },
  79557. enumerable: true,
  79558. configurable: true
  79559. });
  79560. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  79561. /**
  79562. * Gets the ground material created by the helper.
  79563. */
  79564. get: function () {
  79565. return this._groundMaterial;
  79566. },
  79567. enumerable: true,
  79568. configurable: true
  79569. });
  79570. /**
  79571. * Updates the background according to the new options
  79572. * @param options
  79573. */
  79574. EnvironmentHelper.prototype.updateOptions = function (options) {
  79575. var newOptions = __assign({}, this._options, options);
  79576. if (this._ground && !newOptions.createGround) {
  79577. this._ground.dispose();
  79578. this._ground = null;
  79579. }
  79580. if (this._groundMaterial && !newOptions.createGround) {
  79581. this._groundMaterial.dispose();
  79582. this._groundMaterial = null;
  79583. }
  79584. if (this._groundTexture) {
  79585. if (this._options.groundTexture != newOptions.groundTexture) {
  79586. this._groundTexture.dispose();
  79587. this._groundTexture = null;
  79588. }
  79589. }
  79590. if (this._skybox && !newOptions.createSkybox) {
  79591. this._skybox.dispose();
  79592. this._skybox = null;
  79593. }
  79594. if (this._skyboxMaterial && !newOptions.createSkybox) {
  79595. this._skyboxMaterial.dispose();
  79596. this._skyboxMaterial = null;
  79597. }
  79598. if (this._skyboxTexture) {
  79599. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  79600. this._skyboxTexture.dispose();
  79601. this._skyboxTexture = null;
  79602. }
  79603. }
  79604. if (this._groundMirror && !newOptions.enableGroundMirror) {
  79605. this._groundMirror.dispose();
  79606. this._groundMirror = null;
  79607. }
  79608. if (this._scene.environmentTexture) {
  79609. if (this._options.environmentTexture != newOptions.environmentTexture) {
  79610. this._scene.environmentTexture.dispose();
  79611. }
  79612. }
  79613. this._options = newOptions;
  79614. this._setupBackground();
  79615. this._setupImageProcessing();
  79616. };
  79617. /**
  79618. * Sets the primary color of all the available elements.
  79619. * @param color
  79620. */
  79621. EnvironmentHelper.prototype.setMainColor = function (color) {
  79622. if (this.groundMaterial) {
  79623. this.groundMaterial.primaryColor = color;
  79624. }
  79625. if (this.skyboxMaterial) {
  79626. this.skyboxMaterial.primaryColor = color;
  79627. }
  79628. if (this.groundMirror) {
  79629. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  79630. }
  79631. };
  79632. /**
  79633. * Setup the image processing according to the specified options.
  79634. */
  79635. EnvironmentHelper.prototype._setupImageProcessing = function () {
  79636. if (this._options.setupImageProcessing) {
  79637. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  79638. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  79639. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  79640. this._setupEnvironmentTexture();
  79641. }
  79642. };
  79643. /**
  79644. * Setup the environment texture according to the specified options.
  79645. */
  79646. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  79647. if (this._scene.environmentTexture) {
  79648. return;
  79649. }
  79650. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  79651. this._scene.environmentTexture = this._options.environmentTexture;
  79652. return;
  79653. }
  79654. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  79655. this._scene.environmentTexture = environmentTexture;
  79656. };
  79657. /**
  79658. * Setup the background according to the specified options.
  79659. */
  79660. EnvironmentHelper.prototype._setupBackground = function () {
  79661. if (!this._rootMesh) {
  79662. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  79663. }
  79664. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  79665. var sceneSize = this._getSceneSize();
  79666. if (this._options.createGround) {
  79667. this._setupGround(sceneSize);
  79668. this._setupGroundMaterial();
  79669. this._setupGroundDiffuseTexture();
  79670. if (this._options.enableGroundMirror) {
  79671. this._setupGroundMirrorTexture(sceneSize);
  79672. }
  79673. this._setupMirrorInGroundMaterial();
  79674. }
  79675. if (this._options.createSkybox) {
  79676. this._setupSkybox(sceneSize);
  79677. this._setupSkyboxMaterial();
  79678. this._setupSkyboxReflectionTexture();
  79679. }
  79680. this._rootMesh.position.x = sceneSize.rootPosition.x;
  79681. this._rootMesh.position.z = sceneSize.rootPosition.z;
  79682. this._rootMesh.position.y = sceneSize.rootPosition.y;
  79683. };
  79684. /**
  79685. * Get the scene sizes according to the setup.
  79686. */
  79687. EnvironmentHelper.prototype._getSceneSize = function () {
  79688. var groundSize = this._options.groundSize;
  79689. var skyboxSize = this._options.skyboxSize;
  79690. var rootPosition = this._options.rootPosition;
  79691. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  79692. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79693. }
  79694. var sceneExtends = this._scene.getWorldExtends();
  79695. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  79696. var bias = 0.0001;
  79697. if (this._options.sizeAuto) {
  79698. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  79699. this._scene.activeCamera.upperRadiusLimit) {
  79700. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  79701. }
  79702. if (this._scene.activeCamera) {
  79703. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  79704. }
  79705. var sceneDiagonalLenght = sceneDiagonal.length();
  79706. if (sceneDiagonalLenght > groundSize) {
  79707. groundSize = sceneDiagonalLenght * 2;
  79708. }
  79709. // 10 % bigger.
  79710. groundSize *= 1.1;
  79711. skyboxSize *= 1.5;
  79712. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  79713. rootPosition.y = sceneExtends.min.y - bias;
  79714. }
  79715. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79716. };
  79717. /**
  79718. * Setup the ground according to the specified options.
  79719. */
  79720. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  79721. var _this = this;
  79722. if (!this._ground) {
  79723. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  79724. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  79725. this._ground.parent = this._rootMesh;
  79726. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  79727. }
  79728. this._ground.receiveShadows = this._options.enableGroundShadow;
  79729. };
  79730. /**
  79731. * Setup the ground material according to the specified options.
  79732. */
  79733. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  79734. if (!this._groundMaterial) {
  79735. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  79736. }
  79737. this._groundMaterial.alpha = this._options.groundOpacity;
  79738. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  79739. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  79740. this._groundMaterial.primaryLevel = 1;
  79741. this._groundMaterial.primaryColor = this._options.groundColor;
  79742. this._groundMaterial.secondaryLevel = 0;
  79743. this._groundMaterial.tertiaryLevel = 0;
  79744. this._groundMaterial.useRGBColor = false;
  79745. this._groundMaterial.enableNoise = true;
  79746. if (this._ground) {
  79747. this._ground.material = this._groundMaterial;
  79748. }
  79749. };
  79750. /**
  79751. * Setup the ground diffuse texture according to the specified options.
  79752. */
  79753. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  79754. if (!this._groundMaterial) {
  79755. return;
  79756. }
  79757. if (this._groundTexture) {
  79758. return;
  79759. }
  79760. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  79761. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  79762. return;
  79763. }
  79764. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  79765. diffuseTexture.gammaSpace = false;
  79766. diffuseTexture.hasAlpha = true;
  79767. this._groundMaterial.diffuseTexture = diffuseTexture;
  79768. };
  79769. /**
  79770. * Setup the ground mirror texture according to the specified options.
  79771. */
  79772. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  79773. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79774. if (!this._groundMirror) {
  79775. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  79776. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  79777. this._groundMirror.anisotropicFilteringLevel = 1;
  79778. this._groundMirror.wrapU = wrapping;
  79779. this._groundMirror.wrapV = wrapping;
  79780. this._groundMirror.gammaSpace = false;
  79781. if (this._groundMirror.renderList) {
  79782. for (var i = 0; i < this._scene.meshes.length; i++) {
  79783. var mesh = this._scene.meshes[i];
  79784. if (mesh !== this._ground &&
  79785. mesh !== this._skybox &&
  79786. mesh !== this._rootMesh) {
  79787. this._groundMirror.renderList.push(mesh);
  79788. }
  79789. }
  79790. }
  79791. }
  79792. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  79793. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  79794. };
  79795. /**
  79796. * Setup the ground to receive the mirror texture.
  79797. */
  79798. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  79799. if (this._groundMaterial) {
  79800. this._groundMaterial.reflectionTexture = this._groundMirror;
  79801. this._groundMaterial.reflectionFresnel = true;
  79802. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  79803. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  79804. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  79805. }
  79806. };
  79807. /**
  79808. * Setup the skybox according to the specified options.
  79809. */
  79810. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  79811. var _this = this;
  79812. if (!this._skybox) {
  79813. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  79814. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  79815. }
  79816. this._skybox.parent = this._rootMesh;
  79817. };
  79818. /**
  79819. * Setup the skybox material according to the specified options.
  79820. */
  79821. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  79822. if (!this._skybox) {
  79823. return;
  79824. }
  79825. if (!this._skyboxMaterial) {
  79826. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  79827. }
  79828. this._skyboxMaterial.useRGBColor = false;
  79829. this._skyboxMaterial.primaryLevel = 1;
  79830. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  79831. this._skyboxMaterial.secondaryLevel = 0;
  79832. this._skyboxMaterial.tertiaryLevel = 0;
  79833. this._skyboxMaterial.enableNoise = true;
  79834. this._skybox.material = this._skyboxMaterial;
  79835. };
  79836. /**
  79837. * Setup the skybox reflection texture according to the specified options.
  79838. */
  79839. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  79840. if (!this._skyboxMaterial) {
  79841. return;
  79842. }
  79843. if (this._skyboxTexture) {
  79844. return;
  79845. }
  79846. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  79847. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79848. return;
  79849. }
  79850. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  79851. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  79852. this._skyboxTexture.gammaSpace = false;
  79853. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79854. };
  79855. /**
  79856. * Dispose all the elements created by the Helper.
  79857. */
  79858. EnvironmentHelper.prototype.dispose = function () {
  79859. if (this._groundMaterial) {
  79860. this._groundMaterial.dispose(true, true);
  79861. }
  79862. if (this._skyboxMaterial) {
  79863. this._skyboxMaterial.dispose(true, true);
  79864. }
  79865. this._rootMesh.dispose(false);
  79866. };
  79867. /**
  79868. * Default ground texture URL.
  79869. */
  79870. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  79871. /**
  79872. * Default skybox texture URL.
  79873. */
  79874. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  79875. /**
  79876. * Default environment texture URL.
  79877. */
  79878. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  79879. return EnvironmentHelper;
  79880. }());
  79881. BABYLON.EnvironmentHelper = EnvironmentHelper;
  79882. })(BABYLON || (BABYLON = {}));
  79883. //# sourceMappingURL=babylon.environmentHelper.js.map
  79884. 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}"};
  79885. 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.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\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};"};
  79886. (function universalModuleDefinition(root, factory) {
  79887. var f = factory();
  79888. if (root && root["BABYLON"]) {
  79889. return;
  79890. }
  79891. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  79892. globalObject["BABYLON"] = f;
  79893. if(typeof exports === 'object' && typeof module === 'object')
  79894. module.exports = f;
  79895. else if(typeof define === 'function' && define.amd)
  79896. define(["BABYLON"], factory);
  79897. else if(typeof exports === 'object')
  79898. exports["BABYLON"] = f;
  79899. else {
  79900. root["BABYLON"] = f;
  79901. }
  79902. })(this, function() {
  79903. return BABYLON;
  79904. });