babylon.max.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492
  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. var BABYLON;
  18. (function (BABYLON) {
  19. /**
  20. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  21. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  22. */
  23. var EffectFallbacks = /** @class */ (function () {
  24. function EffectFallbacks() {
  25. this._defines = {};
  26. this._currentRank = 32;
  27. this._maxRank = -1;
  28. }
  29. /**
  30. * Removes the fallback from the bound mesh.
  31. */
  32. EffectFallbacks.prototype.unBindMesh = function () {
  33. this._mesh = null;
  34. };
  35. /**
  36. * Adds a fallback on the specified property.
  37. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  38. * @param define The name of the define in the shader
  39. */
  40. EffectFallbacks.prototype.addFallback = function (rank, define) {
  41. if (!this._defines[rank]) {
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. this._defines[rank] = new Array();
  49. }
  50. this._defines[rank].push(define);
  51. };
  52. /**
  53. * Sets the mesh to use CPU skinning when needing to fallback.
  54. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  55. * @param mesh The mesh to use the fallbacks.
  56. */
  57. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  58. this._mesh = mesh;
  59. if (rank < this._currentRank) {
  60. this._currentRank = rank;
  61. }
  62. if (rank > this._maxRank) {
  63. this._maxRank = rank;
  64. }
  65. };
  66. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  67. /**
  68. * Checks to see if more fallbacks are still availible.
  69. */
  70. get: function () {
  71. return this._currentRank <= this._maxRank;
  72. },
  73. enumerable: true,
  74. configurable: true
  75. });
  76. /**
  77. * Removes the defines that shoould be removed when falling back.
  78. * @param currentDefines defines the current define statements for the shader.
  79. * @param effect defines the current effect we try to compile
  80. * @returns The resulting defines with defines of the current rank removed.
  81. */
  82. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  83. // First we try to switch to CPU skinning
  84. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  85. this._mesh.computeBonesUsingShaders = false;
  86. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  87. var scene = this._mesh.getScene();
  88. for (var index = 0; index < scene.meshes.length; index++) {
  89. var otherMesh = scene.meshes[index];
  90. if (!otherMesh.material) {
  91. continue;
  92. }
  93. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  94. continue;
  95. }
  96. if (otherMesh.material.getEffect() === effect) {
  97. otherMesh.computeBonesUsingShaders = false;
  98. }
  99. else {
  100. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  101. var subMesh = _a[_i];
  102. var subMeshEffect = subMesh.effect;
  103. if (subMeshEffect === effect) {
  104. otherMesh.computeBonesUsingShaders = false;
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. }
  111. else {
  112. var currentFallbacks = this._defines[this._currentRank];
  113. if (currentFallbacks) {
  114. for (var index = 0; index < currentFallbacks.length; index++) {
  115. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  116. }
  117. }
  118. this._currentRank++;
  119. }
  120. return currentDefines;
  121. };
  122. return EffectFallbacks;
  123. }());
  124. BABYLON.EffectFallbacks = EffectFallbacks;
  125. /**
  126. * Options to be used when creating an effect.
  127. */
  128. var EffectCreationOptions = /** @class */ (function () {
  129. function EffectCreationOptions() {
  130. }
  131. return EffectCreationOptions;
  132. }());
  133. BABYLON.EffectCreationOptions = EffectCreationOptions;
  134. /**
  135. * Effect containing vertex and fragment shader that can be executed on an object.
  136. */
  137. var Effect = /** @class */ (function () {
  138. /**
  139. * Instantiates an effect.
  140. * An effect can be used to create/manage/execute vertex and fragment shaders.
  141. * @param baseName Name of the effect.
  142. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  143. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  144. * @param samplers List of sampler variables that will be passed to the shader.
  145. * @param engine Engine to be used to render the effect
  146. * @param defines Define statements to be added to the shader.
  147. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  148. * @param onCompiled Callback that will be called when the shader is compiled.
  149. * @param onError Callback that will be called if an error occurs during shader compilation.
  150. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  151. */
  152. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  153. if (samplers === void 0) { samplers = null; }
  154. if (defines === void 0) { defines = null; }
  155. if (fallbacks === void 0) { fallbacks = null; }
  156. if (onCompiled === void 0) { onCompiled = null; }
  157. if (onError === void 0) { onError = null; }
  158. var _this = this;
  159. /**
  160. * Unique ID of the effect.
  161. */
  162. this.uniqueId = 0;
  163. /**
  164. * Observable that will be called when the shader is compiled.
  165. */
  166. this.onCompileObservable = new BABYLON.Observable();
  167. /**
  168. * Observable that will be called if an error occurs during shader compilation.
  169. */
  170. this.onErrorObservable = new BABYLON.Observable();
  171. /**
  172. * Observable that will be called when effect is bound.
  173. */
  174. this.onBindObservable = new BABYLON.Observable();
  175. this._uniformBuffersNames = {};
  176. this._isReady = false;
  177. this._compilationError = "";
  178. this.name = baseName;
  179. if (attributesNamesOrOptions.attributes) {
  180. var options = attributesNamesOrOptions;
  181. this._engine = uniformsNamesOrEngine;
  182. this._attributesNames = options.attributes;
  183. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  184. this._samplers = options.samplers;
  185. this.defines = options.defines;
  186. this.onError = options.onError;
  187. this.onCompiled = options.onCompiled;
  188. this._fallbacks = options.fallbacks;
  189. this._indexParameters = options.indexParameters;
  190. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  191. if (options.uniformBuffersNames) {
  192. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  193. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  194. }
  195. }
  196. }
  197. else {
  198. this._engine = engine;
  199. this.defines = defines;
  200. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  201. this._samplers = samplers;
  202. this._attributesNames = attributesNamesOrOptions;
  203. this.onError = onError;
  204. this.onCompiled = onCompiled;
  205. this._indexParameters = indexParameters;
  206. this._fallbacks = fallbacks;
  207. }
  208. this.uniqueId = Effect._uniqueIdSeed++;
  209. var vertexSource;
  210. var fragmentSource;
  211. if (baseName.vertexElement) {
  212. vertexSource = document.getElementById(baseName.vertexElement);
  213. if (!vertexSource) {
  214. vertexSource = baseName.vertexElement;
  215. }
  216. }
  217. else {
  218. vertexSource = baseName.vertex || baseName;
  219. }
  220. if (baseName.fragmentElement) {
  221. fragmentSource = document.getElementById(baseName.fragmentElement);
  222. if (!fragmentSource) {
  223. fragmentSource = baseName.fragmentElement;
  224. }
  225. }
  226. else {
  227. fragmentSource = baseName.fragment || baseName;
  228. }
  229. var finalVertexCode;
  230. this._loadVertexShaderAsync(vertexSource)
  231. .then(function (vertexCode) {
  232. return _this._processIncludesAsync(vertexCode);
  233. })
  234. .then(function (vertexCodeWithIncludes) {
  235. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  236. return _this._loadFragmentShaderAsync(fragmentSource);
  237. })
  238. .then(function (fragmentCode) {
  239. return _this._processIncludesAsync(fragmentCode);
  240. })
  241. .then(function (fragmentCodeWithIncludes) {
  242. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  243. if (baseName) {
  244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  246. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  247. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  248. }
  249. else {
  250. _this._vertexSourceCode = finalVertexCode;
  251. _this._fragmentSourceCode = migratedFragmentCode;
  252. }
  253. _this._prepareEffect();
  254. });
  255. }
  256. Object.defineProperty(Effect.prototype, "key", {
  257. /**
  258. * Unique key for this effect
  259. */
  260. get: function () {
  261. return this._key;
  262. },
  263. enumerable: true,
  264. configurable: true
  265. });
  266. /**
  267. * If the effect has been compiled and prepared.
  268. * @returns if the effect is compiled and prepared.
  269. */
  270. Effect.prototype.isReady = function () {
  271. return this._isReady;
  272. };
  273. /**
  274. * The engine the effect was initialized with.
  275. * @returns the engine.
  276. */
  277. Effect.prototype.getEngine = function () {
  278. return this._engine;
  279. };
  280. /**
  281. * The compiled webGL program for the effect
  282. * @returns the webGL program.
  283. */
  284. Effect.prototype.getProgram = function () {
  285. return this._program;
  286. };
  287. /**
  288. * The set of names of attribute variables for the shader.
  289. * @returns An array of attribute names.
  290. */
  291. Effect.prototype.getAttributesNames = function () {
  292. return this._attributesNames;
  293. };
  294. /**
  295. * Returns the attribute at the given index.
  296. * @param index The index of the attribute.
  297. * @returns The location of the attribute.
  298. */
  299. Effect.prototype.getAttributeLocation = function (index) {
  300. return this._attributes[index];
  301. };
  302. /**
  303. * Returns the attribute based on the name of the variable.
  304. * @param name of the attribute to look up.
  305. * @returns the attribute location.
  306. */
  307. Effect.prototype.getAttributeLocationByName = function (name) {
  308. var index = this._attributesNames.indexOf(name);
  309. return this._attributes[index];
  310. };
  311. /**
  312. * The number of attributes.
  313. * @returns the numnber of attributes.
  314. */
  315. Effect.prototype.getAttributesCount = function () {
  316. return this._attributes.length;
  317. };
  318. /**
  319. * Gets the index of a uniform variable.
  320. * @param uniformName of the uniform to look up.
  321. * @returns the index.
  322. */
  323. Effect.prototype.getUniformIndex = function (uniformName) {
  324. return this._uniformsNames.indexOf(uniformName);
  325. };
  326. /**
  327. * Returns the attribute based on the name of the variable.
  328. * @param uniformName of the uniform to look up.
  329. * @returns the location of the uniform.
  330. */
  331. Effect.prototype.getUniform = function (uniformName) {
  332. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  333. };
  334. /**
  335. * Returns an array of sampler variable names
  336. * @returns The array of sampler variable neames.
  337. */
  338. Effect.prototype.getSamplers = function () {
  339. return this._samplers;
  340. };
  341. /**
  342. * The error from the last compilation.
  343. * @returns the error string.
  344. */
  345. Effect.prototype.getCompilationError = function () {
  346. return this._compilationError;
  347. };
  348. /**
  349. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  350. * @param func The callback to be used.
  351. */
  352. Effect.prototype.executeWhenCompiled = function (func) {
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. };
  361. /** @ignore */
  362. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  363. if (BABYLON.Tools.IsWindowObjectExist()) {
  364. // DOM element ?
  365. if (vertex instanceof HTMLElement) {
  366. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  367. return Promise.resolve(vertexCode);
  368. }
  369. }
  370. // Base64 encoded ?
  371. if (vertex.substr(0, 7) === "base64:") {
  372. var vertexBinary = window.atob(vertex.substr(7));
  373. return Promise.resolve(vertexBinary);
  374. }
  375. // Is in local store ?
  376. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  377. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  378. }
  379. var vertexShaderUrl;
  380. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  381. vertexShaderUrl = vertex;
  382. }
  383. else {
  384. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  385. }
  386. // Vertex shader
  387. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (fragment instanceof HTMLElement) {
  394. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  395. return Promise.resolve(fragmentCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (fragment.substr(0, 7) === "base64:") {
  400. var fragmentBinary = window.atob(fragment.substr(7));
  401. return Promise.resolve(fragmentBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  406. }
  407. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  408. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  409. }
  410. var fragmentShaderUrl;
  411. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  412. fragmentShaderUrl = fragment;
  413. }
  414. else {
  415. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  416. }
  417. // Fragment shader
  418. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  419. };
  420. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  421. // Rebuild shaders source code
  422. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  423. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  424. vertexCode = prefix + vertexCode;
  425. fragmentCode = prefix + fragmentCode;
  426. // Number lines of shaders source code
  427. var i = 2;
  428. var regex = /\n/gm;
  429. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  430. i = 2;
  431. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  432. // Dump shaders name and formatted source code
  433. if (this.name.vertexElement) {
  434. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  435. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  436. }
  437. else if (this.name.vertex) {
  438. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  439. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  440. }
  441. else {
  442. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  443. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  444. }
  445. };
  446. ;
  447. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  448. var preparedSourceCode = this._processPrecision(sourceCode);
  449. if (this._engine.webGLVersion == 1) {
  450. return preparedSourceCode;
  451. }
  452. // Already converted
  453. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  454. return preparedSourceCode.replace("#version 300 es", "");
  455. }
  456. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  457. // Remove extensions
  458. // #extension GL_OES_standard_derivatives : enable
  459. // #extension GL_EXT_shader_texture_lod : enable
  460. // #extension GL_EXT_frag_depth : enable
  461. // #extension GL_EXT_draw_buffers : require
  462. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  463. var result = preparedSourceCode.replace(regex, "");
  464. // Migrate to GLSL v300
  465. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  466. result = result.replace(/attribute[ \t]/g, "in ");
  467. result = result.replace(/[ \t]attribute/g, " in");
  468. if (isFragment) {
  469. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  470. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  471. result = result.replace(/texture2D\s*\(/g, "texture(");
  472. result = result.replace(/textureCube\s*\(/g, "texture(");
  473. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  474. result = result.replace(/gl_FragColor/g, "glFragColor");
  475. result = result.replace(/gl_FragData/g, "glFragData");
  476. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  477. }
  478. return result;
  479. };
  480. Effect.prototype._processIncludesAsync = function (sourceCode) {
  481. var _this = this;
  482. return new Promise(function (resolve, reject) {
  483. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  484. var match = regex.exec(sourceCode);
  485. var returnValue = sourceCode;
  486. while (match != null) {
  487. var includeFile = match[1];
  488. // Uniform declaration
  489. if (includeFile.indexOf("__decl__") !== -1) {
  490. includeFile = includeFile.replace(/__decl__/, "");
  491. if (_this._engine.supportsUniformBuffers) {
  492. includeFile = includeFile.replace(/Vertex/, "Ubo");
  493. includeFile = includeFile.replace(/Fragment/, "Ubo");
  494. }
  495. includeFile = includeFile + "Declaration";
  496. }
  497. if (Effect.IncludesShadersStore[includeFile]) {
  498. // Substitution
  499. var includeContent = Effect.IncludesShadersStore[includeFile];
  500. if (match[2]) {
  501. var splits = match[3].split(",");
  502. for (var index = 0; index < splits.length; index += 2) {
  503. var source = new RegExp(splits[index], "g");
  504. var dest = splits[index + 1];
  505. includeContent = includeContent.replace(source, dest);
  506. }
  507. }
  508. if (match[4]) {
  509. var indexString = match[5];
  510. if (indexString.indexOf("..") !== -1) {
  511. var indexSplits = indexString.split("..");
  512. var minIndex = parseInt(indexSplits[0]);
  513. var maxIndex = parseInt(indexSplits[1]);
  514. var sourceIncludeContent = includeContent.slice(0);
  515. includeContent = "";
  516. if (isNaN(maxIndex)) {
  517. maxIndex = _this._indexParameters[indexSplits[1]];
  518. }
  519. for (var i = minIndex; i < maxIndex; i++) {
  520. if (!_this._engine.supportsUniformBuffers) {
  521. // Ubo replacement
  522. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  523. return p1 + "{X}";
  524. });
  525. }
  526. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  527. }
  528. }
  529. else {
  530. if (!_this._engine.supportsUniformBuffers) {
  531. // Ubo replacement
  532. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  533. return p1 + "{X}";
  534. });
  535. }
  536. includeContent = includeContent.replace(/\{X\}/g, indexString);
  537. }
  538. }
  539. // Replace
  540. returnValue = returnValue.replace(match[0], includeContent);
  541. }
  542. else {
  543. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  544. _this._engine._loadFileAsync(includeShaderUrl)
  545. .then(function (fileContent) {
  546. Effect.IncludesShadersStore[includeFile] = fileContent;
  547. return _this._processIncludesAsync(returnValue);
  548. })
  549. .then(function (returnValue) {
  550. resolve(returnValue);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. resolve(returnValue);
  557. });
  558. };
  559. Effect.prototype._processPrecision = function (source) {
  560. if (source.indexOf("precision highp float") === -1) {
  561. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  562. source = "precision mediump float;\n" + source;
  563. }
  564. else {
  565. source = "precision highp float;\n" + source;
  566. }
  567. }
  568. else {
  569. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  570. source = source.replace("precision highp float", "precision mediump float");
  571. }
  572. }
  573. return source;
  574. };
  575. /**
  576. * Recompiles the webGL program
  577. * @param vertexSourceCode The source code for the vertex shader.
  578. * @param fragmentSourceCode The source code for the fragment shader.
  579. * @param onCompiled Callback called when completed.
  580. * @param onError Callback called on error.
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. */
  616. Effect.prototype._prepareEffect = function () {
  617. var attributesNames = this._attributesNames;
  618. var defines = this.defines;
  619. var fallbacks = this._fallbacks;
  620. this._valueCache = {};
  621. var previousProgram = this._program;
  622. try {
  623. var engine = this._engine;
  624. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  625. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  626. }
  627. else {
  628. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  629. }
  630. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  631. if (engine.supportsUniformBuffers) {
  632. for (var name in this._uniformBuffersNames) {
  633. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  634. }
  635. }
  636. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  637. this._attributes = engine.getAttributes(this._program, attributesNames);
  638. var index;
  639. for (index = 0; index < this._samplers.length; index++) {
  640. var sampler = this.getUniform(this._samplers[index]);
  641. if (sampler == null) {
  642. this._samplers.splice(index, 1);
  643. index--;
  644. }
  645. }
  646. engine.bindSamplers(this);
  647. this._compilationError = "";
  648. this._isReady = true;
  649. if (this.onCompiled) {
  650. this.onCompiled(this);
  651. }
  652. this.onCompileObservable.notifyObservers(this);
  653. this.onCompileObservable.clear();
  654. // Unbind mesh reference in fallbacks
  655. if (this._fallbacks) {
  656. this._fallbacks.unBindMesh();
  657. }
  658. if (previousProgram) {
  659. this.getEngine()._deleteProgram(previousProgram);
  660. }
  661. }
  662. catch (e) {
  663. this._compilationError = e.message;
  664. // Let's go through fallbacks then
  665. BABYLON.Tools.Error("Unable to compile effect:");
  666. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  667. return " " + uniform;
  668. }));
  669. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  670. return " " + attribute;
  671. }));
  672. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else {
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. */
  715. Effect.prototype._bindTexture = function (channel, texture) {
  716. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  717. };
  718. /**
  719. * Sets a texture on the engine to be used in the shader.
  720. * @param channel Name of the sampler variable.
  721. * @param texture Texture to set.
  722. */
  723. Effect.prototype.setTexture = function (channel, texture) {
  724. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  725. };
  726. /**
  727. * Sets an array of textures on the engine to be used in the shader.
  728. * @param channel Name of the variable.
  729. * @param textures Textures to set.
  730. */
  731. Effect.prototype.setTextureArray = function (channel, textures) {
  732. if (this._samplers.indexOf(channel + "Ex") === -1) {
  733. var initialPos = this._samplers.indexOf(channel);
  734. for (var index = 1; index < textures.length; index++) {
  735. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  736. }
  737. }
  738. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  739. };
  740. /**
  741. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  742. * @param channel Name of the sampler variable.
  743. * @param postProcess Post process to get the input texture from.
  744. */
  745. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  746. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  747. };
  748. /** @ignore */
  749. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  750. var cache = this._valueCache[uniformName];
  751. var flag = matrix.updateFlag;
  752. if (cache !== undefined && cache === flag) {
  753. return false;
  754. }
  755. this._valueCache[uniformName] = flag;
  756. return true;
  757. };
  758. /** @ignore */
  759. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  760. var cache = this._valueCache[uniformName];
  761. if (!cache) {
  762. cache = [x, y];
  763. this._valueCache[uniformName] = cache;
  764. return true;
  765. }
  766. var changed = false;
  767. if (cache[0] !== x) {
  768. cache[0] = x;
  769. changed = true;
  770. }
  771. if (cache[1] !== y) {
  772. cache[1] = y;
  773. changed = true;
  774. }
  775. return changed;
  776. };
  777. /** @ignore */
  778. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  779. var cache = this._valueCache[uniformName];
  780. if (!cache) {
  781. cache = [x, y, z];
  782. this._valueCache[uniformName] = cache;
  783. return true;
  784. }
  785. var changed = false;
  786. if (cache[0] !== x) {
  787. cache[0] = x;
  788. changed = true;
  789. }
  790. if (cache[1] !== y) {
  791. cache[1] = y;
  792. changed = true;
  793. }
  794. if (cache[2] !== z) {
  795. cache[2] = z;
  796. changed = true;
  797. }
  798. return changed;
  799. };
  800. /** @ignore */
  801. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y, z, w];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. if (cache[2] !== z) {
  818. cache[2] = z;
  819. changed = true;
  820. }
  821. if (cache[3] !== w) {
  822. cache[3] = w;
  823. changed = true;
  824. }
  825. return changed;
  826. };
  827. /**
  828. * Binds a buffer to a uniform.
  829. * @param buffer Buffer to bind.
  830. * @param name Name of the uniform variable to bind to.
  831. */
  832. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  833. var bufferName = this._uniformBuffersNames[name];
  834. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  835. return;
  836. }
  837. Effect._baseCache[bufferName] = buffer;
  838. this._engine.bindUniformBufferBase(buffer, bufferName);
  839. };
  840. /**
  841. * Binds block to a uniform.
  842. * @param blockName Name of the block to bind.
  843. * @param index Index to bind.
  844. */
  845. Effect.prototype.bindUniformBlock = function (blockName, index) {
  846. this._engine.bindUniformBlock(this._program, blockName, index);
  847. };
  848. /**
  849. * Sets an interger value on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param value Value to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setInt = function (uniformName, value) {
  855. var cache = this._valueCache[uniformName];
  856. if (cache !== undefined && cache === value)
  857. return this;
  858. this._valueCache[uniformName] = value;
  859. this._engine.setInt(this.getUniform(uniformName), value);
  860. return this;
  861. };
  862. /**
  863. * Sets an int array on a uniform variable.
  864. * @param uniformName Name of the variable.
  865. * @param array array to be set.
  866. * @returns this effect.
  867. */
  868. Effect.prototype.setIntArray = function (uniformName, array) {
  869. this._valueCache[uniformName] = null;
  870. this._engine.setIntArray(this.getUniform(uniformName), array);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray2 = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray2(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray3 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray3(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray4 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray4(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an float array on a uniform variable.
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setFloatArray = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setFloatArray(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an array on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setArray = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setArray(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray2 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray2(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray3 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray3(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray4 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray4(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets matrices on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrices matrices to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1001. if (!matrices) {
  1002. return this;
  1003. }
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1006. return this;
  1007. };
  1008. /**
  1009. * Sets matrix on a uniform variable.
  1010. * @param uniformName Name of the variable.
  1011. * @param matrix matrix to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1015. if (this._cacheMatrix(uniformName, matrix)) {
  1016. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1017. }
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1022. * @param uniformName Name of the variable.
  1023. * @param matrix matrix to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a float on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param value value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setFloat = function (uniformName, value) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === value)
  1051. return this;
  1052. this._valueCache[uniformName] = value;
  1053. this._engine.setFloat(this.getUniform(uniformName), value);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a boolean on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param bool value to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setBool = function (uniformName, bool) {
  1063. var cache = this._valueCache[uniformName];
  1064. if (cache !== undefined && cache === bool)
  1065. return this;
  1066. this._valueCache[uniformName] = bool;
  1067. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a Vector2 on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param vector2 vector2 to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1077. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1078. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1079. }
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a float2 on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param x First float in float2.
  1086. * @param y Second float in float2.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1090. if (this._cacheFloat2(uniformName, x, y)) {
  1091. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1092. }
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a Vector3 on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param vector3 Value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1102. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a float3 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param x First float in float3.
  1111. * @param y Second float in float3.
  1112. * @param z Third float in float3.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1116. if (this._cacheFloat3(uniformName, x, y, z)) {
  1117. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector4 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector4 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1128. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1129. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float4 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float4.
  1137. * @param y Second float in float4.
  1138. * @param z Third float in float4.
  1139. * @param w Fourth float in float4.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1143. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1144. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Color3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param color3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setColor3 = function (uniformName, color3) {
  1155. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1156. this._engine.setColor3(this.getUniform(uniformName), color3);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a Color4 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param color3 Value to be set.
  1164. * @param alpha Alpha value to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1168. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1170. }
  1171. return this;
  1172. };
  1173. /**
  1174. * Sets a Color4 on a uniform variable
  1175. * @param uniformName defines the name of the variable
  1176. * @param color4 defines the value to be set
  1177. * @returns this effect.
  1178. */
  1179. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1180. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1181. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1182. }
  1183. return this;
  1184. };
  1185. /**
  1186. * Resets the cache of effects.
  1187. */
  1188. Effect.ResetCache = function () {
  1189. Effect._baseCache = {};
  1190. };
  1191. Effect._uniqueIdSeed = 0;
  1192. Effect._baseCache = {};
  1193. // Statics
  1194. /**
  1195. * Store of each shader (The can be looked up using effect.key)
  1196. */
  1197. Effect.ShadersStore = {};
  1198. /**
  1199. * Store of each included file for a shader (The can be looked up using effect.key)
  1200. */
  1201. Effect.IncludesShadersStore = {};
  1202. return Effect;
  1203. }());
  1204. BABYLON.Effect = Effect;
  1205. })(BABYLON || (BABYLON = {}));
  1206. //# sourceMappingURL=babylon.effect.js.map
  1207. //# sourceMappingURL=babylon.types.js.map
  1208. var BABYLON;
  1209. (function (BABYLON) {
  1210. var KeyboardEventTypes = /** @class */ (function () {
  1211. function KeyboardEventTypes() {
  1212. }
  1213. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1214. get: function () {
  1215. return KeyboardEventTypes._KEYDOWN;
  1216. },
  1217. enumerable: true,
  1218. configurable: true
  1219. });
  1220. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1221. get: function () {
  1222. return KeyboardEventTypes._KEYUP;
  1223. },
  1224. enumerable: true,
  1225. configurable: true
  1226. });
  1227. KeyboardEventTypes._KEYDOWN = 0x01;
  1228. KeyboardEventTypes._KEYUP = 0x02;
  1229. return KeyboardEventTypes;
  1230. }());
  1231. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1232. var KeyboardInfo = /** @class */ (function () {
  1233. function KeyboardInfo(type, event) {
  1234. this.type = type;
  1235. this.event = event;
  1236. }
  1237. return KeyboardInfo;
  1238. }());
  1239. BABYLON.KeyboardInfo = KeyboardInfo;
  1240. /**
  1241. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1242. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1243. */
  1244. var KeyboardInfoPre = /** @class */ (function (_super) {
  1245. __extends(KeyboardInfoPre, _super);
  1246. function KeyboardInfoPre(type, event) {
  1247. var _this = _super.call(this, type, event) || this;
  1248. _this.skipOnPointerObservable = false;
  1249. return _this;
  1250. }
  1251. return KeyboardInfoPre;
  1252. }(KeyboardInfo));
  1253. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1254. })(BABYLON || (BABYLON = {}));
  1255. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1256. var BABYLON;
  1257. (function (BABYLON) {
  1258. var PointerEventTypes = /** @class */ (function () {
  1259. function PointerEventTypes() {
  1260. }
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOWN;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERUP;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERMOVE;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERWHEEL;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERPICK;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERTAP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERDOUBLETAP;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. PointerEventTypes._POINTERDOWN = 0x01;
  1311. PointerEventTypes._POINTERUP = 0x02;
  1312. PointerEventTypes._POINTERMOVE = 0x04;
  1313. PointerEventTypes._POINTERWHEEL = 0x08;
  1314. PointerEventTypes._POINTERPICK = 0x10;
  1315. PointerEventTypes._POINTERTAP = 0x20;
  1316. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1317. return PointerEventTypes;
  1318. }());
  1319. BABYLON.PointerEventTypes = PointerEventTypes;
  1320. var PointerInfoBase = /** @class */ (function () {
  1321. function PointerInfoBase(type, event) {
  1322. this.type = type;
  1323. this.event = event;
  1324. }
  1325. return PointerInfoBase;
  1326. }());
  1327. BABYLON.PointerInfoBase = PointerInfoBase;
  1328. /**
  1329. * This class is used to store pointer related info for the onPrePointerObservable event.
  1330. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1331. */
  1332. var PointerInfoPre = /** @class */ (function (_super) {
  1333. __extends(PointerInfoPre, _super);
  1334. function PointerInfoPre(type, event, localX, localY) {
  1335. var _this = _super.call(this, type, event) || this;
  1336. _this.skipOnPointerObservable = false;
  1337. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1338. return _this;
  1339. }
  1340. return PointerInfoPre;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfoPre = PointerInfoPre;
  1343. /**
  1344. * This type contains all the data related to a pointer event in Babylon.js.
  1345. * 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.
  1346. */
  1347. var PointerInfo = /** @class */ (function (_super) {
  1348. __extends(PointerInfo, _super);
  1349. function PointerInfo(type, event, pickInfo) {
  1350. var _this = _super.call(this, type, event) || this;
  1351. _this.pickInfo = pickInfo;
  1352. return _this;
  1353. }
  1354. return PointerInfo;
  1355. }(PointerInfoBase));
  1356. BABYLON.PointerInfo = PointerInfo;
  1357. })(BABYLON || (BABYLON = {}));
  1358. //# sourceMappingURL=babylon.pointerEvents.js.map
  1359. var BABYLON;
  1360. (function (BABYLON) {
  1361. BABYLON.ToGammaSpace = 1 / 2.2;
  1362. BABYLON.ToLinearSpace = 2.2;
  1363. BABYLON.Epsilon = 0.001;
  1364. /**
  1365. * Class used to hold a RBG color
  1366. */
  1367. var Color3 = /** @class */ (function () {
  1368. /**
  1369. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1370. * @param r defines the red component (between 0 and 1, default is 0)
  1371. * @param g defines the green component (between 0 and 1, default is 0)
  1372. * @param b defines the blue component (between 0 and 1, default is 0)
  1373. */
  1374. function Color3(
  1375. /**
  1376. * Defines the red component (between 0 and 1, default is 0)
  1377. */
  1378. r,
  1379. /**
  1380. * Defines the green component (between 0 and 1, default is 0)
  1381. */
  1382. g,
  1383. /**
  1384. * Defines the blue component (between 0 and 1, default is 0)
  1385. */
  1386. b) {
  1387. if (r === void 0) { r = 0; }
  1388. if (g === void 0) { g = 0; }
  1389. if (b === void 0) { b = 0; }
  1390. this.r = r;
  1391. this.g = g;
  1392. this.b = b;
  1393. }
  1394. /**
  1395. * Creates a string with the Color3 current values
  1396. * @returns the string representation of the Color3 object
  1397. */
  1398. Color3.prototype.toString = function () {
  1399. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1400. };
  1401. /**
  1402. * Returns the string "Color3"
  1403. * @returns "Color3"
  1404. */
  1405. Color3.prototype.getClassName = function () {
  1406. return "Color3";
  1407. };
  1408. /**
  1409. * Compute the Color3 hash code
  1410. * @returns an unique number that can be used to hash Color3 objects
  1411. */
  1412. Color3.prototype.getHashCode = function () {
  1413. var hash = this.r || 0;
  1414. hash = (hash * 397) ^ (this.g || 0);
  1415. hash = (hash * 397) ^ (this.b || 0);
  1416. return hash;
  1417. };
  1418. // Operators
  1419. /**
  1420. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1421. * @param array defines the array where to store the r,g,b components
  1422. * @param index defines an optional index in the target array to define where to start storing values
  1423. * @returns the current Color3 object
  1424. */
  1425. Color3.prototype.toArray = function (array, index) {
  1426. if (index === undefined) {
  1427. index = 0;
  1428. }
  1429. array[index] = this.r;
  1430. array[index + 1] = this.g;
  1431. array[index + 2] = this.b;
  1432. return this;
  1433. };
  1434. /**
  1435. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1436. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1437. * @returns a new {BABYLON.Color4} object
  1438. */
  1439. Color3.prototype.toColor4 = function (alpha) {
  1440. if (alpha === void 0) { alpha = 1; }
  1441. return new Color4(this.r, this.g, this.b, alpha);
  1442. };
  1443. /**
  1444. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1445. * @returns the new array
  1446. */
  1447. Color3.prototype.asArray = function () {
  1448. var result = new Array();
  1449. this.toArray(result, 0);
  1450. return result;
  1451. };
  1452. /**
  1453. * Returns the luminance value
  1454. * @returns a float value
  1455. */
  1456. Color3.prototype.toLuminance = function () {
  1457. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1458. };
  1459. /**
  1460. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1461. * @param otherColor defines the second operand
  1462. * @returns the new Color3 object
  1463. */
  1464. Color3.prototype.multiply = function (otherColor) {
  1465. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1466. };
  1467. /**
  1468. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1469. * @param otherColor defines the second operand
  1470. * @param result defines the Color3 object where to store the result
  1471. * @returns the current Color3
  1472. */
  1473. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1474. result.r = this.r * otherColor.r;
  1475. result.g = this.g * otherColor.g;
  1476. result.b = this.b * otherColor.b;
  1477. return this;
  1478. };
  1479. /**
  1480. * Determines equality between Color3 objects
  1481. * @param otherColor defines the second operand
  1482. * @returns true if the rgb values are equal to the passed ones
  1483. */
  1484. Color3.prototype.equals = function (otherColor) {
  1485. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1486. };
  1487. /**
  1488. * Determines equality between the current Color3 object and a set of r,b,g values
  1489. * @param r defines the red component to check
  1490. * @param g defines the green component to check
  1491. * @param b defines the blue component to check
  1492. * @returns true if the rgb values are equal to the passed ones
  1493. */
  1494. Color3.prototype.equalsFloats = function (r, g, b) {
  1495. return this.r === r && this.g === g && this.b === b;
  1496. };
  1497. /**
  1498. * Multiplies in place each rgb value by scale
  1499. * @param scale defines the scaling factor
  1500. * @returns the updated Color3.
  1501. */
  1502. Color3.prototype.scale = function (scale) {
  1503. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1504. };
  1505. /**
  1506. * Multiplies the rgb values by scale and stores the result into "result"
  1507. * @param scale defines the scaling factor
  1508. * @param result defines the Color3 object where to store the result
  1509. * @returns the unmodified current Color3.
  1510. */
  1511. Color3.prototype.scaleToRef = function (scale, result) {
  1512. result.r = this.r * scale;
  1513. result.g = this.g * scale;
  1514. result.b = this.b * scale;
  1515. return this;
  1516. };
  1517. /**
  1518. * Clamps the rgb values by the min and max values and stores the result into "result"
  1519. * @param min defines minimum clamping value (default is 0)
  1520. * @param max defines maximum clamping value (default is 1)
  1521. * @param result defines color to store the result into
  1522. * @returns the original Color3
  1523. */
  1524. Color3.prototype.clampToRef = function (min, max, result) {
  1525. if (min === void 0) { min = 0; }
  1526. if (max === void 0) { max = 1; }
  1527. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1528. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1529. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1530. return this;
  1531. };
  1532. /**
  1533. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1534. * @param otherColor defines the second operand
  1535. * @returns the new Color3
  1536. */
  1537. Color3.prototype.add = function (otherColor) {
  1538. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1539. };
  1540. /**
  1541. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1542. * @param otherColor defines the second operand
  1543. * @param result defines Color3 object to store the result into
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.addToRef = function (otherColor, result) {
  1547. result.r = this.r + otherColor.r;
  1548. result.g = this.g + otherColor.g;
  1549. result.b = this.b + otherColor.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1554. * @param otherColor defines the second operand
  1555. * @returns the new Color3
  1556. */
  1557. Color3.prototype.subtract = function (otherColor) {
  1558. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1559. };
  1560. /**
  1561. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1562. * @param otherColor defines the second operand
  1563. * @param result defines Color3 object to store the result into
  1564. * @returns the unmodified current Color3
  1565. */
  1566. Color3.prototype.subtractToRef = function (otherColor, result) {
  1567. result.r = this.r - otherColor.r;
  1568. result.g = this.g - otherColor.g;
  1569. result.b = this.b - otherColor.b;
  1570. return this;
  1571. };
  1572. /**
  1573. * Copy the current object
  1574. * @returns a new Color3 copied the current one
  1575. */
  1576. Color3.prototype.clone = function () {
  1577. return new Color3(this.r, this.g, this.b);
  1578. };
  1579. /**
  1580. * Copies the rgb values from the source in the current Color3
  1581. * @param source defines the source Color3 object
  1582. * @returns the updated Color3 object
  1583. */
  1584. Color3.prototype.copyFrom = function (source) {
  1585. this.r = source.r;
  1586. this.g = source.g;
  1587. this.b = source.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Updates the Color3 rgb values from the passed floats
  1592. * @param r defines the red component to read from
  1593. * @param g defines the green component to read from
  1594. * @param b defines the blue component to read from
  1595. * @returns the current Color3 object
  1596. */
  1597. Color3.prototype.copyFromFloats = function (r, g, b) {
  1598. this.r = r;
  1599. this.g = g;
  1600. this.b = b;
  1601. return this;
  1602. };
  1603. /**
  1604. * Updates the Color3 rgb values from the passed floats
  1605. * @param r defines the red component to read from
  1606. * @param g defines the green component to read from
  1607. * @param b defines the blue component to read from
  1608. * @returns the current Color3 object
  1609. */
  1610. Color3.prototype.set = function (r, g, b) {
  1611. return this.copyFromFloats(r, g, b);
  1612. };
  1613. /**
  1614. * Compute the Color3 hexadecimal code as a string
  1615. * @returns a string containing the hexadecimal representation of the Color3 object
  1616. */
  1617. Color3.prototype.toHexString = function () {
  1618. var intR = (this.r * 255) | 0;
  1619. var intG = (this.g * 255) | 0;
  1620. var intB = (this.b * 255) | 0;
  1621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1622. };
  1623. /**
  1624. * Computes a new Color3 converted from the current one to linear space
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.prototype.toLinearSpace = function () {
  1628. var convertedColor = new Color3();
  1629. this.toLinearSpaceToRef(convertedColor);
  1630. return convertedColor;
  1631. };
  1632. /**
  1633. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1634. * @param convertedColor defines the Color3 object where to store the linear space version
  1635. * @returns the unmodified Color3
  1636. */
  1637. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1638. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1639. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1640. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1641. return this;
  1642. };
  1643. /**
  1644. * Computes a new Color3 converted from the current one to gamma space
  1645. * @returns a new Color3 object
  1646. */
  1647. Color3.prototype.toGammaSpace = function () {
  1648. var convertedColor = new Color3();
  1649. this.toGammaSpaceToRef(convertedColor);
  1650. return convertedColor;
  1651. };
  1652. /**
  1653. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1654. * @param convertedColor defines the Color3 object where to store the gamma space version
  1655. * @returns the unmodified Color3
  1656. */
  1657. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1658. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1659. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1660. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1661. return this;
  1662. };
  1663. // Statics
  1664. /**
  1665. * Creates a new Color3 from the string containing valid hexadecimal values
  1666. * @param hex defines a string containing valid hexadecimal values
  1667. * @returns a new Color3 object
  1668. */
  1669. Color3.FromHexString = function (hex) {
  1670. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1671. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1672. return new Color3(0, 0, 0);
  1673. }
  1674. var r = parseInt(hex.substring(1, 3), 16);
  1675. var g = parseInt(hex.substring(3, 5), 16);
  1676. var b = parseInt(hex.substring(5, 7), 16);
  1677. return Color3.FromInts(r, g, b);
  1678. };
  1679. /**
  1680. * Creates a new Vector3 from the starting index of the passed array
  1681. * @param array defines the source array
  1682. * @param offset defines an offset in the source array
  1683. * @returns a new Color3 object
  1684. */
  1685. Color3.FromArray = function (array, offset) {
  1686. if (offset === void 0) { offset = 0; }
  1687. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1688. };
  1689. /**
  1690. * Creates a new Color3 from integer values (< 256)
  1691. * @param r defines the red component to read from (value between 0 and 255)
  1692. * @param g defines the green component to read from (value between 0 and 255)
  1693. * @param b defines the blue component to read from (value between 0 and 255)
  1694. * @returns a new Color3 object
  1695. */
  1696. Color3.FromInts = function (r, g, b) {
  1697. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1698. };
  1699. /**
  1700. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1701. * @param start defines the start Color3 value
  1702. * @param end defines the end Color3 value
  1703. * @param amount defines the gradient value between start and end
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.Lerp = function (start, end, amount) {
  1707. var r = start.r + ((end.r - start.r) * amount);
  1708. var g = start.g + ((end.g - start.g) * amount);
  1709. var b = start.b + ((end.b - start.b) * amount);
  1710. return new Color3(r, g, b);
  1711. };
  1712. /**
  1713. * Returns a Color3 value containing a red color
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Red = function () { return new Color3(1, 0, 0); };
  1717. /**
  1718. * Returns a Color3 value containing a green color
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.Green = function () { return new Color3(0, 1, 0); };
  1722. /**
  1723. * Returns a Color3 value containing a blue color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1727. /**
  1728. * Returns a Color3 value containing a black color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Black = function () { return new Color3(0, 0, 0); };
  1732. /**
  1733. * Returns a Color3 value containing a white color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.White = function () { return new Color3(1, 1, 1); };
  1737. /**
  1738. * Returns a Color3 value containing a purple color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1742. /**
  1743. * Returns a Color3 value containing a magenta color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a yellow color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a gray color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1757. /**
  1758. * Returns a Color3 value containing a teal color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1762. /**
  1763. * Returns a Color3 value containing a random color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1767. return Color3;
  1768. }());
  1769. BABYLON.Color3 = Color3;
  1770. /**
  1771. * Class used to hold a RBGA color
  1772. */
  1773. var Color4 = /** @class */ (function () {
  1774. /**
  1775. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1776. * @param r defines the red component (between 0 and 1, default is 0)
  1777. * @param g defines the green component (between 0 and 1, default is 0)
  1778. * @param b defines the blue component (between 0 and 1, default is 0)
  1779. * @param a defines the alpha component (between 0 and 1, default is 1)
  1780. */
  1781. function Color4(
  1782. /**
  1783. * Defines the red component (between 0 and 1, default is 0)
  1784. */
  1785. r,
  1786. /**
  1787. * Defines the green component (between 0 and 1, default is 0)
  1788. */
  1789. g,
  1790. /**
  1791. * Defines the blue component (between 0 and 1, default is 0)
  1792. */
  1793. b,
  1794. /**
  1795. * Defines the alpha component (between 0 and 1, default is 1)
  1796. */
  1797. a) {
  1798. if (r === void 0) { r = 0; }
  1799. if (g === void 0) { g = 0; }
  1800. if (b === void 0) { b = 0; }
  1801. if (a === void 0) { a = 1; }
  1802. this.r = r;
  1803. this.g = g;
  1804. this.b = b;
  1805. this.a = a;
  1806. }
  1807. // Operators
  1808. /**
  1809. * Adds in place the passed Color4 values to the current Color4 object
  1810. * @param right defines the second operand
  1811. * @returns the current updated Color4 object
  1812. */
  1813. Color4.prototype.addInPlace = function (right) {
  1814. this.r += right.r;
  1815. this.g += right.g;
  1816. this.b += right.b;
  1817. this.a += right.a;
  1818. return this;
  1819. };
  1820. /**
  1821. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1822. * @returns the new array
  1823. */
  1824. Color4.prototype.asArray = function () {
  1825. var result = new Array();
  1826. this.toArray(result, 0);
  1827. return result;
  1828. };
  1829. /**
  1830. * Stores from the starting index in the passed array the Color4 successive values
  1831. * @param array defines the array where to store the r,g,b components
  1832. * @param index defines an optional index in the target array to define where to start storing values
  1833. * @returns the current Color4 object
  1834. */
  1835. Color4.prototype.toArray = function (array, index) {
  1836. if (index === undefined) {
  1837. index = 0;
  1838. }
  1839. array[index] = this.r;
  1840. array[index + 1] = this.g;
  1841. array[index + 2] = this.b;
  1842. array[index + 3] = this.a;
  1843. return this;
  1844. };
  1845. /**
  1846. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1847. * @param right defines the second operand
  1848. * @returns a new Color4 object
  1849. */
  1850. Color4.prototype.add = function (right) {
  1851. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1852. };
  1853. /**
  1854. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1855. * @param right defines the second operand
  1856. * @returns a new Color4 object
  1857. */
  1858. Color4.prototype.subtract = function (right) {
  1859. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1860. };
  1861. /**
  1862. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1863. * @param right defines the second operand
  1864. * @param result defines the Color4 object where to store the result
  1865. * @returns the current Color4 object
  1866. */
  1867. Color4.prototype.subtractToRef = function (right, result) {
  1868. result.r = this.r - right.r;
  1869. result.g = this.g - right.g;
  1870. result.b = this.b - right.b;
  1871. result.a = this.a - right.a;
  1872. return this;
  1873. };
  1874. /**
  1875. * Creates a new Color4 with the current Color4 values multiplied by scale
  1876. * @param scale defines the scaling factor to apply
  1877. * @returns a new Color4 object
  1878. */
  1879. Color4.prototype.scale = function (scale) {
  1880. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1881. };
  1882. /**
  1883. * Multiplies the current Color4 values by scale and stores the result in "result"
  1884. * @param scale defines the scaling factor to apply
  1885. * @param result defines the Color4 object where to store the result
  1886. * @returns the current Color4.
  1887. */
  1888. Color4.prototype.scaleToRef = function (scale, result) {
  1889. result.r = this.r * scale;
  1890. result.g = this.g * scale;
  1891. result.b = this.b * scale;
  1892. result.a = this.a * scale;
  1893. return this;
  1894. };
  1895. /**
  1896. * Clamps the rgb values by the min and max values and stores the result into "result"
  1897. * @param min defines minimum clamping value (default is 0)
  1898. * @param max defines maximum clamping value (default is 1)
  1899. * @param result defines color to store the result into.
  1900. * @returns the cuurent Color4
  1901. */
  1902. Color4.prototype.clampToRef = function (min, max, result) {
  1903. if (min === void 0) { min = 0; }
  1904. if (max === void 0) { max = 1; }
  1905. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1906. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1907. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1908. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1909. return this;
  1910. };
  1911. /**
  1912. * Multipy an Color4 value by another and return a new Color4 object
  1913. * @param color defines the Color4 value to multiply by
  1914. * @returns a new Color4 object
  1915. */
  1916. Color4.prototype.multiply = function (color) {
  1917. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1918. };
  1919. /**
  1920. * Multipy a Color4 value by another and push the result in a reference value
  1921. * @param color defines the Color4 value to multiply by
  1922. * @param result defines the Color4 to fill the result in
  1923. * @returns the result Color4
  1924. */
  1925. Color4.prototype.multiplyToRef = function (color, result) {
  1926. result.r = this.r * color.r;
  1927. result.g = this.g * color.g;
  1928. result.b = this.b * color.b;
  1929. result.a = this.a * color.a;
  1930. return result;
  1931. };
  1932. /**
  1933. * Creates a string with the Color4 current values
  1934. * @returns the string representation of the Color4 object
  1935. */
  1936. Color4.prototype.toString = function () {
  1937. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1938. };
  1939. /**
  1940. * Returns the string "Color4"
  1941. * @returns "Color4"
  1942. */
  1943. Color4.prototype.getClassName = function () {
  1944. return "Color4";
  1945. };
  1946. /**
  1947. * Compute the Color4 hash code
  1948. * @returns an unique number that can be used to hash Color4 objects
  1949. */
  1950. Color4.prototype.getHashCode = function () {
  1951. var hash = this.r || 0;
  1952. hash = (hash * 397) ^ (this.g || 0);
  1953. hash = (hash * 397) ^ (this.b || 0);
  1954. hash = (hash * 397) ^ (this.a || 0);
  1955. return hash;
  1956. };
  1957. /**
  1958. * Creates a new Color4 copied from the current one
  1959. * @returns a new Color4 object
  1960. */
  1961. Color4.prototype.clone = function () {
  1962. return new Color4(this.r, this.g, this.b, this.a);
  1963. };
  1964. /**
  1965. * Copies the passed Color4 values into the current one
  1966. * @param source defines the source Color4 object
  1967. * @returns the current updated Color4 object
  1968. */
  1969. Color4.prototype.copyFrom = function (source) {
  1970. this.r = source.r;
  1971. this.g = source.g;
  1972. this.b = source.b;
  1973. this.a = source.a;
  1974. return this;
  1975. };
  1976. /**
  1977. * Copies the passed float values into the current one
  1978. * @param r defines the red component to read from
  1979. * @param g defines the green component to read from
  1980. * @param b defines the blue component to read from
  1981. * @param a defines the alpha component to read from
  1982. * @returns the current updated Color4 object
  1983. */
  1984. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1985. this.r = r;
  1986. this.g = g;
  1987. this.b = b;
  1988. this.a = a;
  1989. return this;
  1990. };
  1991. /**
  1992. * Copies the passed float values into the current one
  1993. * @param r defines the red component to read from
  1994. * @param g defines the green component to read from
  1995. * @param b defines the blue component to read from
  1996. * @param a defines the alpha component to read from
  1997. * @returns the current updated Color4 object
  1998. */
  1999. Color4.prototype.set = function (r, g, b, a) {
  2000. return this.copyFromFloats(r, g, b, a);
  2001. };
  2002. /**
  2003. * Compute the Color4 hexadecimal code as a string
  2004. * @returns a string containing the hexadecimal representation of the Color4 object
  2005. */
  2006. Color4.prototype.toHexString = function () {
  2007. var intR = (this.r * 255) | 0;
  2008. var intG = (this.g * 255) | 0;
  2009. var intB = (this.b * 255) | 0;
  2010. var intA = (this.a * 255) | 0;
  2011. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2012. };
  2013. /**
  2014. * Computes a new Color4 converted from the current one to linear space
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.toLinearSpace = function () {
  2018. var convertedColor = new Color4();
  2019. this.toLinearSpaceToRef(convertedColor);
  2020. return convertedColor;
  2021. };
  2022. /**
  2023. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2024. * @param convertedColor defines the Color4 object where to store the linear space version
  2025. * @returns the unmodified Color4
  2026. */
  2027. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2028. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2029. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2030. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2031. convertedColor.a = this.a;
  2032. return this;
  2033. };
  2034. /**
  2035. * Computes a new Color4 converted from the current one to gamma space
  2036. * @returns a new Color4 object
  2037. */
  2038. Color4.prototype.toGammaSpace = function () {
  2039. var convertedColor = new Color4();
  2040. this.toGammaSpaceToRef(convertedColor);
  2041. return convertedColor;
  2042. };
  2043. /**
  2044. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2045. * @param convertedColor defines the Color4 object where to store the gamma space version
  2046. * @returns the unmodified Color4
  2047. */
  2048. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2049. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2050. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2051. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2052. convertedColor.a = this.a;
  2053. return this;
  2054. };
  2055. // Statics
  2056. /**
  2057. * Creates a new Color4 from the string containing valid hexadecimal values
  2058. * @param hex defines a string containing valid hexadecimal values
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromHexString = function (hex) {
  2062. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2063. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2064. return new Color4(0.0, 0.0, 0.0, 0.0);
  2065. }
  2066. var r = parseInt(hex.substring(1, 3), 16);
  2067. var g = parseInt(hex.substring(3, 5), 16);
  2068. var b = parseInt(hex.substring(5, 7), 16);
  2069. var a = parseInt(hex.substring(7, 9), 16);
  2070. return Color4.FromInts(r, g, b, a);
  2071. };
  2072. /**
  2073. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2074. * @param left defines the start value
  2075. * @param right defines the end value
  2076. * @param amount defines the gradient factor
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.Lerp = function (left, right, amount) {
  2080. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2081. Color4.LerpToRef(left, right, amount, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2086. * @param left defines the start value
  2087. * @param right defines the end value
  2088. * @param amount defines the gradient factor
  2089. * @param result defines the Color4 object where to store data
  2090. */
  2091. Color4.LerpToRef = function (left, right, amount, result) {
  2092. result.r = left.r + (right.r - left.r) * amount;
  2093. result.g = left.g + (right.g - left.g) * amount;
  2094. result.b = left.b + (right.b - left.b) * amount;
  2095. result.a = left.a + (right.a - left.a) * amount;
  2096. };
  2097. /**
  2098. * Creates a new Color4 from the starting index element of the passed array
  2099. * @param array defines the source array to read from
  2100. * @param offset defines the offset in the source array
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.FromArray = function (array, offset) {
  2104. if (offset === void 0) { offset = 0; }
  2105. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2106. };
  2107. /**
  2108. * Creates a new Color3 from integer values (< 256)
  2109. * @param r defines the red component to read from (value between 0 and 255)
  2110. * @param g defines the green component to read from (value between 0 and 255)
  2111. * @param b defines the blue component to read from (value between 0 and 255)
  2112. * @param a defines the alpha component to read from (value between 0 and 255)
  2113. * @returns a new Color3 object
  2114. */
  2115. Color4.FromInts = function (r, g, b, a) {
  2116. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2117. };
  2118. /**
  2119. * Check the content of a given array and convert it to an array containing RGBA data
  2120. * If the original array was already containing count * 4 values then it is returned directly
  2121. * @param colors defines the array to check
  2122. * @param count defines the number of RGBA data to expect
  2123. * @returns an array containing count * 4 values (RGBA)
  2124. */
  2125. Color4.CheckColors4 = function (colors, count) {
  2126. // Check if color3 was used
  2127. if (colors.length === count * 3) {
  2128. var colors4 = [];
  2129. for (var index = 0; index < colors.length; index += 3) {
  2130. var newIndex = (index / 3) * 4;
  2131. colors4[newIndex] = colors[index];
  2132. colors4[newIndex + 1] = colors[index + 1];
  2133. colors4[newIndex + 2] = colors[index + 2];
  2134. colors4[newIndex + 3] = 1.0;
  2135. }
  2136. return colors4;
  2137. }
  2138. return colors;
  2139. };
  2140. return Color4;
  2141. }());
  2142. BABYLON.Color4 = Color4;
  2143. var Vector2 = /** @class */ (function () {
  2144. /**
  2145. * Creates a new Vector2 from the passed x and y coordinates.
  2146. */
  2147. function Vector2(x, y) {
  2148. this.x = x;
  2149. this.y = y;
  2150. }
  2151. /**
  2152. * Returns a string with the Vector2 coordinates.
  2153. */
  2154. Vector2.prototype.toString = function () {
  2155. return "{X: " + this.x + " Y:" + this.y + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Vector2"
  2159. */
  2160. Vector2.prototype.getClassName = function () {
  2161. return "Vector2";
  2162. };
  2163. /**
  2164. * Returns the Vector2 hash code as a number.
  2165. */
  2166. Vector2.prototype.getHashCode = function () {
  2167. var hash = this.x || 0;
  2168. hash = (hash * 397) ^ (this.y || 0);
  2169. return hash;
  2170. };
  2171. // Operators
  2172. /**
  2173. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2174. * Returns the Vector2.
  2175. */
  2176. Vector2.prototype.toArray = function (array, index) {
  2177. if (index === void 0) { index = 0; }
  2178. array[index] = this.x;
  2179. array[index + 1] = this.y;
  2180. return this;
  2181. };
  2182. /**
  2183. * Returns a new array with 2 elements : the Vector2 coordinates.
  2184. */
  2185. Vector2.prototype.asArray = function () {
  2186. var result = new Array();
  2187. this.toArray(result, 0);
  2188. return result;
  2189. };
  2190. /**
  2191. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2192. * Returns the updated Vector2.
  2193. */
  2194. Vector2.prototype.copyFrom = function (source) {
  2195. this.x = source.x;
  2196. this.y = source.y;
  2197. return this;
  2198. };
  2199. /**
  2200. * Sets the Vector2 coordinates with the passed floats.
  2201. * Returns the updated Vector2.
  2202. */
  2203. Vector2.prototype.copyFromFloats = function (x, y) {
  2204. this.x = x;
  2205. this.y = y;
  2206. return this;
  2207. };
  2208. /**
  2209. * Sets the Vector2 coordinates with the passed floats.
  2210. * Returns the updated Vector2.
  2211. */
  2212. Vector2.prototype.set = function (x, y) {
  2213. return this.copyFromFloats(x, y);
  2214. };
  2215. /**
  2216. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2217. */
  2218. Vector2.prototype.add = function (otherVector) {
  2219. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2220. };
  2221. /**
  2222. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2223. * Returns the Vector2.
  2224. */
  2225. Vector2.prototype.addToRef = function (otherVector, result) {
  2226. result.x = this.x + otherVector.x;
  2227. result.y = this.y + otherVector.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2232. * Returns the updated Vector2.
  2233. */
  2234. Vector2.prototype.addInPlace = function (otherVector) {
  2235. this.x += otherVector.x;
  2236. this.y += otherVector.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2241. */
  2242. Vector2.prototype.addVector3 = function (otherVector) {
  2243. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2247. */
  2248. Vector2.prototype.subtract = function (otherVector) {
  2249. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2256. result.x = this.x - otherVector.x;
  2257. result.y = this.y - otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.subtractInPlace = function (otherVector) {
  2265. this.x -= otherVector.x;
  2266. this.y -= otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2271. * Returns the updated Vector2.
  2272. */
  2273. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2274. this.x *= otherVector.x;
  2275. this.y *= otherVector.y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2280. */
  2281. Vector2.prototype.multiply = function (otherVector) {
  2282. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2283. };
  2284. /**
  2285. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2286. * Returns the Vector2.
  2287. */
  2288. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2289. result.x = this.x * otherVector.x;
  2290. result.y = this.y * otherVector.y;
  2291. return this;
  2292. };
  2293. /**
  2294. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2295. */
  2296. Vector2.prototype.multiplyByFloats = function (x, y) {
  2297. return new Vector2(this.x * x, this.y * y);
  2298. };
  2299. /**
  2300. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2301. */
  2302. Vector2.prototype.divide = function (otherVector) {
  2303. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2304. };
  2305. /**
  2306. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2307. * Returns the Vector2.
  2308. */
  2309. Vector2.prototype.divideToRef = function (otherVector, result) {
  2310. result.x = this.x / otherVector.x;
  2311. result.y = this.y / otherVector.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Divides the current Vector3 coordinates by the passed ones.
  2316. * Returns the updated Vector3.
  2317. */
  2318. Vector2.prototype.divideInPlace = function (otherVector) {
  2319. return this.divideToRef(otherVector, this);
  2320. };
  2321. /**
  2322. * Returns a new Vector2 with current Vector2 negated coordinates.
  2323. */
  2324. Vector2.prototype.negate = function () {
  2325. return new Vector2(-this.x, -this.y);
  2326. };
  2327. /**
  2328. * Multiply the Vector2 coordinates by scale.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.scaleInPlace = function (scale) {
  2332. this.x *= scale;
  2333. this.y *= scale;
  2334. return this;
  2335. };
  2336. /**
  2337. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2338. */
  2339. Vector2.prototype.scale = function (scale) {
  2340. return new Vector2(this.x * scale, this.y * scale);
  2341. };
  2342. /**
  2343. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2344. */
  2345. Vector2.prototype.equals = function (otherVector) {
  2346. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2347. };
  2348. /**
  2349. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2350. */
  2351. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2352. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2353. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2354. };
  2355. // Properties
  2356. /**
  2357. * Returns the vector length (float).
  2358. */
  2359. Vector2.prototype.length = function () {
  2360. return Math.sqrt(this.x * this.x + this.y * this.y);
  2361. };
  2362. /**
  2363. * Returns the vector squared length (float);
  2364. */
  2365. Vector2.prototype.lengthSquared = function () {
  2366. return (this.x * this.x + this.y * this.y);
  2367. };
  2368. // Methods
  2369. /**
  2370. * Normalize the vector.
  2371. * Returns the updated Vector2.
  2372. */
  2373. Vector2.prototype.normalize = function () {
  2374. var len = this.length();
  2375. if (len === 0)
  2376. return this;
  2377. var num = 1.0 / len;
  2378. this.x *= num;
  2379. this.y *= num;
  2380. return this;
  2381. };
  2382. /**
  2383. * Returns a new Vector2 copied from the Vector2.
  2384. */
  2385. Vector2.prototype.clone = function () {
  2386. return new Vector2(this.x, this.y);
  2387. };
  2388. // Statics
  2389. /**
  2390. * Returns a new Vector2(0, 0)
  2391. */
  2392. Vector2.Zero = function () {
  2393. return new Vector2(0, 0);
  2394. };
  2395. /**
  2396. * Returns a new Vector2(1, 1)
  2397. */
  2398. Vector2.One = function () {
  2399. return new Vector2(1, 1);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 set from the passed index element of the passed array.
  2403. */
  2404. Vector2.FromArray = function (array, offset) {
  2405. if (offset === void 0) { offset = 0; }
  2406. return new Vector2(array[offset], array[offset + 1]);
  2407. };
  2408. /**
  2409. * Sets "result" from the passed index element of the passed array.
  2410. */
  2411. Vector2.FromArrayToRef = function (array, offset, result) {
  2412. result.x = array[offset];
  2413. result.y = array[offset + 1];
  2414. };
  2415. /**
  2416. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2417. */
  2418. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2419. var squared = amount * amount;
  2420. var cubed = amount * squared;
  2421. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2422. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2423. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2424. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2425. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2426. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2427. return new Vector2(x, y);
  2428. };
  2429. /**
  2430. * 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".
  2431. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2432. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2433. */
  2434. Vector2.Clamp = function (value, min, max) {
  2435. var x = value.x;
  2436. x = (x > max.x) ? max.x : x;
  2437. x = (x < min.x) ? min.x : x;
  2438. var y = value.y;
  2439. y = (y > max.y) ? max.y : y;
  2440. y = (y < min.y) ? min.y : y;
  2441. return new Vector2(x, y);
  2442. };
  2443. /**
  2444. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2445. */
  2446. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2447. var squared = amount * amount;
  2448. var cubed = amount * squared;
  2449. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2450. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2451. var part3 = (cubed - (2.0 * squared)) + amount;
  2452. var part4 = cubed - squared;
  2453. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2454. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2455. return new Vector2(x, y);
  2456. };
  2457. /**
  2458. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2459. */
  2460. Vector2.Lerp = function (start, end, amount) {
  2461. var x = start.x + ((end.x - start.x) * amount);
  2462. var y = start.y + ((end.y - start.y) * amount);
  2463. return new Vector2(x, y);
  2464. };
  2465. /**
  2466. * Returns the dot product (float) of the vector "left" and the vector "right".
  2467. */
  2468. Vector2.Dot = function (left, right) {
  2469. return left.x * right.x + left.y * right.y;
  2470. };
  2471. /**
  2472. * Returns a new Vector2 equal to the normalized passed vector.
  2473. */
  2474. Vector2.Normalize = function (vector) {
  2475. var newVector = vector.clone();
  2476. newVector.normalize();
  2477. return newVector;
  2478. };
  2479. /**
  2480. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2481. */
  2482. Vector2.Minimize = function (left, right) {
  2483. var x = (left.x < right.x) ? left.x : right.x;
  2484. var y = (left.y < right.y) ? left.y : right.y;
  2485. return new Vector2(x, y);
  2486. };
  2487. /**
  2488. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2489. */
  2490. Vector2.Maximize = function (left, right) {
  2491. var x = (left.x > right.x) ? left.x : right.x;
  2492. var y = (left.y > right.y) ? left.y : right.y;
  2493. return new Vector2(x, y);
  2494. };
  2495. /**
  2496. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2497. */
  2498. Vector2.Transform = function (vector, transformation) {
  2499. var r = Vector2.Zero();
  2500. Vector2.TransformToRef(vector, transformation, r);
  2501. return r;
  2502. };
  2503. /**
  2504. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2505. */
  2506. Vector2.TransformToRef = function (vector, transformation, result) {
  2507. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2508. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2509. result.x = x;
  2510. result.y = y;
  2511. };
  2512. /**
  2513. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2514. */
  2515. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2516. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2517. var sign = a < 0 ? -1 : 1;
  2518. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2519. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2520. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2521. };
  2522. /**
  2523. * Returns the distance (float) between the vectors "value1" and "value2".
  2524. */
  2525. Vector2.Distance = function (value1, value2) {
  2526. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2527. };
  2528. /**
  2529. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2530. */
  2531. Vector2.DistanceSquared = function (value1, value2) {
  2532. var x = value1.x - value2.x;
  2533. var y = value1.y - value2.y;
  2534. return (x * x) + (y * y);
  2535. };
  2536. /**
  2537. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2538. */
  2539. Vector2.Center = function (value1, value2) {
  2540. var center = value1.add(value2);
  2541. center.scaleInPlace(0.5);
  2542. return center;
  2543. };
  2544. /**
  2545. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2546. */
  2547. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2548. var l2 = Vector2.DistanceSquared(segA, segB);
  2549. if (l2 === 0.0) {
  2550. return Vector2.Distance(p, segA);
  2551. }
  2552. var v = segB.subtract(segA);
  2553. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2554. var proj = segA.add(v.multiplyByFloats(t, t));
  2555. return Vector2.Distance(p, proj);
  2556. };
  2557. return Vector2;
  2558. }());
  2559. BABYLON.Vector2 = Vector2;
  2560. /**
  2561. * Classed used to store (x,y,z) vector representation
  2562. * A Vector3 is the main object used in 3D geometry
  2563. * It can represent etiher the coordinates of a point the space, either a direction
  2564. * Reminder: Babylon.js uses a left handed forward facing system
  2565. */
  2566. var Vector3 = /** @class */ (function () {
  2567. /**
  2568. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2569. * @param x defines the first coordinates (on X axis)
  2570. * @param y defines the second coordinates (on Y axis)
  2571. * @param z defines the third coordinates (on Z axis)
  2572. */
  2573. function Vector3(
  2574. /**
  2575. * Defines the first coordinates (on X axis)
  2576. */
  2577. x,
  2578. /**
  2579. * Defines the second coordinates (on Y axis)
  2580. */
  2581. y,
  2582. /**
  2583. * Defines the third coordinates (on Z axis)
  2584. */
  2585. z) {
  2586. this.x = x;
  2587. this.y = y;
  2588. this.z = z;
  2589. }
  2590. /**
  2591. * Creates a string representation of the Vector3
  2592. * @returns a string with the Vector3 coordinates.
  2593. */
  2594. Vector3.prototype.toString = function () {
  2595. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2596. };
  2597. /**
  2598. * Gets the class name
  2599. * @returns the string "Vector3"
  2600. */
  2601. Vector3.prototype.getClassName = function () {
  2602. return "Vector3";
  2603. };
  2604. /**
  2605. * Creates the Vector3 hash code
  2606. * @returns a number which tends to be unique between Vector3 instances
  2607. */
  2608. Vector3.prototype.getHashCode = function () {
  2609. var hash = this.x || 0;
  2610. hash = (hash * 397) ^ (this.y || 0);
  2611. hash = (hash * 397) ^ (this.z || 0);
  2612. return hash;
  2613. };
  2614. // Operators
  2615. /**
  2616. * Creates an array containing three elements : the coordinates of the Vector3
  2617. * @returns a new array of numbers
  2618. */
  2619. Vector3.prototype.asArray = function () {
  2620. var result = [];
  2621. this.toArray(result, 0);
  2622. return result;
  2623. };
  2624. /**
  2625. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2626. * @param array defines the destination array
  2627. * @param index defines the offset in the destination array
  2628. * @returns the current Vector3
  2629. */
  2630. Vector3.prototype.toArray = function (array, index) {
  2631. if (index === void 0) { index = 0; }
  2632. array[index] = this.x;
  2633. array[index + 1] = this.y;
  2634. array[index + 2] = this.z;
  2635. return this;
  2636. };
  2637. /**
  2638. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2639. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2640. */
  2641. Vector3.prototype.toQuaternion = function () {
  2642. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2643. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2644. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2645. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2646. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2647. var cosy = Math.cos(this.y * 0.5);
  2648. var siny = Math.sin(this.y * 0.5);
  2649. result.x = coszMinusx * siny;
  2650. result.y = -sinzMinusx * siny;
  2651. result.z = sinxPlusz * cosy;
  2652. result.w = cosxPlusz * cosy;
  2653. return result;
  2654. };
  2655. /**
  2656. * Adds the passed vector to the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the current updated Vector3
  2659. */
  2660. Vector3.prototype.addInPlace = function (otherVector) {
  2661. this.x += otherVector.x;
  2662. this.y += otherVector.y;
  2663. this.z += otherVector.z;
  2664. return this;
  2665. };
  2666. /**
  2667. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2668. * @param otherVector defines the second operand
  2669. * @returns the resulting Vector3
  2670. */
  2671. Vector3.prototype.add = function (otherVector) {
  2672. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2673. };
  2674. /**
  2675. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2676. * @param otherVector defines the second operand
  2677. * @param result defines the Vector3 object where to store the result
  2678. * @returns the current Vector3
  2679. */
  2680. Vector3.prototype.addToRef = function (otherVector, result) {
  2681. result.x = this.x + otherVector.x;
  2682. result.y = this.y + otherVector.y;
  2683. result.z = this.z + otherVector.z;
  2684. return this;
  2685. };
  2686. /**
  2687. * Subtract the passed vector from the current Vector3
  2688. * @param otherVector defines the second operand
  2689. * @returns the current updated Vector3
  2690. */
  2691. Vector3.prototype.subtractInPlace = function (otherVector) {
  2692. this.x -= otherVector.x;
  2693. this.y -= otherVector.y;
  2694. this.z -= otherVector.z;
  2695. return this;
  2696. };
  2697. /**
  2698. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2699. * @param otherVector defines the second operand
  2700. * @returns the resulting Vector3
  2701. */
  2702. Vector3.prototype.subtract = function (otherVector) {
  2703. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2704. };
  2705. /**
  2706. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2707. * @param otherVector defines the second operand
  2708. * @param result defines the Vector3 object where to store the result
  2709. * @returns the current Vector3
  2710. */
  2711. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2712. result.x = this.x - otherVector.x;
  2713. result.y = this.y - otherVector.y;
  2714. result.z = this.z - otherVector.z;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2719. * @param x defines the x coordinate of the operand
  2720. * @param y defines the y coordinate of the operand
  2721. * @param z defines the z coordinate of the operand
  2722. * @returns the resulting Vector3
  2723. */
  2724. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2725. return new Vector3(this.x - x, this.y - y, this.z - z);
  2726. };
  2727. /**
  2728. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2729. * @param x defines the x coordinate of the operand
  2730. * @param y defines the y coordinate of the operand
  2731. * @param z defines the z coordinate of the operand
  2732. * @param result defines the Vector3 object where to store the result
  2733. * @returns the current Vector3
  2734. */
  2735. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2736. result.x = this.x - x;
  2737. result.y = this.y - y;
  2738. result.z = this.z - z;
  2739. return this;
  2740. };
  2741. /**
  2742. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2743. * @returns a new Vector3
  2744. */
  2745. Vector3.prototype.negate = function () {
  2746. return new Vector3(-this.x, -this.y, -this.z);
  2747. };
  2748. /**
  2749. * Multiplies the Vector3 coordinates by the float "scale"
  2750. * @param scale defines the multiplier factor
  2751. * @returns the current updated Vector3
  2752. */
  2753. Vector3.prototype.scaleInPlace = function (scale) {
  2754. this.x *= scale;
  2755. this.y *= scale;
  2756. this.z *= scale;
  2757. return this;
  2758. };
  2759. /**
  2760. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2761. * @param scale defines the multiplier factor
  2762. * @returns a new Vector3
  2763. */
  2764. Vector3.prototype.scale = function (scale) {
  2765. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2766. };
  2767. /**
  2768. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2769. * @param scale defines the multiplier factor
  2770. * @param result defines the Vector3 object where to store the result
  2771. * @returns the current Vector3
  2772. */
  2773. Vector3.prototype.scaleToRef = function (scale, result) {
  2774. result.x = this.x * scale;
  2775. result.y = this.y * scale;
  2776. result.z = this.z * scale;
  2777. return this;
  2778. };
  2779. /**
  2780. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2781. * @param otherVector defines the second operand
  2782. * @returns true if both vectors are equals
  2783. */
  2784. Vector3.prototype.equals = function (otherVector) {
  2785. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2786. };
  2787. /**
  2788. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2789. * @param otherVector defines the second operand
  2790. * @param epsilon defines the minimal distance to define values as equals
  2791. * @returns true if both vectors are distant less than epsilon
  2792. */
  2793. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2794. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2795. 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);
  2796. };
  2797. /**
  2798. * Returns true if the current Vector3 coordinates equals the passed floats
  2799. * @param x defines the x coordinate of the operand
  2800. * @param y defines the y coordinate of the operand
  2801. * @param z defines the z coordinate of the operand
  2802. * @returns true if both vectors are equals
  2803. */
  2804. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2805. return this.x === x && this.y === y && this.z === z;
  2806. };
  2807. /**
  2808. * Multiplies the current Vector3 coordinates by the passed ones
  2809. * @param otherVector defines the second operand
  2810. * @returns the current updated Vector3
  2811. */
  2812. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2813. this.x *= otherVector.x;
  2814. this.y *= otherVector.y;
  2815. this.z *= otherVector.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2820. * @param otherVector defines the second operand
  2821. * @returns the new Vector3
  2822. */
  2823. Vector3.prototype.multiply = function (otherVector) {
  2824. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2825. };
  2826. /**
  2827. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2828. * @param otherVector defines the second operand
  2829. * @param result defines the Vector3 object where to store the result
  2830. * @returns the current Vector3
  2831. */
  2832. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2833. result.x = this.x * otherVector.x;
  2834. result.y = this.y * otherVector.y;
  2835. result.z = this.z * otherVector.z;
  2836. return this;
  2837. };
  2838. /**
  2839. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2840. * @param x defines the x coordinate of the operand
  2841. * @param y defines the y coordinate of the operand
  2842. * @param z defines the z coordinate of the operand
  2843. * @returns the new Vector3
  2844. */
  2845. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2846. return new Vector3(this.x * x, this.y * y, this.z * z);
  2847. };
  2848. /**
  2849. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2850. * @param otherVector defines the second operand
  2851. * @returns the new Vector3
  2852. */
  2853. Vector3.prototype.divide = function (otherVector) {
  2854. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2855. };
  2856. /**
  2857. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2858. * @param otherVector defines the second operand
  2859. * @param result defines the Vector3 object where to store the result
  2860. * @returns the current Vector3
  2861. */
  2862. Vector3.prototype.divideToRef = function (otherVector, result) {
  2863. result.x = this.x / otherVector.x;
  2864. result.y = this.y / otherVector.y;
  2865. result.z = this.z / otherVector.z;
  2866. return this;
  2867. };
  2868. /**
  2869. * Divides the current Vector3 coordinates by the passed ones.
  2870. * @param otherVector defines the second operand
  2871. * @returns the current updated Vector3
  2872. */
  2873. Vector3.prototype.divideInPlace = function (otherVector) {
  2874. return this.divideToRef(otherVector, this);
  2875. };
  2876. /**
  2877. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2878. * @param other defines the second operand
  2879. * @returns the current updated Vector3
  2880. */
  2881. Vector3.prototype.minimizeInPlace = function (other) {
  2882. if (other.x < this.x)
  2883. this.x = other.x;
  2884. if (other.y < this.y)
  2885. this.y = other.y;
  2886. if (other.z < this.z)
  2887. this.z = other.z;
  2888. return this;
  2889. };
  2890. /**
  2891. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2892. * @param other defines the second operand
  2893. * @returns the current updated Vector3
  2894. */
  2895. Vector3.prototype.maximizeInPlace = function (other) {
  2896. if (other.x > this.x)
  2897. this.x = other.x;
  2898. if (other.y > this.y)
  2899. this.y = other.y;
  2900. if (other.z > this.z)
  2901. this.z = other.z;
  2902. return this;
  2903. };
  2904. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2905. /**
  2906. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2907. */
  2908. get: function () {
  2909. var absX = Math.abs(this.x);
  2910. var absY = Math.abs(this.y);
  2911. if (absX !== absY) {
  2912. return true;
  2913. }
  2914. var absZ = Math.abs(this.z);
  2915. if (absX !== absZ) {
  2916. return true;
  2917. }
  2918. if (absY !== absZ) {
  2919. return true;
  2920. }
  2921. return false;
  2922. },
  2923. enumerable: true,
  2924. configurable: true
  2925. });
  2926. // Properties
  2927. /**
  2928. * Gets the length of the Vector3
  2929. * @returns the length of the Vecto3
  2930. */
  2931. Vector3.prototype.length = function () {
  2932. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2933. };
  2934. /**
  2935. * Gets the squared length of the Vector3
  2936. * @returns squared length of the Vector3
  2937. */
  2938. Vector3.prototype.lengthSquared = function () {
  2939. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2940. };
  2941. /**
  2942. * Normalize the current Vector3.
  2943. * Please note that this is an in place operation.
  2944. * @returns the current updated Vector3
  2945. */
  2946. Vector3.prototype.normalize = function () {
  2947. var len = this.length();
  2948. if (len === 0 || len === 1.0)
  2949. return this;
  2950. var num = 1.0 / len;
  2951. this.x *= num;
  2952. this.y *= num;
  2953. this.z *= num;
  2954. return this;
  2955. };
  2956. /**
  2957. * Normalize the current Vector3 to a new vector
  2958. * @returns the new Vector3
  2959. */
  2960. Vector3.prototype.normalizeToNew = function () {
  2961. var normalized = new Vector3(0, 0, 0);
  2962. this.normalizeToRef(normalized);
  2963. return normalized;
  2964. };
  2965. /**
  2966. * Normalize the current Vector3 to the reference
  2967. * @param reference define the Vector3 to update
  2968. * @returns the updated Vector3
  2969. */
  2970. Vector3.prototype.normalizeToRef = function (reference) {
  2971. var len = this.length();
  2972. if (len === 0 || len === 1.0) {
  2973. reference.set(this.x, this.y, this.z);
  2974. return reference;
  2975. }
  2976. var scale = 1.0 / len;
  2977. this.scaleToRef(scale, reference);
  2978. return reference;
  2979. };
  2980. /**
  2981. * Creates a new Vector3 copied from the current Vector3
  2982. * @returns the new Vector3
  2983. */
  2984. Vector3.prototype.clone = function () {
  2985. return new Vector3(this.x, this.y, this.z);
  2986. };
  2987. /**
  2988. * Copies the passed vector coordinates to the current Vector3 ones
  2989. * @param source defines the source Vector3
  2990. * @returns the current updated Vector3
  2991. */
  2992. Vector3.prototype.copyFrom = function (source) {
  2993. this.x = source.x;
  2994. this.y = source.y;
  2995. this.z = source.z;
  2996. return this;
  2997. };
  2998. /**
  2999. * Copies the passed floats to the current Vector3 coordinates
  3000. * @param x defines the x coordinate of the operand
  3001. * @param y defines the y coordinate of the operand
  3002. * @param z defines the z coordinate of the operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3006. this.x = x;
  3007. this.y = y;
  3008. this.z = z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Copies the passed floats to the current Vector3 coordinates
  3013. * @param x defines the x coordinate of the operand
  3014. * @param y defines the y coordinate of the operand
  3015. * @param z defines the z coordinate of the operand
  3016. * @returns the current updated Vector3
  3017. */
  3018. Vector3.prototype.set = function (x, y, z) {
  3019. return this.copyFromFloats(x, y, z);
  3020. };
  3021. // Statics
  3022. /**
  3023. * Get the clip factor between two vectors
  3024. * @param vector0 defines the first operand
  3025. * @param vector1 defines the second operand
  3026. * @param axis defines the axis to use
  3027. * @param size defines the size along the axis
  3028. * @returns the clip factor
  3029. */
  3030. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3031. var d0 = Vector3.Dot(vector0, axis) - size;
  3032. var d1 = Vector3.Dot(vector1, axis) - size;
  3033. var s = d0 / (d0 - d1);
  3034. return s;
  3035. };
  3036. /**
  3037. * Get angle between two vectors
  3038. * @param vector0 angle between vector0 and vector1
  3039. * @param vector1 angle between vector0 and vector1
  3040. * @param normal direction of the normal
  3041. * @return the angle between vector0 and vector1
  3042. */
  3043. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3044. var v0 = vector0.clone().normalize();
  3045. var v1 = vector1.clone().normalize();
  3046. var dot = Vector3.Dot(v0, v1);
  3047. var n = Vector3.Cross(v0, v1);
  3048. if (Vector3.Dot(n, normal) > 0) {
  3049. return Math.acos(dot);
  3050. }
  3051. return -Math.acos(dot);
  3052. };
  3053. /**
  3054. * Returns a new Vector3 set from the index "offset" of the passed array
  3055. * @param array defines the source array
  3056. * @param offset defines the offset in the source array
  3057. * @returns the new Vector3
  3058. */
  3059. Vector3.FromArray = function (array, offset) {
  3060. if (!offset) {
  3061. offset = 0;
  3062. }
  3063. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3064. };
  3065. /**
  3066. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3067. * This function is deprecated. Use FromArray instead
  3068. * @param array defines the source array
  3069. * @param offset defines the offset in the source array
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.FromFloatArray = function (array, offset) {
  3073. return Vector3.FromArray(array, offset);
  3074. };
  3075. /**
  3076. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3077. * @param array defines the source array
  3078. * @param offset defines the offset in the source array
  3079. * @param result defines the Vector3 where to store the result
  3080. */
  3081. Vector3.FromArrayToRef = function (array, offset, result) {
  3082. result.x = array[offset];
  3083. result.y = array[offset + 1];
  3084. result.z = array[offset + 2];
  3085. };
  3086. /**
  3087. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3088. * This function is deprecated. Use FromArrayToRef instead.
  3089. * @param array defines the source array
  3090. * @param offset defines the offset in the source array
  3091. * @param result defines the Vector3 where to store the result
  3092. */
  3093. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3094. return Vector3.FromArrayToRef(array, offset, result);
  3095. };
  3096. /**
  3097. * Sets the passed vector "result" with the passed floats.
  3098. * @param x defines the x coordinate of the source
  3099. * @param y defines the y coordinate of the source
  3100. * @param z defines the z coordinate of the source
  3101. * @param result defines the Vector3 where to store the result
  3102. */
  3103. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3104. result.x = x;
  3105. result.y = y;
  3106. result.z = z;
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3110. * @returns a new empty Vector3
  3111. */
  3112. Vector3.Zero = function () {
  3113. return new Vector3(0.0, 0.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3117. * @returns a new unit Vector3
  3118. */
  3119. Vector3.One = function () {
  3120. return new Vector3(1.0, 1.0, 1.0);
  3121. };
  3122. /**
  3123. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3124. * @returns a new up Vector3
  3125. */
  3126. Vector3.Up = function () {
  3127. return new Vector3(0.0, 1.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3131. * @returns a new forward Vector3
  3132. */
  3133. Vector3.Forward = function () {
  3134. return new Vector3(0.0, 0.0, 1.0);
  3135. };
  3136. /**
  3137. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3138. * @returns a new right Vector3
  3139. */
  3140. Vector3.Right = function () {
  3141. return new Vector3(1.0, 0.0, 0.0);
  3142. };
  3143. /**
  3144. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3145. * @returns a new left Vector3
  3146. */
  3147. Vector3.Left = function () {
  3148. return new Vector3(-1.0, 0.0, 0.0);
  3149. };
  3150. /**
  3151. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3152. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3153. * @param vector defines the Vector3 to transform
  3154. * @param transformation defines the transformation matrix
  3155. * @returns the transformed Vector3
  3156. */
  3157. Vector3.TransformCoordinates = function (vector, transformation) {
  3158. var result = Vector3.Zero();
  3159. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3160. return result;
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3164. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3165. * @param vector defines the Vector3 to transform
  3166. * @param transformation defines the transformation matrix
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3170. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3171. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3172. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3173. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3174. result.x = x / w;
  3175. result.y = y / w;
  3176. result.z = z / w;
  3177. };
  3178. /**
  3179. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3180. * This method computes tranformed coordinates only, not transformed direction vectors
  3181. * @param x define the x coordinate of the source vector
  3182. * @param y define the y coordinate of the source vector
  3183. * @param z define the z coordinate of the source vector
  3184. * @param transformation defines the transformation matrix
  3185. * @param result defines the Vector3 where to store the result
  3186. */
  3187. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3188. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3189. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3190. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3191. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3192. result.x = rx / rw;
  3193. result.y = ry / rw;
  3194. result.z = rz / rw;
  3195. };
  3196. /**
  3197. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3198. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3199. * @param vector defines the Vector3 to transform
  3200. * @param transformation defines the transformation matrix
  3201. * @returns the new Vector3
  3202. */
  3203. Vector3.TransformNormal = function (vector, transformation) {
  3204. var result = Vector3.Zero();
  3205. Vector3.TransformNormalToRef(vector, transformation, result);
  3206. return result;
  3207. };
  3208. /**
  3209. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3210. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3211. * @param vector defines the Vector3 to transform
  3212. * @param transformation defines the transformation matrix
  3213. * @param result defines the Vector3 where to store the result
  3214. */
  3215. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3216. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3217. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3218. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3219. result.x = x;
  3220. result.y = y;
  3221. result.z = z;
  3222. };
  3223. /**
  3224. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3225. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3226. * @param x define the x coordinate of the source vector
  3227. * @param y define the y coordinate of the source vector
  3228. * @param z define the z coordinate of the source vector
  3229. * @param transformation defines the transformation matrix
  3230. * @param result defines the Vector3 where to store the result
  3231. */
  3232. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3233. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3234. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3235. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3236. };
  3237. /**
  3238. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3239. * @param value1 defines the first control point
  3240. * @param value2 defines the second control point
  3241. * @param value3 defines the third control point
  3242. * @param value4 defines the fourth control point
  3243. * @param amount defines the amount on the spline to use
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3247. var squared = amount * amount;
  3248. var cubed = amount * squared;
  3249. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3250. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3251. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3252. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3253. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3254. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3255. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3256. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3257. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * 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"
  3262. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3263. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3264. * @param value defines the current value
  3265. * @param min defines the lower range value
  3266. * @param max defines the upper range value
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.Clamp = function (value, min, max) {
  3270. var x = value.x;
  3271. x = (x > max.x) ? max.x : x;
  3272. x = (x < min.x) ? min.x : x;
  3273. var y = value.y;
  3274. y = (y > max.y) ? max.y : y;
  3275. y = (y < min.y) ? min.y : y;
  3276. var z = value.z;
  3277. z = (z > max.z) ? max.z : z;
  3278. z = (z < min.z) ? min.z : z;
  3279. return new Vector3(x, y, z);
  3280. };
  3281. /**
  3282. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3283. * @param value1 defines the first control point
  3284. * @param tangent1 defines the first tangent vector
  3285. * @param value2 defines the second control point
  3286. * @param tangent2 defines the second tangent vector
  3287. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3288. * @returns the new Vector3
  3289. */
  3290. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3291. var squared = amount * amount;
  3292. var cubed = amount * squared;
  3293. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3294. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3295. var part3 = (cubed - (2.0 * squared)) + amount;
  3296. var part4 = cubed - squared;
  3297. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3298. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3299. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3300. return new Vector3(x, y, z);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3304. * @param start defines the start value
  3305. * @param end defines the end value
  3306. * @param amount max defines amount between both (between 0 and 1)
  3307. * @returns the new Vector3
  3308. */
  3309. Vector3.Lerp = function (start, end, amount) {
  3310. var result = new Vector3(0, 0, 0);
  3311. Vector3.LerpToRef(start, end, amount, result);
  3312. return result;
  3313. };
  3314. /**
  3315. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3316. * @param start defines the start value
  3317. * @param end defines the end value
  3318. * @param amount max defines amount between both (between 0 and 1)
  3319. * @param result defines the Vector3 where to store the result
  3320. */
  3321. Vector3.LerpToRef = function (start, end, amount, result) {
  3322. result.x = start.x + ((end.x - start.x) * amount);
  3323. result.y = start.y + ((end.y - start.y) * amount);
  3324. result.z = start.z + ((end.z - start.z) * amount);
  3325. };
  3326. /**
  3327. * Returns the dot product (float) between the vectors "left" and "right"
  3328. * @param left defines the left operand
  3329. * @param right defines the right operand
  3330. * @returns the dot product
  3331. */
  3332. Vector3.Dot = function (left, right) {
  3333. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3334. };
  3335. /**
  3336. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3337. * The cross product is then orthogonal to both "left" and "right"
  3338. * @param left defines the left operand
  3339. * @param right defines the right operand
  3340. * @returns the cross product
  3341. */
  3342. Vector3.Cross = function (left, right) {
  3343. var result = Vector3.Zero();
  3344. Vector3.CrossToRef(left, right, result);
  3345. return result;
  3346. };
  3347. /**
  3348. * Sets the passed vector "result" with the cross product of "left" and "right"
  3349. * The cross product is then orthogonal to both "left" and "right"
  3350. * @param left defines the left operand
  3351. * @param right defines the right operand
  3352. * @param result defines the Vector3 where to store the result
  3353. */
  3354. Vector3.CrossToRef = function (left, right, result) {
  3355. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3356. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3357. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3358. result.copyFrom(MathTmp.Vector3[0]);
  3359. };
  3360. /**
  3361. * Returns a new Vector3 as the normalization of the passed vector
  3362. * @param vector defines the Vector3 to normalize
  3363. * @returns the new Vector3
  3364. */
  3365. Vector3.Normalize = function (vector) {
  3366. var result = Vector3.Zero();
  3367. Vector3.NormalizeToRef(vector, result);
  3368. return result;
  3369. };
  3370. /**
  3371. * Sets the passed vector "result" with the normalization of the passed first vector
  3372. * @param vector defines the Vector3 to normalize
  3373. * @param result defines the Vector3 where to store the result
  3374. */
  3375. Vector3.NormalizeToRef = function (vector, result) {
  3376. result.copyFrom(vector);
  3377. result.normalize();
  3378. };
  3379. /**
  3380. * Project a Vector3 onto screen space
  3381. * @param vector defines the Vector3 to project
  3382. * @param world defines the world matrix to use
  3383. * @param transform defines the transform (view x projection) matrix to use
  3384. * @param viewport defines the screen viewport to use
  3385. * @returns the new Vector3
  3386. */
  3387. Vector3.Project = function (vector, world, transform, viewport) {
  3388. var cw = viewport.width;
  3389. var ch = viewport.height;
  3390. var cx = viewport.x;
  3391. var cy = viewport.y;
  3392. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3393. 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);
  3394. var matrix = MathTmp.Matrix[0];
  3395. world.multiplyToRef(transform, matrix);
  3396. matrix.multiplyToRef(viewportMatrix, matrix);
  3397. return Vector3.TransformCoordinates(vector, matrix);
  3398. };
  3399. /**
  3400. * Unproject from screen space to object space
  3401. * @param source defines the screen space Vector3 to use
  3402. * @param viewportWidth defines the current width of the viewport
  3403. * @param viewportHeight defines the current height of the viewport
  3404. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3405. * @param transform defines the transform (view x projection) matrix to use
  3406. * @returns the new Vector3
  3407. */
  3408. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3409. var matrix = MathTmp.Matrix[0];
  3410. world.multiplyToRef(transform, matrix);
  3411. matrix.invert();
  3412. source.x = source.x / viewportWidth * 2 - 1;
  3413. source.y = -(source.y / viewportHeight * 2 - 1);
  3414. var vector = Vector3.TransformCoordinates(source, matrix);
  3415. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3416. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3417. vector = vector.scale(1.0 / num);
  3418. }
  3419. return vector;
  3420. };
  3421. /**
  3422. * Unproject from screen space to object space
  3423. * @param source defines the screen space Vector3 to use
  3424. * @param viewportWidth defines the current width of the viewport
  3425. * @param viewportHeight defines the current height of the viewport
  3426. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3427. * @param view defines the view matrix to use
  3428. * @param projection defines the projection matrix to use
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3432. var result = Vector3.Zero();
  3433. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Unproject from screen space to object space
  3438. * @param source defines the screen space Vector3 to use
  3439. * @param viewportWidth defines the current width of the viewport
  3440. * @param viewportHeight defines the current height of the viewport
  3441. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3442. * @param view defines the view matrix to use
  3443. * @param projection defines the projection matrix to use
  3444. * @param result defines the Vector3 where to store the result
  3445. */
  3446. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3447. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3448. };
  3449. /**
  3450. * Unproject from screen space to object space
  3451. * @param sourceX defines the screen space x coordinate to use
  3452. * @param sourceY defines the screen space y coordinate to use
  3453. * @param sourceZ defines the screen space z coordinate to use
  3454. * @param viewportWidth defines the current width of the viewport
  3455. * @param viewportHeight defines the current height of the viewport
  3456. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3457. * @param view defines the view matrix to use
  3458. * @param projection defines the projection matrix to use
  3459. * @param result defines the Vector3 where to store the result
  3460. */
  3461. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3462. var matrix = MathTmp.Matrix[0];
  3463. world.multiplyToRef(view, matrix);
  3464. matrix.multiplyToRef(projection, matrix);
  3465. matrix.invert();
  3466. var screenSource = MathTmp.Vector3[0];
  3467. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3468. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3469. screenSource.z = 2 * sourceZ - 1.0;
  3470. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3471. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3472. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3473. result.scaleInPlace(1.0 / num);
  3474. }
  3475. };
  3476. /**
  3477. * Gets the minimal coordinate values between two Vector3
  3478. * @param left defines the first operand
  3479. * @param right defines the second operand
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Minimize = function (left, right) {
  3483. var min = left.clone();
  3484. min.minimizeInPlace(right);
  3485. return min;
  3486. };
  3487. /**
  3488. * Gets the maximal coordinate values between two Vector3
  3489. * @param left defines the first operand
  3490. * @param right defines the second operand
  3491. * @returns the new Vector3
  3492. */
  3493. Vector3.Maximize = function (left, right) {
  3494. var max = left.clone();
  3495. max.maximizeInPlace(right);
  3496. return max;
  3497. };
  3498. /**
  3499. * Returns the distance between the vectors "value1" and "value2"
  3500. * @param value1 defines the first operand
  3501. * @param value2 defines the second operand
  3502. * @returns the distance
  3503. */
  3504. Vector3.Distance = function (value1, value2) {
  3505. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3506. };
  3507. /**
  3508. * Returns the squared distance between the vectors "value1" and "value2"
  3509. * @param value1 defines the first operand
  3510. * @param value2 defines the second operand
  3511. * @returns the squared distance
  3512. */
  3513. Vector3.DistanceSquared = function (value1, value2) {
  3514. var x = value1.x - value2.x;
  3515. var y = value1.y - value2.y;
  3516. var z = value1.z - value2.z;
  3517. return (x * x) + (y * y) + (z * z);
  3518. };
  3519. /**
  3520. * Returns a new Vector3 located at the center between "value1" and "value2"
  3521. * @param value1 defines the first operand
  3522. * @param value2 defines the second operand
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.Center = function (value1, value2) {
  3526. var center = value1.add(value2);
  3527. center.scaleInPlace(0.5);
  3528. return center;
  3529. };
  3530. /**
  3531. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3532. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3533. * to something in order to rotate it from its local system to the given target system
  3534. * Note: axis1, axis2 and axis3 are normalized during this operation
  3535. * @param axis1 defines the first axis
  3536. * @param axis2 defines the second axis
  3537. * @param axis3 defines the third axis
  3538. * @returns a new Vector3
  3539. */
  3540. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3541. var rotation = Vector3.Zero();
  3542. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3543. return rotation;
  3544. };
  3545. /**
  3546. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3547. * @param axis1 defines the first axis
  3548. * @param axis2 defines the second axis
  3549. * @param axis3 defines the third axis
  3550. * @param ref defines the Vector3 where to store the result
  3551. */
  3552. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3553. var quat = MathTmp.Quaternion[0];
  3554. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3555. quat.toEulerAnglesToRef(ref);
  3556. };
  3557. return Vector3;
  3558. }());
  3559. BABYLON.Vector3 = Vector3;
  3560. //Vector4 class created for EulerAngle class conversion to Quaternion
  3561. var Vector4 = /** @class */ (function () {
  3562. /**
  3563. * Creates a Vector4 object from the passed floats.
  3564. */
  3565. function Vector4(x, y, z, w) {
  3566. this.x = x;
  3567. this.y = y;
  3568. this.z = z;
  3569. this.w = w;
  3570. }
  3571. /**
  3572. * Returns the string with the Vector4 coordinates.
  3573. */
  3574. Vector4.prototype.toString = function () {
  3575. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3576. };
  3577. /**
  3578. * Returns the string "Vector4".
  3579. */
  3580. Vector4.prototype.getClassName = function () {
  3581. return "Vector4";
  3582. };
  3583. /**
  3584. * Returns the Vector4 hash code.
  3585. */
  3586. Vector4.prototype.getHashCode = function () {
  3587. var hash = this.x || 0;
  3588. hash = (hash * 397) ^ (this.y || 0);
  3589. hash = (hash * 397) ^ (this.z || 0);
  3590. hash = (hash * 397) ^ (this.w || 0);
  3591. return hash;
  3592. };
  3593. // Operators
  3594. /**
  3595. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3596. */
  3597. Vector4.prototype.asArray = function () {
  3598. var result = new Array();
  3599. this.toArray(result, 0);
  3600. return result;
  3601. };
  3602. /**
  3603. * Populates the passed array from the passed index with the Vector4 coordinates.
  3604. * Returns the Vector4.
  3605. */
  3606. Vector4.prototype.toArray = function (array, index) {
  3607. if (index === undefined) {
  3608. index = 0;
  3609. }
  3610. array[index] = this.x;
  3611. array[index + 1] = this.y;
  3612. array[index + 2] = this.z;
  3613. array[index + 3] = this.w;
  3614. return this;
  3615. };
  3616. /**
  3617. * Adds the passed vector to the current Vector4.
  3618. * Returns the updated Vector4.
  3619. */
  3620. Vector4.prototype.addInPlace = function (otherVector) {
  3621. this.x += otherVector.x;
  3622. this.y += otherVector.y;
  3623. this.z += otherVector.z;
  3624. this.w += otherVector.w;
  3625. return this;
  3626. };
  3627. /**
  3628. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3629. */
  3630. Vector4.prototype.add = function (otherVector) {
  3631. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3632. };
  3633. /**
  3634. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3635. * Returns the current Vector4.
  3636. */
  3637. Vector4.prototype.addToRef = function (otherVector, result) {
  3638. result.x = this.x + otherVector.x;
  3639. result.y = this.y + otherVector.y;
  3640. result.z = this.z + otherVector.z;
  3641. result.w = this.w + otherVector.w;
  3642. return this;
  3643. };
  3644. /**
  3645. * Subtract in place the passed vector from the current Vector4.
  3646. * Returns the updated Vector4.
  3647. */
  3648. Vector4.prototype.subtractInPlace = function (otherVector) {
  3649. this.x -= otherVector.x;
  3650. this.y -= otherVector.y;
  3651. this.z -= otherVector.z;
  3652. this.w -= otherVector.w;
  3653. return this;
  3654. };
  3655. /**
  3656. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3657. */
  3658. Vector4.prototype.subtract = function (otherVector) {
  3659. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3660. };
  3661. /**
  3662. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3663. * Returns the current Vector4.
  3664. */
  3665. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3666. result.x = this.x - otherVector.x;
  3667. result.y = this.y - otherVector.y;
  3668. result.z = this.z - otherVector.z;
  3669. result.w = this.w - otherVector.w;
  3670. return this;
  3671. };
  3672. /**
  3673. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3674. */
  3675. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3676. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3677. };
  3678. /**
  3679. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3680. * Returns the current Vector4.
  3681. */
  3682. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3683. result.x = this.x - x;
  3684. result.y = this.y - y;
  3685. result.z = this.z - z;
  3686. result.w = this.w - w;
  3687. return this;
  3688. };
  3689. /**
  3690. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3691. */
  3692. Vector4.prototype.negate = function () {
  3693. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3694. };
  3695. /**
  3696. * Multiplies the current Vector4 coordinates by scale (float).
  3697. * Returns the updated Vector4.
  3698. */
  3699. Vector4.prototype.scaleInPlace = function (scale) {
  3700. this.x *= scale;
  3701. this.y *= scale;
  3702. this.z *= scale;
  3703. this.w *= scale;
  3704. return this;
  3705. };
  3706. /**
  3707. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3708. */
  3709. Vector4.prototype.scale = function (scale) {
  3710. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3711. };
  3712. /**
  3713. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3714. * Returns the current Vector4.
  3715. */
  3716. Vector4.prototype.scaleToRef = function (scale, result) {
  3717. result.x = this.x * scale;
  3718. result.y = this.y * scale;
  3719. result.z = this.z * scale;
  3720. result.w = this.w * scale;
  3721. return this;
  3722. };
  3723. /**
  3724. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3725. */
  3726. Vector4.prototype.equals = function (otherVector) {
  3727. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3728. };
  3729. /**
  3730. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3731. */
  3732. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3733. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3734. return otherVector
  3735. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3736. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3737. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3738. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3739. };
  3740. /**
  3741. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3742. */
  3743. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3744. return this.x === x && this.y === y && this.z === z && this.w === w;
  3745. };
  3746. /**
  3747. * Multiplies in place the current Vector4 by the passed one.
  3748. * Returns the updated Vector4.
  3749. */
  3750. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3751. this.x *= otherVector.x;
  3752. this.y *= otherVector.y;
  3753. this.z *= otherVector.z;
  3754. this.w *= otherVector.w;
  3755. return this;
  3756. };
  3757. /**
  3758. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3759. */
  3760. Vector4.prototype.multiply = function (otherVector) {
  3761. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3762. };
  3763. /**
  3764. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3765. * Returns the current Vector4.
  3766. */
  3767. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3768. result.x = this.x * otherVector.x;
  3769. result.y = this.y * otherVector.y;
  3770. result.z = this.z * otherVector.z;
  3771. result.w = this.w * otherVector.w;
  3772. return this;
  3773. };
  3774. /**
  3775. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3776. */
  3777. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3778. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3779. };
  3780. /**
  3781. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3782. */
  3783. Vector4.prototype.divide = function (otherVector) {
  3784. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3785. };
  3786. /**
  3787. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3788. * Returns the current Vector4.
  3789. */
  3790. Vector4.prototype.divideToRef = function (otherVector, result) {
  3791. result.x = this.x / otherVector.x;
  3792. result.y = this.y / otherVector.y;
  3793. result.z = this.z / otherVector.z;
  3794. result.w = this.w / otherVector.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Divides the current Vector3 coordinates by the passed ones.
  3799. * @returns the updated Vector3.
  3800. */
  3801. Vector4.prototype.divideInPlace = function (otherVector) {
  3802. return this.divideToRef(otherVector, this);
  3803. };
  3804. /**
  3805. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3806. * @param other defines the second operand
  3807. * @returns the current updated Vector4
  3808. */
  3809. Vector4.prototype.minimizeInPlace = function (other) {
  3810. if (other.x < this.x)
  3811. this.x = other.x;
  3812. if (other.y < this.y)
  3813. this.y = other.y;
  3814. if (other.z < this.z)
  3815. this.z = other.z;
  3816. if (other.w < this.w)
  3817. this.w = other.w;
  3818. return this;
  3819. };
  3820. /**
  3821. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3822. * @param other defines the second operand
  3823. * @returns the current updated Vector4
  3824. */
  3825. Vector4.prototype.maximizeInPlace = function (other) {
  3826. if (other.x > this.x)
  3827. this.x = other.x;
  3828. if (other.y > this.y)
  3829. this.y = other.y;
  3830. if (other.z > this.z)
  3831. this.z = other.z;
  3832. if (other.w > this.w)
  3833. this.w = other.w;
  3834. return this;
  3835. };
  3836. // Properties
  3837. /**
  3838. * Returns the Vector4 length (float).
  3839. */
  3840. Vector4.prototype.length = function () {
  3841. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3842. };
  3843. /**
  3844. * Returns the Vector4 squared length (float).
  3845. */
  3846. Vector4.prototype.lengthSquared = function () {
  3847. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3848. };
  3849. // Methods
  3850. /**
  3851. * Normalizes in place the Vector4.
  3852. * Returns the updated Vector4.
  3853. */
  3854. Vector4.prototype.normalize = function () {
  3855. var len = this.length();
  3856. if (len === 0)
  3857. return this;
  3858. var num = 1.0 / len;
  3859. this.x *= num;
  3860. this.y *= num;
  3861. this.z *= num;
  3862. this.w *= num;
  3863. return this;
  3864. };
  3865. /**
  3866. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3867. */
  3868. Vector4.prototype.toVector3 = function () {
  3869. return new Vector3(this.x, this.y, this.z);
  3870. };
  3871. /**
  3872. * Returns a new Vector4 copied from the current one.
  3873. */
  3874. Vector4.prototype.clone = function () {
  3875. return new Vector4(this.x, this.y, this.z, this.w);
  3876. };
  3877. /**
  3878. * Updates the current Vector4 with the passed one coordinates.
  3879. * Returns the updated Vector4.
  3880. */
  3881. Vector4.prototype.copyFrom = function (source) {
  3882. this.x = source.x;
  3883. this.y = source.y;
  3884. this.z = source.z;
  3885. this.w = source.w;
  3886. return this;
  3887. };
  3888. /**
  3889. * Updates the current Vector4 coordinates with the passed floats.
  3890. * Returns the updated Vector4.
  3891. */
  3892. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3893. this.x = x;
  3894. this.y = y;
  3895. this.z = z;
  3896. this.w = w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the current Vector4 coordinates with the passed floats.
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.set = function (x, y, z, w) {
  3904. return this.copyFromFloats(x, y, z, w);
  3905. };
  3906. // Statics
  3907. /**
  3908. * Returns a new Vector4 set from the starting index of the passed array.
  3909. */
  3910. Vector4.FromArray = function (array, offset) {
  3911. if (!offset) {
  3912. offset = 0;
  3913. }
  3914. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3915. };
  3916. /**
  3917. * Updates the passed vector "result" from the starting index of the passed array.
  3918. */
  3919. Vector4.FromArrayToRef = function (array, offset, result) {
  3920. result.x = array[offset];
  3921. result.y = array[offset + 1];
  3922. result.z = array[offset + 2];
  3923. result.w = array[offset + 3];
  3924. };
  3925. /**
  3926. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3927. */
  3928. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3929. Vector4.FromArrayToRef(array, offset, result);
  3930. };
  3931. /**
  3932. * Updates the passed vector "result" coordinates from the passed floats.
  3933. */
  3934. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3935. result.x = x;
  3936. result.y = y;
  3937. result.z = z;
  3938. result.w = w;
  3939. };
  3940. /**
  3941. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3942. */
  3943. Vector4.Zero = function () {
  3944. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3945. };
  3946. /**
  3947. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3948. */
  3949. Vector4.One = function () {
  3950. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3951. };
  3952. /**
  3953. * Returns a new normalized Vector4 from the passed one.
  3954. */
  3955. Vector4.Normalize = function (vector) {
  3956. var result = Vector4.Zero();
  3957. Vector4.NormalizeToRef(vector, result);
  3958. return result;
  3959. };
  3960. /**
  3961. * Updates the passed vector "result" from the normalization of the passed one.
  3962. */
  3963. Vector4.NormalizeToRef = function (vector, result) {
  3964. result.copyFrom(vector);
  3965. result.normalize();
  3966. };
  3967. Vector4.Minimize = function (left, right) {
  3968. var min = left.clone();
  3969. min.minimizeInPlace(right);
  3970. return min;
  3971. };
  3972. Vector4.Maximize = function (left, right) {
  3973. var max = left.clone();
  3974. max.maximizeInPlace(right);
  3975. return max;
  3976. };
  3977. /**
  3978. * Returns the distance (float) between the vectors "value1" and "value2".
  3979. */
  3980. Vector4.Distance = function (value1, value2) {
  3981. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3982. };
  3983. /**
  3984. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3985. */
  3986. Vector4.DistanceSquared = function (value1, value2) {
  3987. var x = value1.x - value2.x;
  3988. var y = value1.y - value2.y;
  3989. var z = value1.z - value2.z;
  3990. var w = value1.w - value2.w;
  3991. return (x * x) + (y * y) + (z * z) + (w * w);
  3992. };
  3993. /**
  3994. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3995. */
  3996. Vector4.Center = function (value1, value2) {
  3997. var center = value1.add(value2);
  3998. center.scaleInPlace(0.5);
  3999. return center;
  4000. };
  4001. /**
  4002. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4003. * This methods computes transformed normalized direction vectors only.
  4004. */
  4005. Vector4.TransformNormal = function (vector, transformation) {
  4006. var result = Vector4.Zero();
  4007. Vector4.TransformNormalToRef(vector, transformation, result);
  4008. return result;
  4009. };
  4010. /**
  4011. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4012. * This methods computes transformed normalized direction vectors only.
  4013. */
  4014. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4015. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4016. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4017. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4018. result.x = x;
  4019. result.y = y;
  4020. result.z = z;
  4021. result.w = vector.w;
  4022. };
  4023. /**
  4024. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4025. * This methods computes transformed normalized direction vectors only.
  4026. */
  4027. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4028. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4029. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4030. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4031. result.w = w;
  4032. };
  4033. return Vector4;
  4034. }());
  4035. BABYLON.Vector4 = Vector4;
  4036. var Size = /** @class */ (function () {
  4037. /**
  4038. * Creates a Size object from the passed width and height (floats).
  4039. */
  4040. function Size(width, height) {
  4041. this.width = width;
  4042. this.height = height;
  4043. }
  4044. // Returns a string with the Size width and height.
  4045. Size.prototype.toString = function () {
  4046. return "{W: " + this.width + ", H: " + this.height + "}";
  4047. };
  4048. /**
  4049. * Returns the string "Size"
  4050. */
  4051. Size.prototype.getClassName = function () {
  4052. return "Size";
  4053. };
  4054. /**
  4055. * Returns the Size hash code.
  4056. */
  4057. Size.prototype.getHashCode = function () {
  4058. var hash = this.width || 0;
  4059. hash = (hash * 397) ^ (this.height || 0);
  4060. return hash;
  4061. };
  4062. /**
  4063. * Updates the current size from the passed one.
  4064. * Returns the updated Size.
  4065. */
  4066. Size.prototype.copyFrom = function (src) {
  4067. this.width = src.width;
  4068. this.height = src.height;
  4069. };
  4070. /**
  4071. * Updates in place the current Size from the passed floats.
  4072. * Returns the updated Size.
  4073. */
  4074. Size.prototype.copyFromFloats = function (width, height) {
  4075. this.width = width;
  4076. this.height = height;
  4077. return this;
  4078. };
  4079. /**
  4080. * Updates in place the current Size from the passed floats.
  4081. * Returns the updated Size.
  4082. */
  4083. Size.prototype.set = function (width, height) {
  4084. return this.copyFromFloats(width, height);
  4085. };
  4086. /**
  4087. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4088. */
  4089. Size.prototype.multiplyByFloats = function (w, h) {
  4090. return new Size(this.width * w, this.height * h);
  4091. };
  4092. /**
  4093. * Returns a new Size copied from the passed one.
  4094. */
  4095. Size.prototype.clone = function () {
  4096. return new Size(this.width, this.height);
  4097. };
  4098. /**
  4099. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4100. */
  4101. Size.prototype.equals = function (other) {
  4102. if (!other) {
  4103. return false;
  4104. }
  4105. return (this.width === other.width) && (this.height === other.height);
  4106. };
  4107. Object.defineProperty(Size.prototype, "surface", {
  4108. /**
  4109. * Returns the surface of the Size : width * height (float).
  4110. */
  4111. get: function () {
  4112. return this.width * this.height;
  4113. },
  4114. enumerable: true,
  4115. configurable: true
  4116. });
  4117. /**
  4118. * Returns a new Size set to (0.0, 0.0)
  4119. */
  4120. Size.Zero = function () {
  4121. return new Size(0.0, 0.0);
  4122. };
  4123. /**
  4124. * Returns a new Size set as the addition result of the current Size and the passed one.
  4125. */
  4126. Size.prototype.add = function (otherSize) {
  4127. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4128. return r;
  4129. };
  4130. /**
  4131. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4132. */
  4133. Size.prototype.subtract = function (otherSize) {
  4134. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4135. return r;
  4136. };
  4137. /**
  4138. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4139. */
  4140. Size.Lerp = function (start, end, amount) {
  4141. var w = start.width + ((end.width - start.width) * amount);
  4142. var h = start.height + ((end.height - start.height) * amount);
  4143. return new Size(w, h);
  4144. };
  4145. return Size;
  4146. }());
  4147. BABYLON.Size = Size;
  4148. var Quaternion = /** @class */ (function () {
  4149. /**
  4150. * Creates a new Quaternion from the passed floats.
  4151. */
  4152. function Quaternion(x, y, z, w) {
  4153. if (x === void 0) { x = 0.0; }
  4154. if (y === void 0) { y = 0.0; }
  4155. if (z === void 0) { z = 0.0; }
  4156. if (w === void 0) { w = 1.0; }
  4157. this.x = x;
  4158. this.y = y;
  4159. this.z = z;
  4160. this.w = w;
  4161. }
  4162. /**
  4163. * Returns a string with the Quaternion coordinates.
  4164. */
  4165. Quaternion.prototype.toString = function () {
  4166. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4167. };
  4168. /**
  4169. * Returns the string "Quaternion".
  4170. */
  4171. Quaternion.prototype.getClassName = function () {
  4172. return "Quaternion";
  4173. };
  4174. /**
  4175. * Returns the Quaternion hash code.
  4176. */
  4177. Quaternion.prototype.getHashCode = function () {
  4178. var hash = this.x || 0;
  4179. hash = (hash * 397) ^ (this.y || 0);
  4180. hash = (hash * 397) ^ (this.z || 0);
  4181. hash = (hash * 397) ^ (this.w || 0);
  4182. return hash;
  4183. };
  4184. /**
  4185. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4186. */
  4187. Quaternion.prototype.asArray = function () {
  4188. return [this.x, this.y, this.z, this.w];
  4189. };
  4190. /**
  4191. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4192. */
  4193. Quaternion.prototype.equals = function (otherQuaternion) {
  4194. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4195. };
  4196. /**
  4197. * Returns a new Quaternion copied from the current one.
  4198. */
  4199. Quaternion.prototype.clone = function () {
  4200. return new Quaternion(this.x, this.y, this.z, this.w);
  4201. };
  4202. /**
  4203. * Updates the current Quaternion from the passed one coordinates.
  4204. * Returns the updated Quaterion.
  4205. */
  4206. Quaternion.prototype.copyFrom = function (other) {
  4207. this.x = other.x;
  4208. this.y = other.y;
  4209. this.z = other.z;
  4210. this.w = other.w;
  4211. return this;
  4212. };
  4213. /**
  4214. * Updates the current Quaternion from the passed float coordinates.
  4215. * Returns the updated Quaterion.
  4216. */
  4217. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4218. this.x = x;
  4219. this.y = y;
  4220. this.z = z;
  4221. this.w = w;
  4222. return this;
  4223. };
  4224. /**
  4225. * Updates the current Quaternion from the passed float coordinates.
  4226. * Returns the updated Quaterion.
  4227. */
  4228. Quaternion.prototype.set = function (x, y, z, w) {
  4229. return this.copyFromFloats(x, y, z, w);
  4230. };
  4231. /**
  4232. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4233. */
  4234. Quaternion.prototype.add = function (other) {
  4235. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4236. };
  4237. /**
  4238. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4239. */
  4240. Quaternion.prototype.subtract = function (other) {
  4241. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4242. };
  4243. /**
  4244. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4245. */
  4246. Quaternion.prototype.scale = function (value) {
  4247. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4248. };
  4249. /**
  4250. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4251. */
  4252. Quaternion.prototype.multiply = function (q1) {
  4253. var result = new Quaternion(0, 0, 0, 1.0);
  4254. this.multiplyToRef(q1, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4259. * Returns the current Quaternion.
  4260. */
  4261. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4262. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4263. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4264. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4265. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4266. result.copyFromFloats(x, y, z, w);
  4267. return this;
  4268. };
  4269. /**
  4270. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4271. * Returns the updated Quaternion.
  4272. */
  4273. Quaternion.prototype.multiplyInPlace = function (q1) {
  4274. this.multiplyToRef(q1, this);
  4275. return this;
  4276. };
  4277. /**
  4278. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4279. * Returns the current Quaternion.
  4280. */
  4281. Quaternion.prototype.conjugateToRef = function (ref) {
  4282. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4283. return this;
  4284. };
  4285. /**
  4286. * Conjugates in place the current Quaternion.
  4287. * Returns the updated Quaternion.
  4288. */
  4289. Quaternion.prototype.conjugateInPlace = function () {
  4290. this.x *= -1;
  4291. this.y *= -1;
  4292. this.z *= -1;
  4293. return this;
  4294. };
  4295. /**
  4296. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4297. */
  4298. Quaternion.prototype.conjugate = function () {
  4299. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4300. return result;
  4301. };
  4302. /**
  4303. * Returns the Quaternion length (float).
  4304. */
  4305. Quaternion.prototype.length = function () {
  4306. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4307. };
  4308. /**
  4309. * Normalize in place the current Quaternion.
  4310. * Returns the updated Quaternion.
  4311. */
  4312. Quaternion.prototype.normalize = function () {
  4313. var length = 1.0 / this.length();
  4314. this.x *= length;
  4315. this.y *= length;
  4316. this.z *= length;
  4317. this.w *= length;
  4318. return this;
  4319. };
  4320. /**
  4321. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4322. */
  4323. Quaternion.prototype.toEulerAngles = function (order) {
  4324. if (order === void 0) { order = "YZX"; }
  4325. var result = Vector3.Zero();
  4326. this.toEulerAnglesToRef(result, order);
  4327. return result;
  4328. };
  4329. /**
  4330. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4331. * Returns the current Quaternion.
  4332. */
  4333. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4334. if (order === void 0) { order = "YZX"; }
  4335. var qz = this.z;
  4336. var qx = this.x;
  4337. var qy = this.y;
  4338. var qw = this.w;
  4339. var sqw = qw * qw;
  4340. var sqz = qz * qz;
  4341. var sqx = qx * qx;
  4342. var sqy = qy * qy;
  4343. var zAxisY = qy * qz - qx * qw;
  4344. var limit = .4999999;
  4345. if (zAxisY < -limit) {
  4346. result.y = 2 * Math.atan2(qy, qw);
  4347. result.x = Math.PI / 2;
  4348. result.z = 0;
  4349. }
  4350. else if (zAxisY > limit) {
  4351. result.y = 2 * Math.atan2(qy, qw);
  4352. result.x = -Math.PI / 2;
  4353. result.z = 0;
  4354. }
  4355. else {
  4356. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4357. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4358. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4359. }
  4360. return this;
  4361. };
  4362. /**
  4363. * Updates the passed rotation matrix with the current Quaternion values.
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.toRotationMatrix = function (result) {
  4367. var xx = this.x * this.x;
  4368. var yy = this.y * this.y;
  4369. var zz = this.z * this.z;
  4370. var xy = this.x * this.y;
  4371. var zw = this.z * this.w;
  4372. var zx = this.z * this.x;
  4373. var yw = this.y * this.w;
  4374. var yz = this.y * this.z;
  4375. var xw = this.x * this.w;
  4376. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4377. result.m[1] = 2.0 * (xy + zw);
  4378. result.m[2] = 2.0 * (zx - yw);
  4379. result.m[3] = 0;
  4380. result.m[4] = 2.0 * (xy - zw);
  4381. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4382. result.m[6] = 2.0 * (yz + xw);
  4383. result.m[7] = 0;
  4384. result.m[8] = 2.0 * (zx + yw);
  4385. result.m[9] = 2.0 * (yz - xw);
  4386. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4387. result.m[11] = 0;
  4388. result.m[12] = 0;
  4389. result.m[13] = 0;
  4390. result.m[14] = 0;
  4391. result.m[15] = 1.0;
  4392. result._markAsUpdated();
  4393. return this;
  4394. };
  4395. /**
  4396. * Updates the current Quaternion from the passed rotation matrix values.
  4397. * Returns the updated Quaternion.
  4398. */
  4399. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4400. Quaternion.FromRotationMatrixToRef(matrix, this);
  4401. return this;
  4402. };
  4403. // Statics
  4404. /**
  4405. * Returns a new Quaternion set from the passed rotation matrix values.
  4406. */
  4407. Quaternion.FromRotationMatrix = function (matrix) {
  4408. var result = new Quaternion();
  4409. Quaternion.FromRotationMatrixToRef(matrix, result);
  4410. return result;
  4411. };
  4412. /**
  4413. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4414. */
  4415. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4416. var data = matrix.m;
  4417. var m11 = data[0], m12 = data[4], m13 = data[8];
  4418. var m21 = data[1], m22 = data[5], m23 = data[9];
  4419. var m31 = data[2], m32 = data[6], m33 = data[10];
  4420. var trace = m11 + m22 + m33;
  4421. var s;
  4422. if (trace > 0) {
  4423. s = 0.5 / Math.sqrt(trace + 1.0);
  4424. result.w = 0.25 / s;
  4425. result.x = (m32 - m23) * s;
  4426. result.y = (m13 - m31) * s;
  4427. result.z = (m21 - m12) * s;
  4428. }
  4429. else if (m11 > m22 && m11 > m33) {
  4430. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4431. result.w = (m32 - m23) / s;
  4432. result.x = 0.25 * s;
  4433. result.y = (m12 + m21) / s;
  4434. result.z = (m13 + m31) / s;
  4435. }
  4436. else if (m22 > m33) {
  4437. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4438. result.w = (m13 - m31) / s;
  4439. result.x = (m12 + m21) / s;
  4440. result.y = 0.25 * s;
  4441. result.z = (m23 + m32) / s;
  4442. }
  4443. else {
  4444. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4445. result.w = (m21 - m12) / s;
  4446. result.x = (m13 + m31) / s;
  4447. result.y = (m23 + m32) / s;
  4448. result.z = 0.25 * s;
  4449. }
  4450. };
  4451. /**
  4452. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4453. */
  4454. Quaternion.Zero = function () {
  4455. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion as the inverted current Quaternion.
  4459. */
  4460. Quaternion.Inverse = function (q) {
  4461. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4462. };
  4463. /**
  4464. * Returns the identity Quaternion.
  4465. */
  4466. Quaternion.Identity = function () {
  4467. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4468. };
  4469. Quaternion.IsIdentity = function (quaternion) {
  4470. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4471. };
  4472. /**
  4473. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4474. */
  4475. Quaternion.RotationAxis = function (axis, angle) {
  4476. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4477. };
  4478. /**
  4479. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4480. */
  4481. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4482. var sin = Math.sin(angle / 2);
  4483. axis.normalize();
  4484. result.w = Math.cos(angle / 2);
  4485. result.x = axis.x * sin;
  4486. result.y = axis.y * sin;
  4487. result.z = axis.z * sin;
  4488. return result;
  4489. };
  4490. /**
  4491. * Retuns a new Quaternion set from the starting index of the passed array.
  4492. */
  4493. Quaternion.FromArray = function (array, offset) {
  4494. if (!offset) {
  4495. offset = 0;
  4496. }
  4497. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4498. };
  4499. /**
  4500. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4501. */
  4502. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4503. var q = new Quaternion();
  4504. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4505. return q;
  4506. };
  4507. /**
  4508. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4509. */
  4510. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4511. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4512. var halfRoll = roll * 0.5;
  4513. var halfPitch = pitch * 0.5;
  4514. var halfYaw = yaw * 0.5;
  4515. var sinRoll = Math.sin(halfRoll);
  4516. var cosRoll = Math.cos(halfRoll);
  4517. var sinPitch = Math.sin(halfPitch);
  4518. var cosPitch = Math.cos(halfPitch);
  4519. var sinYaw = Math.sin(halfYaw);
  4520. var cosYaw = Math.cos(halfYaw);
  4521. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4522. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4523. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4524. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4525. };
  4526. /**
  4527. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4528. */
  4529. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4530. var result = new Quaternion();
  4531. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4532. return result;
  4533. };
  4534. /**
  4535. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4536. */
  4537. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4538. // Produces a quaternion from Euler angles in the z-x-z orientation
  4539. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4540. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4541. var halfBeta = beta * 0.5;
  4542. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4543. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4544. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4545. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4546. };
  4547. /**
  4548. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4549. * cf to Vector3.RotationFromAxis() documentation.
  4550. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4551. */
  4552. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4553. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4554. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4555. return quat;
  4556. };
  4557. /**
  4558. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4559. * cf to Vector3.RotationFromAxis() documentation.
  4560. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4561. */
  4562. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4563. var rotMat = MathTmp.Matrix[0];
  4564. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4565. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4566. };
  4567. Quaternion.Slerp = function (left, right, amount) {
  4568. var result = Quaternion.Identity();
  4569. Quaternion.SlerpToRef(left, right, amount, result);
  4570. return result;
  4571. };
  4572. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4573. var num2;
  4574. var num3;
  4575. var num = amount;
  4576. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4577. var flag = false;
  4578. if (num4 < 0) {
  4579. flag = true;
  4580. num4 = -num4;
  4581. }
  4582. if (num4 > 0.999999) {
  4583. num3 = 1 - num;
  4584. num2 = flag ? -num : num;
  4585. }
  4586. else {
  4587. var num5 = Math.acos(num4);
  4588. var num6 = (1.0 / Math.sin(num5));
  4589. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4590. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4591. }
  4592. result.x = (num3 * left.x) + (num2 * right.x);
  4593. result.y = (num3 * left.y) + (num2 * right.y);
  4594. result.z = (num3 * left.z) + (num2 * right.z);
  4595. result.w = (num3 * left.w) + (num2 * right.w);
  4596. };
  4597. /**
  4598. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4599. */
  4600. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4601. var squared = amount * amount;
  4602. var cubed = amount * squared;
  4603. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4604. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4605. var part3 = (cubed - (2.0 * squared)) + amount;
  4606. var part4 = cubed - squared;
  4607. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4608. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4609. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4610. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4611. return new Quaternion(x, y, z, w);
  4612. };
  4613. return Quaternion;
  4614. }());
  4615. BABYLON.Quaternion = Quaternion;
  4616. var Matrix = /** @class */ (function () {
  4617. function Matrix() {
  4618. this._isIdentity = false;
  4619. this._isIdentityDirty = true;
  4620. this.m = new Float32Array(16);
  4621. this._markAsUpdated();
  4622. }
  4623. Matrix.prototype._markAsUpdated = function () {
  4624. this.updateFlag = Matrix._updateFlagSeed++;
  4625. this._isIdentityDirty = true;
  4626. };
  4627. // Properties
  4628. /**
  4629. * Boolean : True is the matrix is the identity matrix
  4630. */
  4631. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4632. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4633. if (this._isIdentityDirty) {
  4634. this._isIdentityDirty = false;
  4635. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4636. this._isIdentity = false;
  4637. }
  4638. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4639. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4640. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4641. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4642. this._isIdentity = false;
  4643. }
  4644. else {
  4645. this._isIdentity = true;
  4646. }
  4647. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4648. this._isIdentity = false;
  4649. }
  4650. }
  4651. return this._isIdentity;
  4652. };
  4653. /**
  4654. * Returns the matrix determinant (float).
  4655. */
  4656. Matrix.prototype.determinant = function () {
  4657. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4658. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4659. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4660. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4661. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4662. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4663. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4664. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4665. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4666. };
  4667. // Methods
  4668. /**
  4669. * Returns the matrix underlying array.
  4670. */
  4671. Matrix.prototype.toArray = function () {
  4672. return this.m;
  4673. };
  4674. /**
  4675. * Returns the matrix underlying array.
  4676. */
  4677. Matrix.prototype.asArray = function () {
  4678. return this.toArray();
  4679. };
  4680. /**
  4681. * Inverts in place the Matrix.
  4682. * Returns the Matrix inverted.
  4683. */
  4684. Matrix.prototype.invert = function () {
  4685. this.invertToRef(this);
  4686. return this;
  4687. };
  4688. /**
  4689. * Sets all the matrix elements to zero.
  4690. * Returns the Matrix.
  4691. */
  4692. Matrix.prototype.reset = function () {
  4693. for (var index = 0; index < 16; index++) {
  4694. this.m[index] = 0.0;
  4695. }
  4696. this._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4701. */
  4702. Matrix.prototype.add = function (other) {
  4703. var result = new Matrix();
  4704. this.addToRef(other, result);
  4705. return result;
  4706. };
  4707. /**
  4708. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4709. * Returns the Matrix.
  4710. */
  4711. Matrix.prototype.addToRef = function (other, result) {
  4712. for (var index = 0; index < 16; index++) {
  4713. result.m[index] = this.m[index] + other.m[index];
  4714. }
  4715. result._markAsUpdated();
  4716. return this;
  4717. };
  4718. /**
  4719. * Adds in place the passed matrix to the current Matrix.
  4720. * Returns the updated Matrix.
  4721. */
  4722. Matrix.prototype.addToSelf = function (other) {
  4723. for (var index = 0; index < 16; index++) {
  4724. this.m[index] += other.m[index];
  4725. }
  4726. this._markAsUpdated();
  4727. return this;
  4728. };
  4729. /**
  4730. * Sets the passed matrix with the current inverted Matrix.
  4731. * Returns the unmodified current Matrix.
  4732. */
  4733. Matrix.prototype.invertToRef = function (other) {
  4734. var l1 = this.m[0];
  4735. var l2 = this.m[1];
  4736. var l3 = this.m[2];
  4737. var l4 = this.m[3];
  4738. var l5 = this.m[4];
  4739. var l6 = this.m[5];
  4740. var l7 = this.m[6];
  4741. var l8 = this.m[7];
  4742. var l9 = this.m[8];
  4743. var l10 = this.m[9];
  4744. var l11 = this.m[10];
  4745. var l12 = this.m[11];
  4746. var l13 = this.m[12];
  4747. var l14 = this.m[13];
  4748. var l15 = this.m[14];
  4749. var l16 = this.m[15];
  4750. var l17 = (l11 * l16) - (l12 * l15);
  4751. var l18 = (l10 * l16) - (l12 * l14);
  4752. var l19 = (l10 * l15) - (l11 * l14);
  4753. var l20 = (l9 * l16) - (l12 * l13);
  4754. var l21 = (l9 * l15) - (l11 * l13);
  4755. var l22 = (l9 * l14) - (l10 * l13);
  4756. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4757. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4758. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4759. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4760. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4761. var l28 = (l7 * l16) - (l8 * l15);
  4762. var l29 = (l6 * l16) - (l8 * l14);
  4763. var l30 = (l6 * l15) - (l7 * l14);
  4764. var l31 = (l5 * l16) - (l8 * l13);
  4765. var l32 = (l5 * l15) - (l7 * l13);
  4766. var l33 = (l5 * l14) - (l6 * l13);
  4767. var l34 = (l7 * l12) - (l8 * l11);
  4768. var l35 = (l6 * l12) - (l8 * l10);
  4769. var l36 = (l6 * l11) - (l7 * l10);
  4770. var l37 = (l5 * l12) - (l8 * l9);
  4771. var l38 = (l5 * l11) - (l7 * l9);
  4772. var l39 = (l5 * l10) - (l6 * l9);
  4773. other.m[0] = l23 * l27;
  4774. other.m[4] = l24 * l27;
  4775. other.m[8] = l25 * l27;
  4776. other.m[12] = l26 * l27;
  4777. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4778. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4779. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4780. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4781. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4782. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4783. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4784. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4785. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4786. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4787. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4788. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4789. other._markAsUpdated();
  4790. return this;
  4791. };
  4792. /**
  4793. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4794. * Returns the updated Matrix.
  4795. */
  4796. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4797. this.m[12] = x;
  4798. this.m[13] = y;
  4799. this.m[14] = z;
  4800. this._markAsUpdated();
  4801. return this;
  4802. };
  4803. /**
  4804. * Inserts the translation vector in the current Matrix.
  4805. * Returns the updated Matrix.
  4806. */
  4807. Matrix.prototype.setTranslation = function (vector3) {
  4808. this.m[12] = vector3.x;
  4809. this.m[13] = vector3.y;
  4810. this.m[14] = vector3.z;
  4811. this._markAsUpdated();
  4812. return this;
  4813. };
  4814. /**
  4815. * Returns a new Vector3 as the extracted translation from the Matrix.
  4816. */
  4817. Matrix.prototype.getTranslation = function () {
  4818. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4819. };
  4820. /**
  4821. * Fill a Vector3 with the extracted translation from the Matrix.
  4822. */
  4823. Matrix.prototype.getTranslationToRef = function (result) {
  4824. result.x = this.m[12];
  4825. result.y = this.m[13];
  4826. result.z = this.m[14];
  4827. return this;
  4828. };
  4829. /**
  4830. * Remove rotation and scaling part from the Matrix.
  4831. * Returns the updated Matrix.
  4832. */
  4833. Matrix.prototype.removeRotationAndScaling = function () {
  4834. this.setRowFromFloats(0, 1, 0, 0, 0);
  4835. this.setRowFromFloats(1, 0, 1, 0, 0);
  4836. this.setRowFromFloats(2, 0, 0, 1, 0);
  4837. return this;
  4838. };
  4839. /**
  4840. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4841. */
  4842. Matrix.prototype.multiply = function (other) {
  4843. var result = new Matrix();
  4844. this.multiplyToRef(other, result);
  4845. return result;
  4846. };
  4847. /**
  4848. * Updates the current Matrix from the passed one values.
  4849. * Returns the updated Matrix.
  4850. */
  4851. Matrix.prototype.copyFrom = function (other) {
  4852. for (var index = 0; index < 16; index++) {
  4853. this.m[index] = other.m[index];
  4854. }
  4855. this._markAsUpdated();
  4856. return this;
  4857. };
  4858. /**
  4859. * Populates the passed array from the starting index with the Matrix values.
  4860. * Returns the Matrix.
  4861. */
  4862. Matrix.prototype.copyToArray = function (array, offset) {
  4863. if (offset === void 0) { offset = 0; }
  4864. for (var index = 0; index < 16; index++) {
  4865. array[offset + index] = this.m[index];
  4866. }
  4867. return this;
  4868. };
  4869. /**
  4870. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4871. */
  4872. Matrix.prototype.multiplyToRef = function (other, result) {
  4873. this.multiplyToArray(other, result.m, 0);
  4874. result._markAsUpdated();
  4875. return this;
  4876. };
  4877. /**
  4878. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4879. */
  4880. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4881. var tm0 = this.m[0];
  4882. var tm1 = this.m[1];
  4883. var tm2 = this.m[2];
  4884. var tm3 = this.m[3];
  4885. var tm4 = this.m[4];
  4886. var tm5 = this.m[5];
  4887. var tm6 = this.m[6];
  4888. var tm7 = this.m[7];
  4889. var tm8 = this.m[8];
  4890. var tm9 = this.m[9];
  4891. var tm10 = this.m[10];
  4892. var tm11 = this.m[11];
  4893. var tm12 = this.m[12];
  4894. var tm13 = this.m[13];
  4895. var tm14 = this.m[14];
  4896. var tm15 = this.m[15];
  4897. var om0 = other.m[0];
  4898. var om1 = other.m[1];
  4899. var om2 = other.m[2];
  4900. var om3 = other.m[3];
  4901. var om4 = other.m[4];
  4902. var om5 = other.m[5];
  4903. var om6 = other.m[6];
  4904. var om7 = other.m[7];
  4905. var om8 = other.m[8];
  4906. var om9 = other.m[9];
  4907. var om10 = other.m[10];
  4908. var om11 = other.m[11];
  4909. var om12 = other.m[12];
  4910. var om13 = other.m[13];
  4911. var om14 = other.m[14];
  4912. var om15 = other.m[15];
  4913. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4914. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4915. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4916. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4917. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4918. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4919. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4920. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4921. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4922. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4923. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4924. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4925. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4926. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4927. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4928. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4929. return this;
  4930. };
  4931. /**
  4932. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4933. */
  4934. Matrix.prototype.equals = function (value) {
  4935. return value &&
  4936. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4937. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4938. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4939. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4940. };
  4941. /**
  4942. * Returns a new Matrix from the current Matrix.
  4943. */
  4944. Matrix.prototype.clone = function () {
  4945. 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]);
  4946. };
  4947. /**
  4948. * Returns the string "Matrix"
  4949. */
  4950. Matrix.prototype.getClassName = function () {
  4951. return "Matrix";
  4952. };
  4953. /**
  4954. * Returns the Matrix hash code.
  4955. */
  4956. Matrix.prototype.getHashCode = function () {
  4957. var hash = this.m[0] || 0;
  4958. for (var i = 1; i < 16; i++) {
  4959. hash = (hash * 397) ^ (this.m[i] || 0);
  4960. }
  4961. return hash;
  4962. };
  4963. /**
  4964. * Decomposes the current Matrix into :
  4965. * - a scale vector3 passed as a reference to update,
  4966. * - a rotation quaternion passed as a reference to update,
  4967. * - a translation vector3 passed as a reference to update.
  4968. * Returns the true if operation was successful.
  4969. */
  4970. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4971. translation.x = this.m[12];
  4972. translation.y = this.m[13];
  4973. translation.z = this.m[14];
  4974. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4975. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4976. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4977. if (this.determinant() <= 0) {
  4978. scale.y *= -1;
  4979. }
  4980. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4981. rotation.x = 0;
  4982. rotation.y = 0;
  4983. rotation.z = 0;
  4984. rotation.w = 1;
  4985. return false;
  4986. }
  4987. 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]);
  4988. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4989. return true;
  4990. };
  4991. /**
  4992. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4993. * @param ref matrix to store the result
  4994. */
  4995. Matrix.prototype.toNormalMatrix = function (ref) {
  4996. this.invertToRef(ref);
  4997. ref.transpose();
  4998. var m = ref.m;
  4999. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5000. };
  5001. /**
  5002. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5003. */
  5004. Matrix.prototype.getRotationMatrix = function () {
  5005. var result = Matrix.Identity();
  5006. this.getRotationMatrixToRef(result);
  5007. return result;
  5008. };
  5009. /**
  5010. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5011. * Returns the current Matrix.
  5012. */
  5013. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5014. var m = this.m;
  5015. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5016. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5017. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5018. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5019. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5020. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5021. 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);
  5022. return this;
  5023. };
  5024. // Statics
  5025. /**
  5026. * Returns a new Matrix set from the starting index of the passed array.
  5027. */
  5028. Matrix.FromArray = function (array, offset) {
  5029. var result = new Matrix();
  5030. if (!offset) {
  5031. offset = 0;
  5032. }
  5033. Matrix.FromArrayToRef(array, offset, result);
  5034. return result;
  5035. };
  5036. /**
  5037. * Sets the passed "result" matrix from the starting index of the passed array.
  5038. */
  5039. Matrix.FromArrayToRef = function (array, offset, result) {
  5040. for (var index = 0; index < 16; index++) {
  5041. result.m[index] = array[index + offset];
  5042. }
  5043. result._markAsUpdated();
  5044. };
  5045. /**
  5046. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5047. */
  5048. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5049. for (var index = 0; index < 16; index++) {
  5050. result.m[index] = array[index + offset] * scale;
  5051. }
  5052. result._markAsUpdated();
  5053. };
  5054. /**
  5055. * Sets the passed matrix "result" with the 16 passed floats.
  5056. */
  5057. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5058. result.m[0] = initialM11;
  5059. result.m[1] = initialM12;
  5060. result.m[2] = initialM13;
  5061. result.m[3] = initialM14;
  5062. result.m[4] = initialM21;
  5063. result.m[5] = initialM22;
  5064. result.m[6] = initialM23;
  5065. result.m[7] = initialM24;
  5066. result.m[8] = initialM31;
  5067. result.m[9] = initialM32;
  5068. result.m[10] = initialM33;
  5069. result.m[11] = initialM34;
  5070. result.m[12] = initialM41;
  5071. result.m[13] = initialM42;
  5072. result.m[14] = initialM43;
  5073. result.m[15] = initialM44;
  5074. result._markAsUpdated();
  5075. };
  5076. /**
  5077. * Returns the index-th row of the current matrix as a new Vector4.
  5078. */
  5079. Matrix.prototype.getRow = function (index) {
  5080. if (index < 0 || index > 3) {
  5081. return null;
  5082. }
  5083. var i = index * 4;
  5084. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5085. };
  5086. /**
  5087. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5088. * Returns the updated Matrix.
  5089. */
  5090. Matrix.prototype.setRow = function (index, row) {
  5091. if (index < 0 || index > 3) {
  5092. return this;
  5093. }
  5094. var i = index * 4;
  5095. this.m[i + 0] = row.x;
  5096. this.m[i + 1] = row.y;
  5097. this.m[i + 2] = row.z;
  5098. this.m[i + 3] = row.w;
  5099. this._markAsUpdated();
  5100. return this;
  5101. };
  5102. /**
  5103. * Compute the transpose of the matrix.
  5104. * Returns a new Matrix.
  5105. */
  5106. Matrix.prototype.transpose = function () {
  5107. return Matrix.Transpose(this);
  5108. };
  5109. /**
  5110. * Compute the transpose of the matrix.
  5111. * Returns the current matrix.
  5112. */
  5113. Matrix.prototype.transposeToRef = function (result) {
  5114. Matrix.TransposeToRef(this, result);
  5115. return this;
  5116. };
  5117. /**
  5118. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5119. * Returns the updated Matrix.
  5120. */
  5121. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5122. if (index < 0 || index > 3) {
  5123. return this;
  5124. }
  5125. var i = index * 4;
  5126. this.m[i + 0] = x;
  5127. this.m[i + 1] = y;
  5128. this.m[i + 2] = z;
  5129. this.m[i + 3] = w;
  5130. this._markAsUpdated();
  5131. return this;
  5132. };
  5133. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5134. /**
  5135. * Static identity matrix to be used as readonly matrix
  5136. * Must not be updated.
  5137. */
  5138. get: function () {
  5139. return Matrix._identityReadOnly;
  5140. },
  5141. enumerable: true,
  5142. configurable: true
  5143. });
  5144. /**
  5145. * Returns a new Matrix set from the 16 passed floats.
  5146. */
  5147. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5148. var result = new Matrix();
  5149. result.m[0] = initialM11;
  5150. result.m[1] = initialM12;
  5151. result.m[2] = initialM13;
  5152. result.m[3] = initialM14;
  5153. result.m[4] = initialM21;
  5154. result.m[5] = initialM22;
  5155. result.m[6] = initialM23;
  5156. result.m[7] = initialM24;
  5157. result.m[8] = initialM31;
  5158. result.m[9] = initialM32;
  5159. result.m[10] = initialM33;
  5160. result.m[11] = initialM34;
  5161. result.m[12] = initialM41;
  5162. result.m[13] = initialM42;
  5163. result.m[14] = initialM43;
  5164. result.m[15] = initialM44;
  5165. return result;
  5166. };
  5167. /**
  5168. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5169. */
  5170. Matrix.Compose = function (scale, rotation, translation) {
  5171. var result = Matrix.Identity();
  5172. Matrix.ComposeToRef(scale, rotation, translation, result);
  5173. return result;
  5174. };
  5175. /**
  5176. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5177. */
  5178. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5179. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5180. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5181. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5182. result.setTranslation(translation);
  5183. };
  5184. /**
  5185. * Returns a new indentity Matrix.
  5186. */
  5187. Matrix.Identity = function () {
  5188. 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);
  5189. };
  5190. /**
  5191. * Sets the passed "result" as an identity matrix.
  5192. */
  5193. Matrix.IdentityToRef = function (result) {
  5194. 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);
  5195. };
  5196. /**
  5197. * Returns a new zero Matrix.
  5198. */
  5199. Matrix.Zero = function () {
  5200. 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);
  5201. };
  5202. /**
  5203. * Returns a new rotation matrix for "angle" radians around the X axis.
  5204. */
  5205. Matrix.RotationX = function (angle) {
  5206. var result = new Matrix();
  5207. Matrix.RotationXToRef(angle, result);
  5208. return result;
  5209. };
  5210. /**
  5211. * Returns a new Matrix as the passed inverted one.
  5212. */
  5213. Matrix.Invert = function (source) {
  5214. var result = new Matrix();
  5215. source.invertToRef(result);
  5216. return result;
  5217. };
  5218. /**
  5219. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5220. */
  5221. Matrix.RotationXToRef = function (angle, result) {
  5222. var s = Math.sin(angle);
  5223. var c = Math.cos(angle);
  5224. result.m[0] = 1.0;
  5225. result.m[15] = 1.0;
  5226. result.m[5] = c;
  5227. result.m[10] = c;
  5228. result.m[9] = -s;
  5229. result.m[6] = s;
  5230. result.m[1] = 0.0;
  5231. result.m[2] = 0.0;
  5232. result.m[3] = 0.0;
  5233. result.m[4] = 0.0;
  5234. result.m[7] = 0.0;
  5235. result.m[8] = 0.0;
  5236. result.m[11] = 0.0;
  5237. result.m[12] = 0.0;
  5238. result.m[13] = 0.0;
  5239. result.m[14] = 0.0;
  5240. result._markAsUpdated();
  5241. };
  5242. /**
  5243. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5244. */
  5245. Matrix.RotationY = function (angle) {
  5246. var result = new Matrix();
  5247. Matrix.RotationYToRef(angle, result);
  5248. return result;
  5249. };
  5250. /**
  5251. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5252. */
  5253. Matrix.RotationYToRef = function (angle, result) {
  5254. var s = Math.sin(angle);
  5255. var c = Math.cos(angle);
  5256. result.m[5] = 1.0;
  5257. result.m[15] = 1.0;
  5258. result.m[0] = c;
  5259. result.m[2] = -s;
  5260. result.m[8] = s;
  5261. result.m[10] = c;
  5262. result.m[1] = 0.0;
  5263. result.m[3] = 0.0;
  5264. result.m[4] = 0.0;
  5265. result.m[6] = 0.0;
  5266. result.m[7] = 0.0;
  5267. result.m[9] = 0.0;
  5268. result.m[11] = 0.0;
  5269. result.m[12] = 0.0;
  5270. result.m[13] = 0.0;
  5271. result.m[14] = 0.0;
  5272. result._markAsUpdated();
  5273. };
  5274. /**
  5275. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5276. */
  5277. Matrix.RotationZ = function (angle) {
  5278. var result = new Matrix();
  5279. Matrix.RotationZToRef(angle, result);
  5280. return result;
  5281. };
  5282. /**
  5283. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5284. */
  5285. Matrix.RotationZToRef = function (angle, result) {
  5286. var s = Math.sin(angle);
  5287. var c = Math.cos(angle);
  5288. result.m[10] = 1.0;
  5289. result.m[15] = 1.0;
  5290. result.m[0] = c;
  5291. result.m[1] = s;
  5292. result.m[4] = -s;
  5293. result.m[5] = c;
  5294. result.m[2] = 0.0;
  5295. result.m[3] = 0.0;
  5296. result.m[6] = 0.0;
  5297. result.m[7] = 0.0;
  5298. result.m[8] = 0.0;
  5299. result.m[9] = 0.0;
  5300. result.m[11] = 0.0;
  5301. result.m[12] = 0.0;
  5302. result.m[13] = 0.0;
  5303. result.m[14] = 0.0;
  5304. result._markAsUpdated();
  5305. };
  5306. /**
  5307. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5308. */
  5309. Matrix.RotationAxis = function (axis, angle) {
  5310. var result = Matrix.Zero();
  5311. Matrix.RotationAxisToRef(axis, angle, result);
  5312. return result;
  5313. };
  5314. /**
  5315. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5316. */
  5317. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5318. var s = Math.sin(-angle);
  5319. var c = Math.cos(-angle);
  5320. var c1 = 1 - c;
  5321. axis.normalize();
  5322. result.m[0] = (axis.x * axis.x) * c1 + c;
  5323. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5324. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5325. result.m[3] = 0.0;
  5326. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5327. result.m[5] = (axis.y * axis.y) * c1 + c;
  5328. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5329. result.m[7] = 0.0;
  5330. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5331. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5332. result.m[10] = (axis.z * axis.z) * c1 + c;
  5333. result.m[11] = 0.0;
  5334. result.m[15] = 1.0;
  5335. result._markAsUpdated();
  5336. };
  5337. /**
  5338. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5339. */
  5340. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5341. var result = new Matrix();
  5342. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5343. return result;
  5344. };
  5345. /**
  5346. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5347. */
  5348. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5349. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5350. this._tempQuaternion.toRotationMatrix(result);
  5351. };
  5352. /**
  5353. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5354. */
  5355. Matrix.Scaling = function (x, y, z) {
  5356. var result = Matrix.Zero();
  5357. Matrix.ScalingToRef(x, y, z, result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5362. */
  5363. Matrix.ScalingToRef = function (x, y, z, result) {
  5364. result.m[0] = x;
  5365. result.m[1] = 0.0;
  5366. result.m[2] = 0.0;
  5367. result.m[3] = 0.0;
  5368. result.m[4] = 0.0;
  5369. result.m[5] = y;
  5370. result.m[6] = 0.0;
  5371. result.m[7] = 0.0;
  5372. result.m[8] = 0.0;
  5373. result.m[9] = 0.0;
  5374. result.m[10] = z;
  5375. result.m[11] = 0.0;
  5376. result.m[12] = 0.0;
  5377. result.m[13] = 0.0;
  5378. result.m[14] = 0.0;
  5379. result.m[15] = 1.0;
  5380. result._markAsUpdated();
  5381. };
  5382. /**
  5383. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5384. */
  5385. Matrix.Translation = function (x, y, z) {
  5386. var result = Matrix.Identity();
  5387. Matrix.TranslationToRef(x, y, z, result);
  5388. return result;
  5389. };
  5390. /**
  5391. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5392. */
  5393. Matrix.TranslationToRef = function (x, y, z, result) {
  5394. 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);
  5395. };
  5396. /**
  5397. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5398. */
  5399. Matrix.Lerp = function (startValue, endValue, gradient) {
  5400. var result = Matrix.Zero();
  5401. for (var index = 0; index < 16; index++) {
  5402. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5403. }
  5404. result._markAsUpdated();
  5405. return result;
  5406. };
  5407. /**
  5408. * Returns a new Matrix whose values are computed by :
  5409. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5410. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5411. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5412. */
  5413. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5414. var startScale = new Vector3(0, 0, 0);
  5415. var startRotation = new Quaternion();
  5416. var startTranslation = new Vector3(0, 0, 0);
  5417. startValue.decompose(startScale, startRotation, startTranslation);
  5418. var endScale = new Vector3(0, 0, 0);
  5419. var endRotation = new Quaternion();
  5420. var endTranslation = new Vector3(0, 0, 0);
  5421. endValue.decompose(endScale, endRotation, endTranslation);
  5422. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5423. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5424. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5425. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5426. };
  5427. /**
  5428. * 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".
  5429. * This methods works for a Left-Handed system.
  5430. */
  5431. Matrix.LookAtLH = function (eye, target, up) {
  5432. var result = Matrix.Zero();
  5433. Matrix.LookAtLHToRef(eye, target, up, result);
  5434. return result;
  5435. };
  5436. /**
  5437. * 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".
  5438. * This methods works for a Left-Handed system.
  5439. */
  5440. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5441. // Z axis
  5442. target.subtractToRef(eye, this._zAxis);
  5443. this._zAxis.normalize();
  5444. // X axis
  5445. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5446. if (this._xAxis.lengthSquared() === 0) {
  5447. this._xAxis.x = 1.0;
  5448. }
  5449. else {
  5450. this._xAxis.normalize();
  5451. }
  5452. // Y axis
  5453. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5454. this._yAxis.normalize();
  5455. // Eye angles
  5456. var ex = -Vector3.Dot(this._xAxis, eye);
  5457. var ey = -Vector3.Dot(this._yAxis, eye);
  5458. var ez = -Vector3.Dot(this._zAxis, eye);
  5459. 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);
  5460. };
  5461. /**
  5462. * 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".
  5463. * This methods works for a Right-Handed system.
  5464. */
  5465. Matrix.LookAtRH = function (eye, target, up) {
  5466. var result = Matrix.Zero();
  5467. Matrix.LookAtRHToRef(eye, target, up, result);
  5468. return result;
  5469. };
  5470. /**
  5471. * 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".
  5472. * This methods works for a Left-Handed system.
  5473. */
  5474. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5475. // Z axis
  5476. eye.subtractToRef(target, this._zAxis);
  5477. this._zAxis.normalize();
  5478. // X axis
  5479. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5480. if (this._xAxis.lengthSquared() === 0) {
  5481. this._xAxis.x = 1.0;
  5482. }
  5483. else {
  5484. this._xAxis.normalize();
  5485. }
  5486. // Y axis
  5487. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5488. this._yAxis.normalize();
  5489. // Eye angles
  5490. var ex = -Vector3.Dot(this._xAxis, eye);
  5491. var ey = -Vector3.Dot(this._yAxis, eye);
  5492. var ez = -Vector3.Dot(this._zAxis, eye);
  5493. 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);
  5494. };
  5495. /**
  5496. * 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.
  5497. */
  5498. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5499. var matrix = Matrix.Zero();
  5500. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5501. return matrix;
  5502. };
  5503. /**
  5504. * 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.
  5505. */
  5506. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5507. var n = znear;
  5508. var f = zfar;
  5509. var a = 2.0 / width;
  5510. var b = 2.0 / height;
  5511. var c = 2.0 / (f - n);
  5512. var d = -(f + n) / (f - n);
  5513. 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);
  5514. };
  5515. /**
  5516. * 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.
  5517. */
  5518. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5519. var matrix = Matrix.Zero();
  5520. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5521. return matrix;
  5522. };
  5523. /**
  5524. * 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.
  5525. */
  5526. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5527. var n = znear;
  5528. var f = zfar;
  5529. var a = 2.0 / (right - left);
  5530. var b = 2.0 / (top - bottom);
  5531. var c = 2.0 / (f - n);
  5532. var d = -(f + n) / (f - n);
  5533. var i0 = (left + right) / (left - right);
  5534. var i1 = (top + bottom) / (bottom - top);
  5535. 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);
  5536. };
  5537. /**
  5538. * 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.
  5539. */
  5540. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5541. var matrix = Matrix.Zero();
  5542. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5543. return matrix;
  5544. };
  5545. /**
  5546. * 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.
  5547. */
  5548. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5549. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5550. result.m[10] *= -1.0;
  5551. };
  5552. /**
  5553. * 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.
  5554. */
  5555. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5556. var matrix = Matrix.Zero();
  5557. var n = znear;
  5558. var f = zfar;
  5559. var a = 2.0 * n / width;
  5560. var b = 2.0 * n / height;
  5561. var c = (f + n) / (f - n);
  5562. var d = -2.0 * f * n / (f - n);
  5563. 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);
  5564. return matrix;
  5565. };
  5566. /**
  5567. * 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.
  5568. */
  5569. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5570. var matrix = Matrix.Zero();
  5571. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5572. return matrix;
  5573. };
  5574. /**
  5575. * 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.
  5576. */
  5577. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5578. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5579. var n = znear;
  5580. var f = zfar;
  5581. var t = 1.0 / (Math.tan(fov * 0.5));
  5582. var a = isVerticalFovFixed ? (t / aspect) : t;
  5583. var b = isVerticalFovFixed ? t : (t * aspect);
  5584. var c = (f + n) / (f - n);
  5585. var d = -2.0 * f * n / (f - n);
  5586. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5587. };
  5588. /**
  5589. * 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.
  5590. */
  5591. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5592. var matrix = Matrix.Zero();
  5593. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5594. return matrix;
  5595. };
  5596. /**
  5597. * 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.
  5598. */
  5599. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5600. //alternatively this could be expressed as:
  5601. // m = PerspectiveFovLHToRef
  5602. // m[10] *= -1.0;
  5603. // m[11] *= -1.0;
  5604. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5605. var n = znear;
  5606. var f = zfar;
  5607. var t = 1.0 / (Math.tan(fov * 0.5));
  5608. var a = isVerticalFovFixed ? (t / aspect) : t;
  5609. var b = isVerticalFovFixed ? t : (t * aspect);
  5610. var c = -(f + n) / (f - n);
  5611. var d = -2 * f * n / (f - n);
  5612. 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);
  5613. };
  5614. /**
  5615. * 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.
  5616. */
  5617. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5618. if (rightHanded === void 0) { rightHanded = false; }
  5619. var rightHandedFactor = rightHanded ? -1 : 1;
  5620. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5621. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5622. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5623. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5624. var xScale = 2.0 / (leftTan + rightTan);
  5625. var yScale = 2.0 / (upTan + downTan);
  5626. result.m[0] = xScale;
  5627. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5628. result.m[5] = yScale;
  5629. result.m[6] = result.m[7] = 0.0;
  5630. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5631. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5632. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5633. result.m[10] = -zfar / (znear - zfar);
  5634. result.m[11] = 1.0 * rightHandedFactor;
  5635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5636. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5637. // result.m[14] = (znear * zfar) / (znear - zfar);
  5638. result._markAsUpdated();
  5639. };
  5640. /**
  5641. * Returns the final transformation matrix : world * view * projection * viewport
  5642. */
  5643. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5644. var cw = viewport.width;
  5645. var ch = viewport.height;
  5646. var cx = viewport.x;
  5647. var cy = viewport.y;
  5648. 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);
  5649. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5650. };
  5651. /**
  5652. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5653. */
  5654. Matrix.GetAsMatrix2x2 = function (matrix) {
  5655. return new Float32Array([
  5656. matrix.m[0], matrix.m[1],
  5657. matrix.m[4], matrix.m[5]
  5658. ]);
  5659. };
  5660. /**
  5661. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5662. */
  5663. Matrix.GetAsMatrix3x3 = function (matrix) {
  5664. return new Float32Array([
  5665. matrix.m[0], matrix.m[1], matrix.m[2],
  5666. matrix.m[4], matrix.m[5], matrix.m[6],
  5667. matrix.m[8], matrix.m[9], matrix.m[10]
  5668. ]);
  5669. };
  5670. /**
  5671. * Compute the transpose of the passed Matrix.
  5672. * Returns a new Matrix.
  5673. */
  5674. Matrix.Transpose = function (matrix) {
  5675. var result = new Matrix();
  5676. Matrix.TransposeToRef(matrix, result);
  5677. return result;
  5678. };
  5679. /**
  5680. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5681. */
  5682. Matrix.TransposeToRef = function (matrix, result) {
  5683. result.m[0] = matrix.m[0];
  5684. result.m[1] = matrix.m[4];
  5685. result.m[2] = matrix.m[8];
  5686. result.m[3] = matrix.m[12];
  5687. result.m[4] = matrix.m[1];
  5688. result.m[5] = matrix.m[5];
  5689. result.m[6] = matrix.m[9];
  5690. result.m[7] = matrix.m[13];
  5691. result.m[8] = matrix.m[2];
  5692. result.m[9] = matrix.m[6];
  5693. result.m[10] = matrix.m[10];
  5694. result.m[11] = matrix.m[14];
  5695. result.m[12] = matrix.m[3];
  5696. result.m[13] = matrix.m[7];
  5697. result.m[14] = matrix.m[11];
  5698. result.m[15] = matrix.m[15];
  5699. };
  5700. /**
  5701. * Returns a new Matrix as the reflection matrix across the passed plane.
  5702. */
  5703. Matrix.Reflection = function (plane) {
  5704. var matrix = new Matrix();
  5705. Matrix.ReflectionToRef(plane, matrix);
  5706. return matrix;
  5707. };
  5708. /**
  5709. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5710. */
  5711. Matrix.ReflectionToRef = function (plane, result) {
  5712. plane.normalize();
  5713. var x = plane.normal.x;
  5714. var y = plane.normal.y;
  5715. var z = plane.normal.z;
  5716. var temp = -2 * x;
  5717. var temp2 = -2 * y;
  5718. var temp3 = -2 * z;
  5719. result.m[0] = (temp * x) + 1;
  5720. result.m[1] = temp2 * x;
  5721. result.m[2] = temp3 * x;
  5722. result.m[3] = 0.0;
  5723. result.m[4] = temp * y;
  5724. result.m[5] = (temp2 * y) + 1;
  5725. result.m[6] = temp3 * y;
  5726. result.m[7] = 0.0;
  5727. result.m[8] = temp * z;
  5728. result.m[9] = temp2 * z;
  5729. result.m[10] = (temp3 * z) + 1;
  5730. result.m[11] = 0.0;
  5731. result.m[12] = temp * plane.d;
  5732. result.m[13] = temp2 * plane.d;
  5733. result.m[14] = temp3 * plane.d;
  5734. result.m[15] = 1.0;
  5735. result._markAsUpdated();
  5736. };
  5737. /**
  5738. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5739. */
  5740. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5741. result.m[0] = xaxis.x;
  5742. result.m[1] = xaxis.y;
  5743. result.m[2] = xaxis.z;
  5744. result.m[3] = 0.0;
  5745. result.m[4] = yaxis.x;
  5746. result.m[5] = yaxis.y;
  5747. result.m[6] = yaxis.z;
  5748. result.m[7] = 0.0;
  5749. result.m[8] = zaxis.x;
  5750. result.m[9] = zaxis.y;
  5751. result.m[10] = zaxis.z;
  5752. result.m[11] = 0.0;
  5753. result.m[12] = 0.0;
  5754. result.m[13] = 0.0;
  5755. result.m[14] = 0.0;
  5756. result.m[15] = 1.0;
  5757. result._markAsUpdated();
  5758. };
  5759. /**
  5760. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5761. */
  5762. Matrix.FromQuaternionToRef = function (quat, result) {
  5763. var xx = quat.x * quat.x;
  5764. var yy = quat.y * quat.y;
  5765. var zz = quat.z * quat.z;
  5766. var xy = quat.x * quat.y;
  5767. var zw = quat.z * quat.w;
  5768. var zx = quat.z * quat.x;
  5769. var yw = quat.y * quat.w;
  5770. var yz = quat.y * quat.z;
  5771. var xw = quat.x * quat.w;
  5772. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5773. result.m[1] = 2.0 * (xy + zw);
  5774. result.m[2] = 2.0 * (zx - yw);
  5775. result.m[3] = 0.0;
  5776. result.m[4] = 2.0 * (xy - zw);
  5777. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5778. result.m[6] = 2.0 * (yz + xw);
  5779. result.m[7] = 0.0;
  5780. result.m[8] = 2.0 * (zx + yw);
  5781. result.m[9] = 2.0 * (yz - xw);
  5782. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5783. result.m[11] = 0.0;
  5784. result.m[12] = 0.0;
  5785. result.m[13] = 0.0;
  5786. result.m[14] = 0.0;
  5787. result.m[15] = 1.0;
  5788. result._markAsUpdated();
  5789. };
  5790. Matrix._tempQuaternion = new Quaternion();
  5791. Matrix._xAxis = Vector3.Zero();
  5792. Matrix._yAxis = Vector3.Zero();
  5793. Matrix._zAxis = Vector3.Zero();
  5794. Matrix._updateFlagSeed = 0;
  5795. Matrix._identityReadOnly = Matrix.Identity();
  5796. return Matrix;
  5797. }());
  5798. BABYLON.Matrix = Matrix;
  5799. var Plane = /** @class */ (function () {
  5800. /**
  5801. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5802. */
  5803. function Plane(a, b, c, d) {
  5804. this.normal = new Vector3(a, b, c);
  5805. this.d = d;
  5806. }
  5807. /**
  5808. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5809. */
  5810. Plane.prototype.asArray = function () {
  5811. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5812. };
  5813. // Methods
  5814. /**
  5815. * Returns a new plane copied from the current Plane.
  5816. */
  5817. Plane.prototype.clone = function () {
  5818. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5819. };
  5820. /**
  5821. * Returns the string "Plane".
  5822. */
  5823. Plane.prototype.getClassName = function () {
  5824. return "Plane";
  5825. };
  5826. /**
  5827. * Returns the Plane hash code.
  5828. */
  5829. Plane.prototype.getHashCode = function () {
  5830. var hash = this.normal.getHashCode();
  5831. hash = (hash * 397) ^ (this.d || 0);
  5832. return hash;
  5833. };
  5834. /**
  5835. * Normalize the current Plane in place.
  5836. * Returns the updated Plane.
  5837. */
  5838. Plane.prototype.normalize = function () {
  5839. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5840. var magnitude = 0.0;
  5841. if (norm !== 0) {
  5842. magnitude = 1.0 / norm;
  5843. }
  5844. this.normal.x *= magnitude;
  5845. this.normal.y *= magnitude;
  5846. this.normal.z *= magnitude;
  5847. this.d *= magnitude;
  5848. return this;
  5849. };
  5850. /**
  5851. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5852. */
  5853. Plane.prototype.transform = function (transformation) {
  5854. var transposedMatrix = Matrix.Transpose(transformation);
  5855. var x = this.normal.x;
  5856. var y = this.normal.y;
  5857. var z = this.normal.z;
  5858. var d = this.d;
  5859. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5860. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5861. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5862. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5863. return new Plane(normalX, normalY, normalZ, finalD);
  5864. };
  5865. /**
  5866. * Returns the dot product (float) of the point coordinates and the plane normal.
  5867. */
  5868. Plane.prototype.dotCoordinate = function (point) {
  5869. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5870. };
  5871. /**
  5872. * Updates the current Plane from the plane defined by the three passed points.
  5873. * Returns the updated Plane.
  5874. */
  5875. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5876. var x1 = point2.x - point1.x;
  5877. var y1 = point2.y - point1.y;
  5878. var z1 = point2.z - point1.z;
  5879. var x2 = point3.x - point1.x;
  5880. var y2 = point3.y - point1.y;
  5881. var z2 = point3.z - point1.z;
  5882. var yz = (y1 * z2) - (z1 * y2);
  5883. var xz = (z1 * x2) - (x1 * z2);
  5884. var xy = (x1 * y2) - (y1 * x2);
  5885. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5886. var invPyth;
  5887. if (pyth !== 0) {
  5888. invPyth = 1.0 / pyth;
  5889. }
  5890. else {
  5891. invPyth = 0.0;
  5892. }
  5893. this.normal.x = yz * invPyth;
  5894. this.normal.y = xz * invPyth;
  5895. this.normal.z = xy * invPyth;
  5896. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5897. return this;
  5898. };
  5899. /**
  5900. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5901. */
  5902. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5903. var dot = Vector3.Dot(this.normal, direction);
  5904. return (dot <= epsilon);
  5905. };
  5906. /**
  5907. * Returns the signed distance (float) from the passed point to the Plane.
  5908. */
  5909. Plane.prototype.signedDistanceTo = function (point) {
  5910. return Vector3.Dot(point, this.normal) + this.d;
  5911. };
  5912. // Statics
  5913. /**
  5914. * Returns a new Plane from the passed array.
  5915. */
  5916. Plane.FromArray = function (array) {
  5917. return new Plane(array[0], array[1], array[2], array[3]);
  5918. };
  5919. /**
  5920. * Returns a new Plane defined by the three passed points.
  5921. */
  5922. Plane.FromPoints = function (point1, point2, point3) {
  5923. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5924. result.copyFromPoints(point1, point2, point3);
  5925. return result;
  5926. };
  5927. /**
  5928. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5929. * Note : the vector "normal" is updated because normalized.
  5930. */
  5931. Plane.FromPositionAndNormal = function (origin, normal) {
  5932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5933. normal.normalize();
  5934. result.normal = normal;
  5935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5936. return result;
  5937. };
  5938. /**
  5939. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5940. */
  5941. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5942. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5943. return Vector3.Dot(point, normal) + d;
  5944. };
  5945. return Plane;
  5946. }());
  5947. BABYLON.Plane = Plane;
  5948. var Viewport = /** @class */ (function () {
  5949. /**
  5950. * Creates a Viewport object located at (x, y) and sized (width, height).
  5951. */
  5952. function Viewport(x, y, width, height) {
  5953. this.x = x;
  5954. this.y = y;
  5955. this.width = width;
  5956. this.height = height;
  5957. }
  5958. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5959. if (renderWidthOrEngine.getRenderWidth) {
  5960. var engine = renderWidthOrEngine;
  5961. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5962. }
  5963. var renderWidth = renderWidthOrEngine;
  5964. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5965. };
  5966. /**
  5967. * Returns a new Viewport copied from the current one.
  5968. */
  5969. Viewport.prototype.clone = function () {
  5970. return new Viewport(this.x, this.y, this.width, this.height);
  5971. };
  5972. return Viewport;
  5973. }());
  5974. BABYLON.Viewport = Viewport;
  5975. var Frustum = /** @class */ (function () {
  5976. function Frustum() {
  5977. }
  5978. /**
  5979. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5980. */
  5981. Frustum.GetPlanes = function (transform) {
  5982. var frustumPlanes = [];
  5983. for (var index = 0; index < 6; index++) {
  5984. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5985. }
  5986. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5987. return frustumPlanes;
  5988. };
  5989. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5990. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5991. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5992. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5993. frustumPlane.d = transform.m[15] + transform.m[14];
  5994. frustumPlane.normalize();
  5995. };
  5996. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5997. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5998. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5999. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6000. frustumPlane.d = transform.m[15] - transform.m[14];
  6001. frustumPlane.normalize();
  6002. };
  6003. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6004. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6005. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6006. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6007. frustumPlane.d = transform.m[15] + transform.m[12];
  6008. frustumPlane.normalize();
  6009. };
  6010. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6011. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6012. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6013. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6014. frustumPlane.d = transform.m[15] - transform.m[12];
  6015. frustumPlane.normalize();
  6016. };
  6017. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6018. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6019. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6020. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6021. frustumPlane.d = transform.m[15] - transform.m[13];
  6022. frustumPlane.normalize();
  6023. };
  6024. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6025. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6026. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6027. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6028. frustumPlane.d = transform.m[15] + transform.m[13];
  6029. frustumPlane.normalize();
  6030. };
  6031. /**
  6032. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6033. */
  6034. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6035. // Near
  6036. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6037. // Far
  6038. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6039. // Left
  6040. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6041. // Right
  6042. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6043. // Top
  6044. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6045. // Bottom
  6046. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6047. };
  6048. return Frustum;
  6049. }());
  6050. BABYLON.Frustum = Frustum;
  6051. var Space;
  6052. (function (Space) {
  6053. Space[Space["LOCAL"] = 0] = "LOCAL";
  6054. Space[Space["WORLD"] = 1] = "WORLD";
  6055. Space[Space["BONE"] = 2] = "BONE";
  6056. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6057. var Axis = /** @class */ (function () {
  6058. function Axis() {
  6059. }
  6060. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6061. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6062. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6063. return Axis;
  6064. }());
  6065. BABYLON.Axis = Axis;
  6066. ;
  6067. var BezierCurve = /** @class */ (function () {
  6068. function BezierCurve() {
  6069. }
  6070. /**
  6071. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6072. */
  6073. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6074. // Extract X (which is equal to time here)
  6075. var f0 = 1 - 3 * x2 + 3 * x1;
  6076. var f1 = 3 * x2 - 6 * x1;
  6077. var f2 = 3 * x1;
  6078. var refinedT = t;
  6079. for (var i = 0; i < 5; i++) {
  6080. var refinedT2 = refinedT * refinedT;
  6081. var refinedT3 = refinedT2 * refinedT;
  6082. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6083. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6084. refinedT -= (x - t) * slope;
  6085. refinedT = Math.min(1, Math.max(0, refinedT));
  6086. }
  6087. // Resolve cubic bezier for the given x
  6088. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6089. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6090. Math.pow(refinedT, 3);
  6091. };
  6092. return BezierCurve;
  6093. }());
  6094. BABYLON.BezierCurve = BezierCurve;
  6095. var Orientation;
  6096. (function (Orientation) {
  6097. Orientation[Orientation["CW"] = 0] = "CW";
  6098. Orientation[Orientation["CCW"] = 1] = "CCW";
  6099. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6100. var Angle = /** @class */ (function () {
  6101. /**
  6102. * Creates an Angle object of "radians" radians (float).
  6103. */
  6104. function Angle(radians) {
  6105. var _this = this;
  6106. /**
  6107. * Returns the Angle value in degrees (float).
  6108. */
  6109. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6110. /**
  6111. * Returns the Angle value in radians (float).
  6112. */
  6113. this.radians = function () { return _this._radians; };
  6114. this._radians = radians;
  6115. if (this._radians < 0.0)
  6116. this._radians += (2.0 * Math.PI);
  6117. }
  6118. /**
  6119. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6120. */
  6121. Angle.BetweenTwoPoints = function (a, b) {
  6122. var delta = b.subtract(a);
  6123. var theta = Math.atan2(delta.y, delta.x);
  6124. return new Angle(theta);
  6125. };
  6126. /**
  6127. * Returns a new Angle object from the passed float in radians.
  6128. */
  6129. Angle.FromRadians = function (radians) {
  6130. return new Angle(radians);
  6131. };
  6132. /**
  6133. * Returns a new Angle object from the passed float in degrees.
  6134. */
  6135. Angle.FromDegrees = function (degrees) {
  6136. return new Angle(degrees * Math.PI / 180.0);
  6137. };
  6138. return Angle;
  6139. }());
  6140. BABYLON.Angle = Angle;
  6141. var Arc2 = /** @class */ (function () {
  6142. /**
  6143. * Creates an Arc object from the three passed points : start, middle and end.
  6144. */
  6145. function Arc2(startPoint, midPoint, endPoint) {
  6146. this.startPoint = startPoint;
  6147. this.midPoint = midPoint;
  6148. this.endPoint = endPoint;
  6149. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6150. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6151. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6152. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6153. 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);
  6154. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6155. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6156. var a1 = this.startAngle.degrees();
  6157. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6158. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6159. // angles correction
  6160. if (a2 - a1 > +180.0)
  6161. a2 -= 360.0;
  6162. if (a2 - a1 < -180.0)
  6163. a2 += 360.0;
  6164. if (a3 - a2 > +180.0)
  6165. a3 -= 360.0;
  6166. if (a3 - a2 < -180.0)
  6167. a3 += 360.0;
  6168. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6169. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6170. }
  6171. return Arc2;
  6172. }());
  6173. BABYLON.Arc2 = Arc2;
  6174. var Path2 = /** @class */ (function () {
  6175. /**
  6176. * Creates a Path2 object from the starting 2D coordinates x and y.
  6177. */
  6178. function Path2(x, y) {
  6179. this._points = new Array();
  6180. this._length = 0.0;
  6181. this.closed = false;
  6182. this._points.push(new Vector2(x, y));
  6183. }
  6184. /**
  6185. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6186. * Returns the updated Path2.
  6187. */
  6188. Path2.prototype.addLineTo = function (x, y) {
  6189. if (this.closed) {
  6190. //Tools.Error("cannot add lines to closed paths");
  6191. return this;
  6192. }
  6193. var newPoint = new Vector2(x, y);
  6194. var previousPoint = this._points[this._points.length - 1];
  6195. this._points.push(newPoint);
  6196. this._length += newPoint.subtract(previousPoint).length();
  6197. return this;
  6198. };
  6199. /**
  6200. * 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.
  6201. * Returns the updated Path2.
  6202. */
  6203. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6204. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6205. if (this.closed) {
  6206. //Tools.Error("cannot add arcs to closed paths");
  6207. return this;
  6208. }
  6209. var startPoint = this._points[this._points.length - 1];
  6210. var midPoint = new Vector2(midX, midY);
  6211. var endPoint = new Vector2(endX, endY);
  6212. var arc = new Arc2(startPoint, midPoint, endPoint);
  6213. var increment = arc.angle.radians() / numberOfSegments;
  6214. if (arc.orientation === Orientation.CW)
  6215. increment *= -1;
  6216. var currentAngle = arc.startAngle.radians() + increment;
  6217. for (var i = 0; i < numberOfSegments; i++) {
  6218. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6219. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6220. this.addLineTo(x, y);
  6221. currentAngle += increment;
  6222. }
  6223. return this;
  6224. };
  6225. /**
  6226. * Closes the Path2.
  6227. * Returns the Path2.
  6228. */
  6229. Path2.prototype.close = function () {
  6230. this.closed = true;
  6231. return this;
  6232. };
  6233. /**
  6234. * Returns the Path2 total length (float).
  6235. */
  6236. Path2.prototype.length = function () {
  6237. var result = this._length;
  6238. if (!this.closed) {
  6239. var lastPoint = this._points[this._points.length - 1];
  6240. var firstPoint = this._points[0];
  6241. result += (firstPoint.subtract(lastPoint).length());
  6242. }
  6243. return result;
  6244. };
  6245. /**
  6246. * Returns the Path2 internal array of points.
  6247. */
  6248. Path2.prototype.getPoints = function () {
  6249. return this._points;
  6250. };
  6251. /**
  6252. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6253. */
  6254. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6255. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6256. //Tools.Error("normalized length position should be between 0 and 1.");
  6257. return Vector2.Zero();
  6258. }
  6259. var lengthPosition = normalizedLengthPosition * this.length();
  6260. var previousOffset = 0;
  6261. for (var i = 0; i < this._points.length; i++) {
  6262. var j = (i + 1) % this._points.length;
  6263. var a = this._points[i];
  6264. var b = this._points[j];
  6265. var bToA = b.subtract(a);
  6266. var nextOffset = (bToA.length() + previousOffset);
  6267. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6268. var dir = bToA.normalize();
  6269. var localOffset = lengthPosition - previousOffset;
  6270. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6271. }
  6272. previousOffset = nextOffset;
  6273. }
  6274. //Tools.Error("internal error");
  6275. return Vector2.Zero();
  6276. };
  6277. /**
  6278. * Returns a new Path2 starting at the coordinates (x, y).
  6279. */
  6280. Path2.StartingAt = function (x, y) {
  6281. return new Path2(x, y);
  6282. };
  6283. return Path2;
  6284. }());
  6285. BABYLON.Path2 = Path2;
  6286. var Path3D = /** @class */ (function () {
  6287. /**
  6288. * new Path3D(path, normal, raw)
  6289. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6290. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6291. * path : an array of Vector3, the curve axis of the Path3D
  6292. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6293. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6294. */
  6295. function Path3D(path, firstNormal, raw) {
  6296. if (firstNormal === void 0) { firstNormal = null; }
  6297. this.path = path;
  6298. this._curve = new Array();
  6299. this._distances = new Array();
  6300. this._tangents = new Array();
  6301. this._normals = new Array();
  6302. this._binormals = new Array();
  6303. for (var p = 0; p < path.length; p++) {
  6304. this._curve[p] = path[p].clone(); // hard copy
  6305. }
  6306. this._raw = raw || false;
  6307. this._compute(firstNormal);
  6308. }
  6309. /**
  6310. * Returns the Path3D array of successive Vector3 designing its curve.
  6311. */
  6312. Path3D.prototype.getCurve = function () {
  6313. return this._curve;
  6314. };
  6315. /**
  6316. * Returns an array populated with tangent vectors on each Path3D curve point.
  6317. */
  6318. Path3D.prototype.getTangents = function () {
  6319. return this._tangents;
  6320. };
  6321. /**
  6322. * Returns an array populated with normal vectors on each Path3D curve point.
  6323. */
  6324. Path3D.prototype.getNormals = function () {
  6325. return this._normals;
  6326. };
  6327. /**
  6328. * Returns an array populated with binormal vectors on each Path3D curve point.
  6329. */
  6330. Path3D.prototype.getBinormals = function () {
  6331. return this._binormals;
  6332. };
  6333. /**
  6334. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6335. */
  6336. Path3D.prototype.getDistances = function () {
  6337. return this._distances;
  6338. };
  6339. /**
  6340. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6341. * Returns the same object updated.
  6342. */
  6343. Path3D.prototype.update = function (path, firstNormal) {
  6344. if (firstNormal === void 0) { firstNormal = null; }
  6345. for (var p = 0; p < path.length; p++) {
  6346. this._curve[p].x = path[p].x;
  6347. this._curve[p].y = path[p].y;
  6348. this._curve[p].z = path[p].z;
  6349. }
  6350. this._compute(firstNormal);
  6351. return this;
  6352. };
  6353. // private function compute() : computes tangents, normals and binormals
  6354. Path3D.prototype._compute = function (firstNormal) {
  6355. var l = this._curve.length;
  6356. // first and last tangents
  6357. this._tangents[0] = this._getFirstNonNullVector(0);
  6358. if (!this._raw) {
  6359. this._tangents[0].normalize();
  6360. }
  6361. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6362. if (!this._raw) {
  6363. this._tangents[l - 1].normalize();
  6364. }
  6365. // normals and binormals at first point : arbitrary vector with _normalVector()
  6366. var tg0 = this._tangents[0];
  6367. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6368. this._normals[0] = pp0;
  6369. if (!this._raw) {
  6370. this._normals[0].normalize();
  6371. }
  6372. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6373. if (!this._raw) {
  6374. this._binormals[0].normalize();
  6375. }
  6376. this._distances[0] = 0.0;
  6377. // normals and binormals : next points
  6378. var prev; // previous vector (segment)
  6379. var cur; // current vector (segment)
  6380. var curTang; // current tangent
  6381. // previous normal
  6382. var prevBinor; // previous binormal
  6383. for (var i = 1; i < l; i++) {
  6384. // tangents
  6385. prev = this._getLastNonNullVector(i);
  6386. if (i < l - 1) {
  6387. cur = this._getFirstNonNullVector(i);
  6388. this._tangents[i] = prev.add(cur);
  6389. this._tangents[i].normalize();
  6390. }
  6391. this._distances[i] = this._distances[i - 1] + prev.length();
  6392. // normals and binormals
  6393. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6394. curTang = this._tangents[i];
  6395. prevBinor = this._binormals[i - 1];
  6396. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6397. if (!this._raw) {
  6398. this._normals[i].normalize();
  6399. }
  6400. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6401. if (!this._raw) {
  6402. this._binormals[i].normalize();
  6403. }
  6404. }
  6405. };
  6406. // private function getFirstNonNullVector(index)
  6407. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6408. Path3D.prototype._getFirstNonNullVector = function (index) {
  6409. var i = 1;
  6410. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6411. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6412. i++;
  6413. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6414. }
  6415. return nNVector;
  6416. };
  6417. // private function getLastNonNullVector(index)
  6418. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6419. Path3D.prototype._getLastNonNullVector = function (index) {
  6420. var i = 1;
  6421. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6422. while (nLVector.length() === 0 && index > i + 1) {
  6423. i++;
  6424. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6425. }
  6426. return nLVector;
  6427. };
  6428. // private function normalVector(v0, vt, va) :
  6429. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6430. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6431. Path3D.prototype._normalVector = function (v0, vt, va) {
  6432. var normal0;
  6433. var tgl = vt.length();
  6434. if (tgl === 0.0) {
  6435. tgl = 1.0;
  6436. }
  6437. if (va === undefined || va === null) {
  6438. var point;
  6439. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6440. point = new Vector3(0.0, -1.0, 0.0);
  6441. }
  6442. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6443. point = new Vector3(1.0, 0.0, 0.0);
  6444. }
  6445. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6446. point = new Vector3(0.0, 0.0, 1.0);
  6447. }
  6448. else {
  6449. point = Vector3.Zero();
  6450. }
  6451. normal0 = Vector3.Cross(vt, point);
  6452. }
  6453. else {
  6454. normal0 = Vector3.Cross(vt, va);
  6455. Vector3.CrossToRef(normal0, vt, normal0);
  6456. }
  6457. normal0.normalize();
  6458. return normal0;
  6459. };
  6460. return Path3D;
  6461. }());
  6462. BABYLON.Path3D = Path3D;
  6463. var Curve3 = /** @class */ (function () {
  6464. /**
  6465. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6466. * A Curve3 is designed from a series of successive Vector3.
  6467. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6468. */
  6469. function Curve3(points) {
  6470. this._length = 0.0;
  6471. this._points = points;
  6472. this._length = this._computeLength(points);
  6473. }
  6474. /**
  6475. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6476. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6477. * @param v1 (Vector3) the control point
  6478. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6479. * @param nbPoints (integer) the wanted number of points in the curve
  6480. */
  6481. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6482. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6483. var bez = new Array();
  6484. var equation = function (t, val0, val1, val2) {
  6485. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6486. return res;
  6487. };
  6488. for (var i = 0; i <= nbPoints; i++) {
  6489. 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)));
  6490. }
  6491. return new Curve3(bez);
  6492. };
  6493. /**
  6494. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6495. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6496. * @param v1 (Vector3) the first control point
  6497. * @param v2 (Vector3) the second control point
  6498. * @param v3 (Vector3) the end point of the Cubic Bezier
  6499. * @param nbPoints (integer) the wanted number of points in the curve
  6500. */
  6501. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6502. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6503. var bez = new Array();
  6504. var equation = function (t, val0, val1, val2, val3) {
  6505. 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;
  6506. return res;
  6507. };
  6508. for (var i = 0; i <= nbPoints; i++) {
  6509. 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)));
  6510. }
  6511. return new Curve3(bez);
  6512. };
  6513. /**
  6514. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6515. * @param p1 (Vector3) the origin point of the Hermite Spline
  6516. * @param t1 (Vector3) the tangent vector at the origin point
  6517. * @param p2 (Vector3) the end point of the Hermite Spline
  6518. * @param t2 (Vector3) the tangent vector at the end point
  6519. * @param nbPoints (integer) the wanted number of points in the curve
  6520. */
  6521. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6522. var hermite = new Array();
  6523. var step = 1.0 / nbPoints;
  6524. for (var i = 0; i <= nbPoints; i++) {
  6525. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6526. }
  6527. return new Curve3(hermite);
  6528. };
  6529. /**
  6530. * Returns a Curve3 object along a CatmullRom Spline curve :
  6531. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6532. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6533. */
  6534. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6535. var totalPoints = new Array();
  6536. totalPoints.push(points[0].clone());
  6537. Array.prototype.push.apply(totalPoints, points);
  6538. totalPoints.push(points[points.length - 1].clone());
  6539. var catmullRom = new Array();
  6540. var step = 1.0 / nbPoints;
  6541. var amount = 0.0;
  6542. for (var i = 0; i < totalPoints.length - 3; i++) {
  6543. amount = 0;
  6544. for (var c = 0; c < nbPoints; c++) {
  6545. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6546. amount += step;
  6547. }
  6548. }
  6549. i--;
  6550. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6551. return new Curve3(catmullRom);
  6552. };
  6553. /**
  6554. * Returns the Curve3 stored array of successive Vector3
  6555. */
  6556. Curve3.prototype.getPoints = function () {
  6557. return this._points;
  6558. };
  6559. /**
  6560. * Returns the computed length (float) of the curve.
  6561. */
  6562. Curve3.prototype.length = function () {
  6563. return this._length;
  6564. };
  6565. /**
  6566. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6567. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6568. * curveA and curveB keep unchanged.
  6569. */
  6570. Curve3.prototype.continue = function (curve) {
  6571. var lastPoint = this._points[this._points.length - 1];
  6572. var continuedPoints = this._points.slice();
  6573. var curvePoints = curve.getPoints();
  6574. for (var i = 1; i < curvePoints.length; i++) {
  6575. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6576. }
  6577. var continuedCurve = new Curve3(continuedPoints);
  6578. return continuedCurve;
  6579. };
  6580. Curve3.prototype._computeLength = function (path) {
  6581. var l = 0;
  6582. for (var i = 1; i < path.length; i++) {
  6583. l += (path[i].subtract(path[i - 1])).length();
  6584. }
  6585. return l;
  6586. };
  6587. return Curve3;
  6588. }());
  6589. BABYLON.Curve3 = Curve3;
  6590. // Vertex formats
  6591. var PositionNormalVertex = /** @class */ (function () {
  6592. function PositionNormalVertex(position, normal) {
  6593. if (position === void 0) { position = Vector3.Zero(); }
  6594. if (normal === void 0) { normal = Vector3.Up(); }
  6595. this.position = position;
  6596. this.normal = normal;
  6597. }
  6598. PositionNormalVertex.prototype.clone = function () {
  6599. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6600. };
  6601. return PositionNormalVertex;
  6602. }());
  6603. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6604. var PositionNormalTextureVertex = /** @class */ (function () {
  6605. function PositionNormalTextureVertex(position, normal, uv) {
  6606. if (position === void 0) { position = Vector3.Zero(); }
  6607. if (normal === void 0) { normal = Vector3.Up(); }
  6608. if (uv === void 0) { uv = Vector2.Zero(); }
  6609. this.position = position;
  6610. this.normal = normal;
  6611. this.uv = uv;
  6612. }
  6613. PositionNormalTextureVertex.prototype.clone = function () {
  6614. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6615. };
  6616. return PositionNormalTextureVertex;
  6617. }());
  6618. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6619. // Temporary pre-allocated objects for engine internal use
  6620. // usage in any internal function :
  6621. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6622. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6623. var Tmp = /** @class */ (function () {
  6624. function Tmp() {
  6625. }
  6626. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6627. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6628. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6629. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6630. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6631. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6632. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6633. Matrix.Zero(), Matrix.Zero(),
  6634. Matrix.Zero(), Matrix.Zero(),
  6635. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6636. return Tmp;
  6637. }());
  6638. BABYLON.Tmp = Tmp;
  6639. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6640. var MathTmp = /** @class */ (function () {
  6641. function MathTmp() {
  6642. }
  6643. MathTmp.Vector3 = [Vector3.Zero()];
  6644. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6645. MathTmp.Quaternion = [Quaternion.Zero()];
  6646. return MathTmp;
  6647. }());
  6648. })(BABYLON || (BABYLON = {}));
  6649. //# sourceMappingURL=babylon.math.js.map
  6650. var BABYLON;
  6651. (function (BABYLON) {
  6652. var Scalar = /** @class */ (function () {
  6653. function Scalar() {
  6654. }
  6655. /**
  6656. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6657. */
  6658. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6659. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6660. var num = a - b;
  6661. return -epsilon <= num && num <= epsilon;
  6662. };
  6663. /**
  6664. * Returns a string : the upper case translation of the number i to hexadecimal.
  6665. */
  6666. Scalar.ToHex = function (i) {
  6667. var str = i.toString(16);
  6668. if (i <= 15) {
  6669. return ("0" + str).toUpperCase();
  6670. }
  6671. return str.toUpperCase();
  6672. };
  6673. /**
  6674. * Returns -1 if value is negative and +1 is value is positive.
  6675. * Returns the value itself if it's equal to zero.
  6676. */
  6677. Scalar.Sign = function (value) {
  6678. value = +value; // convert to a number
  6679. if (value === 0 || isNaN(value))
  6680. return value;
  6681. return value > 0 ? 1 : -1;
  6682. };
  6683. /**
  6684. * Returns the value itself if it's between min and max.
  6685. * Returns min if the value is lower than min.
  6686. * Returns max if the value is greater than max.
  6687. */
  6688. Scalar.Clamp = function (value, min, max) {
  6689. if (min === void 0) { min = 0; }
  6690. if (max === void 0) { max = 1; }
  6691. return Math.min(max, Math.max(min, value));
  6692. };
  6693. /**
  6694. * Returns the log2 of value.
  6695. */
  6696. Scalar.Log2 = function (value) {
  6697. return Math.log(value) * Math.LOG2E;
  6698. };
  6699. /**
  6700. * Loops the value, so that it is never larger than length and never smaller than 0.
  6701. *
  6702. * This is similar to the modulo operator but it works with floating point numbers.
  6703. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6704. * With t = 5 and length = 2.5, the result would be 0.0.
  6705. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6706. */
  6707. Scalar.Repeat = function (value, length) {
  6708. return value - Math.floor(value / length) * length;
  6709. };
  6710. /**
  6711. * Normalize the value between 0.0 and 1.0 using min and max values
  6712. */
  6713. Scalar.Normalize = function (value, min, max) {
  6714. return (value - min) / (max - min);
  6715. };
  6716. /**
  6717. * Denormalize the value from 0.0 and 1.0 using min and max values
  6718. */
  6719. Scalar.Denormalize = function (normalized, min, max) {
  6720. return (normalized * (max - min) + min);
  6721. };
  6722. /**
  6723. * Calculates the shortest difference between two given angles given in degrees.
  6724. */
  6725. Scalar.DeltaAngle = function (current, target) {
  6726. var num = Scalar.Repeat(target - current, 360.0);
  6727. if (num > 180.0) {
  6728. num -= 360.0;
  6729. }
  6730. return num;
  6731. };
  6732. /**
  6733. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6734. *
  6735. * The returned value will move back and forth between 0 and length
  6736. */
  6737. Scalar.PingPong = function (tx, length) {
  6738. var t = Scalar.Repeat(tx, length * 2.0);
  6739. return length - Math.abs(t - length);
  6740. };
  6741. /**
  6742. * Interpolates between min and max with smoothing at the limits.
  6743. *
  6744. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6745. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6746. */
  6747. Scalar.SmoothStep = function (from, to, tx) {
  6748. var t = Scalar.Clamp(tx);
  6749. t = -2.0 * t * t * t + 3.0 * t * t;
  6750. return to * t + from * (1.0 - t);
  6751. };
  6752. /**
  6753. * Moves a value current towards target.
  6754. *
  6755. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6756. * Negative values of maxDelta pushes the value away from target.
  6757. */
  6758. Scalar.MoveTowards = function (current, target, maxDelta) {
  6759. var result = 0;
  6760. if (Math.abs(target - current) <= maxDelta) {
  6761. result = target;
  6762. }
  6763. else {
  6764. result = current + Scalar.Sign(target - current) * maxDelta;
  6765. }
  6766. return result;
  6767. };
  6768. /**
  6769. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6770. *
  6771. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6772. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6773. */
  6774. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6775. var num = Scalar.DeltaAngle(current, target);
  6776. var result = 0;
  6777. if (-maxDelta < num && num < maxDelta) {
  6778. result = target;
  6779. }
  6780. else {
  6781. target = current + num;
  6782. result = Scalar.MoveTowards(current, target, maxDelta);
  6783. }
  6784. return result;
  6785. };
  6786. /**
  6787. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6788. */
  6789. Scalar.Lerp = function (start, end, amount) {
  6790. return start + ((end - start) * amount);
  6791. };
  6792. /**
  6793. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6794. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6795. */
  6796. Scalar.LerpAngle = function (start, end, amount) {
  6797. var num = Scalar.Repeat(end - start, 360.0);
  6798. if (num > 180.0) {
  6799. num -= 360.0;
  6800. }
  6801. return start + num * Scalar.Clamp(amount);
  6802. };
  6803. /**
  6804. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6805. */
  6806. Scalar.InverseLerp = function (a, b, value) {
  6807. var result = 0;
  6808. if (a != b) {
  6809. result = Scalar.Clamp((value - a) / (b - a));
  6810. }
  6811. else {
  6812. result = 0.0;
  6813. }
  6814. return result;
  6815. };
  6816. /**
  6817. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6818. */
  6819. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6820. var squared = amount * amount;
  6821. var cubed = amount * squared;
  6822. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6823. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6824. var part3 = (cubed - (2.0 * squared)) + amount;
  6825. var part4 = cubed - squared;
  6826. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6827. };
  6828. /**
  6829. * Returns a random float number between and min and max values
  6830. */
  6831. Scalar.RandomRange = function (min, max) {
  6832. if (min === max)
  6833. return min;
  6834. return ((Math.random() * (max - min)) + min);
  6835. };
  6836. /**
  6837. * This function returns percentage of a number in a given range.
  6838. *
  6839. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6840. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6841. */
  6842. Scalar.RangeToPercent = function (number, min, max) {
  6843. return ((number - min) / (max - min));
  6844. };
  6845. /**
  6846. * This function returns number that corresponds to the percentage in a given range.
  6847. *
  6848. * PercentToRange(0.34,0,100) will return 34.
  6849. */
  6850. Scalar.PercentToRange = function (percent, min, max) {
  6851. return ((max - min) * percent + min);
  6852. };
  6853. /**
  6854. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6855. * @param angle The angle to normalize in radian.
  6856. * @return The converted angle.
  6857. */
  6858. Scalar.NormalizeRadians = function (angle) {
  6859. // More precise but slower version kept for reference.
  6860. // angle = angle % Tools.TwoPi;
  6861. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6862. //if (angle > Math.PI) {
  6863. // angle -= Tools.TwoPi;
  6864. //}
  6865. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6866. return angle;
  6867. };
  6868. /**
  6869. * Two pi constants convenient for computation.
  6870. */
  6871. Scalar.TwoPi = Math.PI * 2;
  6872. return Scalar;
  6873. }());
  6874. BABYLON.Scalar = Scalar;
  6875. })(BABYLON || (BABYLON = {}));
  6876. //# sourceMappingURL=babylon.math.scalar.js.map
  6877. //# sourceMappingURL=babylon.mixins.js.map
  6878. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6879. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6880. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6881. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6882. //# sourceMappingURL=babylon.webgl2.js.map
  6883. var BABYLON;
  6884. (function (BABYLON) {
  6885. var __decoratorInitialStore = {};
  6886. var __mergedStore = {};
  6887. var _copySource = function (creationFunction, source, instanciate) {
  6888. var destination = creationFunction();
  6889. // Tags
  6890. if (BABYLON.Tags) {
  6891. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6892. }
  6893. var classStore = getMergedStore(destination);
  6894. // Properties
  6895. for (var property in classStore) {
  6896. var propertyDescriptor = classStore[property];
  6897. var sourceProperty = source[property];
  6898. var propertyType = propertyDescriptor.type;
  6899. if (sourceProperty !== undefined && sourceProperty !== null) {
  6900. switch (propertyType) {
  6901. case 0: // Value
  6902. case 6:// Mesh reference
  6903. destination[property] = sourceProperty;
  6904. break;
  6905. case 1:// Texture
  6906. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6907. break;
  6908. case 2: // Color3
  6909. case 3: // FresnelParameters
  6910. case 4: // Vector2
  6911. case 5: // Vector3
  6912. case 7: // Color Curves
  6913. case 10:// Quaternion
  6914. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6915. break;
  6916. }
  6917. }
  6918. }
  6919. return destination;
  6920. };
  6921. function getDirectStore(target) {
  6922. var classKey = target.getClassName();
  6923. if (!__decoratorInitialStore[classKey]) {
  6924. __decoratorInitialStore[classKey] = {};
  6925. }
  6926. return __decoratorInitialStore[classKey];
  6927. }
  6928. /**
  6929. * Return the list of properties flagged as serializable
  6930. * @param target: host object
  6931. */
  6932. function getMergedStore(target) {
  6933. var classKey = target.getClassName();
  6934. if (__mergedStore[classKey]) {
  6935. return __mergedStore[classKey];
  6936. }
  6937. __mergedStore[classKey] = {};
  6938. var store = __mergedStore[classKey];
  6939. var currentTarget = target;
  6940. var currentKey = classKey;
  6941. while (currentKey) {
  6942. var initialStore = __decoratorInitialStore[currentKey];
  6943. for (var property in initialStore) {
  6944. store[property] = initialStore[property];
  6945. }
  6946. var parent_1 = void 0;
  6947. var done = false;
  6948. do {
  6949. parent_1 = Object.getPrototypeOf(currentTarget);
  6950. if (!parent_1.getClassName) {
  6951. done = true;
  6952. break;
  6953. }
  6954. if (parent_1.getClassName() !== currentKey) {
  6955. break;
  6956. }
  6957. currentTarget = parent_1;
  6958. } while (parent_1);
  6959. if (done) {
  6960. break;
  6961. }
  6962. currentKey = parent_1.getClassName();
  6963. currentTarget = parent_1;
  6964. }
  6965. return store;
  6966. }
  6967. function generateSerializableMember(type, sourceName) {
  6968. return function (target, propertyKey) {
  6969. var classStore = getDirectStore(target);
  6970. if (!classStore[propertyKey]) {
  6971. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6972. }
  6973. };
  6974. }
  6975. function generateExpandMember(setCallback, targetKey) {
  6976. if (targetKey === void 0) { targetKey = null; }
  6977. return function (target, propertyKey) {
  6978. var key = targetKey || ("_" + propertyKey);
  6979. Object.defineProperty(target, propertyKey, {
  6980. get: function () {
  6981. return this[key];
  6982. },
  6983. set: function (value) {
  6984. if (this[key] === value) {
  6985. return;
  6986. }
  6987. this[key] = value;
  6988. target[setCallback].apply(this);
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. };
  6994. }
  6995. function expandToProperty(callback, targetKey) {
  6996. if (targetKey === void 0) { targetKey = null; }
  6997. return generateExpandMember(callback, targetKey);
  6998. }
  6999. BABYLON.expandToProperty = expandToProperty;
  7000. function serialize(sourceName) {
  7001. return generateSerializableMember(0, sourceName); // value member
  7002. }
  7003. BABYLON.serialize = serialize;
  7004. function serializeAsTexture(sourceName) {
  7005. return generateSerializableMember(1, sourceName); // texture member
  7006. }
  7007. BABYLON.serializeAsTexture = serializeAsTexture;
  7008. function serializeAsColor3(sourceName) {
  7009. return generateSerializableMember(2, sourceName); // color3 member
  7010. }
  7011. BABYLON.serializeAsColor3 = serializeAsColor3;
  7012. function serializeAsFresnelParameters(sourceName) {
  7013. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7014. }
  7015. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7016. function serializeAsVector2(sourceName) {
  7017. return generateSerializableMember(4, sourceName); // vector2 member
  7018. }
  7019. BABYLON.serializeAsVector2 = serializeAsVector2;
  7020. function serializeAsVector3(sourceName) {
  7021. return generateSerializableMember(5, sourceName); // vector3 member
  7022. }
  7023. BABYLON.serializeAsVector3 = serializeAsVector3;
  7024. function serializeAsMeshReference(sourceName) {
  7025. return generateSerializableMember(6, sourceName); // mesh reference member
  7026. }
  7027. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7028. function serializeAsColorCurves(sourceName) {
  7029. return generateSerializableMember(7, sourceName); // color curves
  7030. }
  7031. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7032. function serializeAsColor4(sourceName) {
  7033. return generateSerializableMember(8, sourceName); // color 4
  7034. }
  7035. BABYLON.serializeAsColor4 = serializeAsColor4;
  7036. function serializeAsImageProcessingConfiguration(sourceName) {
  7037. return generateSerializableMember(9, sourceName); // image processing
  7038. }
  7039. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7040. function serializeAsQuaternion(sourceName) {
  7041. return generateSerializableMember(10, sourceName); // quaternion member
  7042. }
  7043. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7044. var SerializationHelper = /** @class */ (function () {
  7045. function SerializationHelper() {
  7046. }
  7047. SerializationHelper.Serialize = function (entity, serializationObject) {
  7048. if (!serializationObject) {
  7049. serializationObject = {};
  7050. }
  7051. // Tags
  7052. if (BABYLON.Tags) {
  7053. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7054. }
  7055. var serializedProperties = getMergedStore(entity);
  7056. // Properties
  7057. for (var property in serializedProperties) {
  7058. var propertyDescriptor = serializedProperties[property];
  7059. var targetPropertyName = propertyDescriptor.sourceName || property;
  7060. var propertyType = propertyDescriptor.type;
  7061. var sourceProperty = entity[property];
  7062. if (sourceProperty !== undefined && sourceProperty !== null) {
  7063. switch (propertyType) {
  7064. case 0:// Value
  7065. serializationObject[targetPropertyName] = sourceProperty;
  7066. break;
  7067. case 1:// Texture
  7068. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7069. break;
  7070. case 2:// Color3
  7071. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7072. break;
  7073. case 3:// FresnelParameters
  7074. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7075. break;
  7076. case 4:// Vector2
  7077. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7078. break;
  7079. case 5:// Vector3
  7080. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7081. break;
  7082. case 6:// Mesh reference
  7083. serializationObject[targetPropertyName] = sourceProperty.id;
  7084. break;
  7085. case 7:// Color Curves
  7086. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7087. break;
  7088. case 8:// Color 4
  7089. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7090. break;
  7091. case 9:// Image Processing
  7092. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7093. break;
  7094. }
  7095. }
  7096. }
  7097. return serializationObject;
  7098. };
  7099. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7100. if (rootUrl === void 0) { rootUrl = null; }
  7101. var destination = creationFunction();
  7102. if (!rootUrl) {
  7103. rootUrl = "";
  7104. }
  7105. // Tags
  7106. if (BABYLON.Tags) {
  7107. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7108. }
  7109. var classStore = getMergedStore(destination);
  7110. // Properties
  7111. for (var property in classStore) {
  7112. var propertyDescriptor = classStore[property];
  7113. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7114. var propertyType = propertyDescriptor.type;
  7115. if (sourceProperty !== undefined && sourceProperty !== null) {
  7116. var dest = destination;
  7117. switch (propertyType) {
  7118. case 0:// Value
  7119. dest[property] = sourceProperty;
  7120. break;
  7121. case 1:// Texture
  7122. if (scene) {
  7123. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7124. }
  7125. break;
  7126. case 2:// Color3
  7127. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7128. break;
  7129. case 3:// FresnelParameters
  7130. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7131. break;
  7132. case 4:// Vector2
  7133. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7134. break;
  7135. case 5:// Vector3
  7136. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7137. break;
  7138. case 6:// Mesh reference
  7139. if (scene) {
  7140. dest[property] = scene.getLastMeshByID(sourceProperty);
  7141. }
  7142. break;
  7143. case 7:// Color Curves
  7144. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7145. break;
  7146. case 8:// Color 4
  7147. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7148. break;
  7149. case 9:// Image Processing
  7150. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7151. break;
  7152. }
  7153. }
  7154. }
  7155. return destination;
  7156. };
  7157. SerializationHelper.Clone = function (creationFunction, source) {
  7158. return _copySource(creationFunction, source, false);
  7159. };
  7160. SerializationHelper.Instanciate = function (creationFunction, source) {
  7161. return _copySource(creationFunction, source, true);
  7162. };
  7163. return SerializationHelper;
  7164. }());
  7165. BABYLON.SerializationHelper = SerializationHelper;
  7166. })(BABYLON || (BABYLON = {}));
  7167. //# sourceMappingURL=babylon.decorators.js.map
  7168. var BABYLON;
  7169. (function (BABYLON) {
  7170. /**
  7171. * Wrapper class for promise with external resolve and reject.
  7172. */
  7173. var Deferred = /** @class */ (function () {
  7174. /**
  7175. * Constructor for this deferred object.
  7176. */
  7177. function Deferred() {
  7178. var _this = this;
  7179. this.promise = new Promise(function (resolve, reject) {
  7180. _this._resolve = resolve;
  7181. _this._reject = reject;
  7182. });
  7183. }
  7184. Object.defineProperty(Deferred.prototype, "resolve", {
  7185. /**
  7186. * The resolve method of the promise associated with this deferred object.
  7187. */
  7188. get: function () {
  7189. return this._resolve;
  7190. },
  7191. enumerable: true,
  7192. configurable: true
  7193. });
  7194. Object.defineProperty(Deferred.prototype, "reject", {
  7195. /**
  7196. * The reject method of the promise associated with this deferred object.
  7197. */
  7198. get: function () {
  7199. return this._reject;
  7200. },
  7201. enumerable: true,
  7202. configurable: true
  7203. });
  7204. return Deferred;
  7205. }());
  7206. BABYLON.Deferred = Deferred;
  7207. })(BABYLON || (BABYLON = {}));
  7208. //# sourceMappingURL=babylon.deferred.js.map
  7209. var BABYLON;
  7210. (function (BABYLON) {
  7211. /**
  7212. * A class serves as a medium between the observable and its observers
  7213. */
  7214. var EventState = /** @class */ (function () {
  7215. /**
  7216. * Create a new EventState
  7217. * @param mask defines the mask associated with this state
  7218. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7219. * @param target defines the original target of the state
  7220. * @param currentTarget defines the current target of the state
  7221. */
  7222. function EventState(mask, skipNextObservers, target, currentTarget) {
  7223. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7224. this.initalize(mask, skipNextObservers, target, currentTarget);
  7225. }
  7226. /**
  7227. * Initialize the current event state
  7228. * @param mask defines the mask associated with this state
  7229. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7230. * @param target defines the original target of the state
  7231. * @param currentTarget defines the current target of the state
  7232. * @returns the current event state
  7233. */
  7234. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7235. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7236. this.mask = mask;
  7237. this.skipNextObservers = skipNextObservers;
  7238. this.target = target;
  7239. this.currentTarget = currentTarget;
  7240. return this;
  7241. };
  7242. return EventState;
  7243. }());
  7244. BABYLON.EventState = EventState;
  7245. /**
  7246. * Represent an Observer registered to a given Observable object.
  7247. */
  7248. var Observer = /** @class */ (function () {
  7249. /**
  7250. * Creates a new observer
  7251. * @param callback defines the callback to call when the observer is notified
  7252. * @param mask defines the mask of the observer (used to filter notifications)
  7253. * @param scope defines the current scope used to restore the JS context
  7254. */
  7255. function Observer(
  7256. /**
  7257. * Defines the callback to call when the observer is notified
  7258. */
  7259. callback,
  7260. /**
  7261. * Defines the mask of the observer (used to filter notifications)
  7262. */
  7263. mask,
  7264. /**
  7265. * Defines the current scope used to restore the JS context
  7266. */
  7267. scope) {
  7268. if (scope === void 0) { scope = null; }
  7269. this.callback = callback;
  7270. this.mask = mask;
  7271. this.scope = scope;
  7272. /** @ignore */
  7273. this._willBeUnregistered = false;
  7274. /**
  7275. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7276. */
  7277. this.unregisterOnNextCall = false;
  7278. }
  7279. return Observer;
  7280. }());
  7281. BABYLON.Observer = Observer;
  7282. /**
  7283. * Represent a list of observers registered to multiple Observables object.
  7284. */
  7285. var MultiObserver = /** @class */ (function () {
  7286. function MultiObserver() {
  7287. }
  7288. /**
  7289. * Release associated resources
  7290. */
  7291. MultiObserver.prototype.dispose = function () {
  7292. if (this._observers && this._observables) {
  7293. for (var index = 0; index < this._observers.length; index++) {
  7294. this._observables[index].remove(this._observers[index]);
  7295. }
  7296. }
  7297. this._observers = null;
  7298. this._observables = null;
  7299. };
  7300. /**
  7301. * Raise a callback when one of the observable will notify
  7302. * @param observables defines a list of observables to watch
  7303. * @param callback defines the callback to call on notification
  7304. * @param mask defines the mask used to filter notifications
  7305. * @param scope defines the current scope used to restore the JS context
  7306. * @returns the new MultiObserver
  7307. */
  7308. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7309. if (mask === void 0) { mask = -1; }
  7310. if (scope === void 0) { scope = null; }
  7311. var result = new MultiObserver();
  7312. result._observers = new Array();
  7313. result._observables = observables;
  7314. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7315. var observable = observables_1[_i];
  7316. var observer = observable.add(callback, mask, false, scope);
  7317. if (observer) {
  7318. result._observers.push(observer);
  7319. }
  7320. }
  7321. return result;
  7322. };
  7323. return MultiObserver;
  7324. }());
  7325. BABYLON.MultiObserver = MultiObserver;
  7326. /**
  7327. * The Observable class is a simple implementation of the Observable pattern.
  7328. * 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.
  7329. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7330. * 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).
  7331. * 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.
  7332. */
  7333. var Observable = /** @class */ (function () {
  7334. /**
  7335. * Creates a new observable
  7336. * @param onObserverAdded defines a callback to call when a new observer is added
  7337. */
  7338. function Observable(onObserverAdded) {
  7339. this._observers = new Array();
  7340. this._eventState = new EventState(0);
  7341. if (onObserverAdded) {
  7342. this._onObserverAdded = onObserverAdded;
  7343. }
  7344. }
  7345. /**
  7346. * Create a new Observer with the specified callback
  7347. * @param callback the callback that will be executed for that Observer
  7348. * @param mask the mask used to filter observers
  7349. * @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.
  7350. * @param scope optional scope for the callback to be called from
  7351. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7352. * @returns the new observer created for the callback
  7353. */
  7354. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7355. if (mask === void 0) { mask = -1; }
  7356. if (insertFirst === void 0) { insertFirst = false; }
  7357. if (scope === void 0) { scope = null; }
  7358. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7359. if (!callback) {
  7360. return null;
  7361. }
  7362. var observer = new Observer(callback, mask, scope);
  7363. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7364. if (insertFirst) {
  7365. this._observers.unshift(observer);
  7366. }
  7367. else {
  7368. this._observers.push(observer);
  7369. }
  7370. if (this._onObserverAdded) {
  7371. this._onObserverAdded(observer);
  7372. }
  7373. return observer;
  7374. };
  7375. /**
  7376. * Remove an Observer from the Observable object
  7377. * @param observer the instance of the Observer to remove
  7378. * @returns false if it doesn't belong to this Observable
  7379. */
  7380. Observable.prototype.remove = function (observer) {
  7381. if (!observer) {
  7382. return false;
  7383. }
  7384. var index = this._observers.indexOf(observer);
  7385. if (index !== -1) {
  7386. this._observers.splice(index, 1);
  7387. return true;
  7388. }
  7389. return false;
  7390. };
  7391. /**
  7392. * Remove a callback from the Observable object
  7393. * @param callback the callback to remove
  7394. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7395. * @returns false if it doesn't belong to this Observable
  7396. */
  7397. Observable.prototype.removeCallback = function (callback, scope) {
  7398. for (var index = 0; index < this._observers.length; index++) {
  7399. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7400. this._observers.splice(index, 1);
  7401. return true;
  7402. }
  7403. }
  7404. return false;
  7405. };
  7406. Observable.prototype._deferUnregister = function (observer) {
  7407. var _this = this;
  7408. observer.unregisterOnNextCall = false;
  7409. observer._willBeUnregistered = true;
  7410. BABYLON.Tools.SetImmediate(function () {
  7411. _this.remove(observer);
  7412. });
  7413. };
  7414. /**
  7415. * Notify all Observers by calling their respective callback with the given data
  7416. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7417. * @param eventData defines the data to send to all observers
  7418. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7419. * @param target defines the original target of the state
  7420. * @param currentTarget defines the current target of the state
  7421. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7422. */
  7423. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7424. if (mask === void 0) { mask = -1; }
  7425. if (!this._observers.length) {
  7426. return true;
  7427. }
  7428. var state = this._eventState;
  7429. state.mask = mask;
  7430. state.target = target;
  7431. state.currentTarget = currentTarget;
  7432. state.skipNextObservers = false;
  7433. state.lastReturnValue = eventData;
  7434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7435. var obs = _a[_i];
  7436. if (obs._willBeUnregistered) {
  7437. continue;
  7438. }
  7439. if (obs.mask & mask) {
  7440. if (obs.scope) {
  7441. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7442. }
  7443. else {
  7444. state.lastReturnValue = obs.callback(eventData, state);
  7445. }
  7446. if (obs.unregisterOnNextCall) {
  7447. this._deferUnregister(obs);
  7448. }
  7449. }
  7450. if (state.skipNextObservers) {
  7451. return false;
  7452. }
  7453. }
  7454. return true;
  7455. };
  7456. /**
  7457. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7458. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7459. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7460. * and it is crucial that all callbacks will be executed.
  7461. * The order of the callbacks is kept, callbacks are not executed parallel.
  7462. *
  7463. * @param eventData The data to be sent to each callback
  7464. * @param mask is used to filter observers defaults to -1
  7465. * @param target defines the callback target (see EventState)
  7466. * @param currentTarget defines he current object in the bubbling phase
  7467. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7468. */
  7469. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7470. var _this = this;
  7471. if (mask === void 0) { mask = -1; }
  7472. // create an empty promise
  7473. var p = Promise.resolve(eventData);
  7474. // no observers? return this promise.
  7475. if (!this._observers.length) {
  7476. return p;
  7477. }
  7478. var state = this._eventState;
  7479. state.mask = mask;
  7480. state.target = target;
  7481. state.currentTarget = currentTarget;
  7482. state.skipNextObservers = false;
  7483. // execute one callback after another (not using Promise.all, the order is important)
  7484. this._observers.forEach(function (obs) {
  7485. if (state.skipNextObservers) {
  7486. return;
  7487. }
  7488. if (obs._willBeUnregistered) {
  7489. return;
  7490. }
  7491. if (obs.mask & mask) {
  7492. if (obs.scope) {
  7493. p = p.then(function (lastReturnedValue) {
  7494. state.lastReturnValue = lastReturnedValue;
  7495. return obs.callback.apply(obs.scope, [eventData, state]);
  7496. });
  7497. }
  7498. else {
  7499. p = p.then(function (lastReturnedValue) {
  7500. state.lastReturnValue = lastReturnedValue;
  7501. return obs.callback(eventData, state);
  7502. });
  7503. }
  7504. if (obs.unregisterOnNextCall) {
  7505. _this._deferUnregister(obs);
  7506. }
  7507. }
  7508. });
  7509. // return the eventData
  7510. return p.then(function () { return eventData; });
  7511. };
  7512. /**
  7513. * Notify a specific observer
  7514. * @param observer defines the observer to notify
  7515. * @param eventData defines the data to be sent to each callback
  7516. * @param mask is used to filter observers defaults to -1
  7517. */
  7518. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7519. if (mask === void 0) { mask = -1; }
  7520. var state = this._eventState;
  7521. state.mask = mask;
  7522. state.skipNextObservers = false;
  7523. observer.callback(eventData, state);
  7524. };
  7525. /**
  7526. * Gets a boolean indicating if the observable has at least one observer
  7527. * @returns true is the Observable has at least one Observer registered
  7528. */
  7529. Observable.prototype.hasObservers = function () {
  7530. return this._observers.length > 0;
  7531. };
  7532. /**
  7533. * Clear the list of observers
  7534. */
  7535. Observable.prototype.clear = function () {
  7536. this._observers = new Array();
  7537. this._onObserverAdded = null;
  7538. };
  7539. /**
  7540. * Clone the current observable
  7541. * @returns a new observable
  7542. */
  7543. Observable.prototype.clone = function () {
  7544. var result = new Observable();
  7545. result._observers = this._observers.slice(0);
  7546. return result;
  7547. };
  7548. /**
  7549. * Does this observable handles observer registered with a given mask
  7550. * @param mask defines the mask to be tested
  7551. * @return whether or not one observer registered with the given mask is handeled
  7552. **/
  7553. Observable.prototype.hasSpecificMask = function (mask) {
  7554. if (mask === void 0) { mask = -1; }
  7555. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7556. var obs = _a[_i];
  7557. if (obs.mask & mask || obs.mask === mask) {
  7558. return true;
  7559. }
  7560. }
  7561. return false;
  7562. };
  7563. return Observable;
  7564. }());
  7565. BABYLON.Observable = Observable;
  7566. })(BABYLON || (BABYLON = {}));
  7567. //# sourceMappingURL=babylon.observable.js.map
  7568. var BABYLON;
  7569. (function (BABYLON) {
  7570. var SmartArray = /** @class */ (function () {
  7571. function SmartArray(capacity) {
  7572. this.length = 0;
  7573. this.data = new Array(capacity);
  7574. this._id = SmartArray._GlobalId++;
  7575. }
  7576. SmartArray.prototype.push = function (value) {
  7577. this.data[this.length++] = value;
  7578. if (this.length > this.data.length) {
  7579. this.data.length *= 2;
  7580. }
  7581. };
  7582. SmartArray.prototype.forEach = function (func) {
  7583. for (var index = 0; index < this.length; index++) {
  7584. func(this.data[index]);
  7585. }
  7586. };
  7587. SmartArray.prototype.sort = function (compareFn) {
  7588. this.data.sort(compareFn);
  7589. };
  7590. SmartArray.prototype.reset = function () {
  7591. this.length = 0;
  7592. };
  7593. SmartArray.prototype.dispose = function () {
  7594. this.reset();
  7595. if (this.data) {
  7596. this.data.length = 0;
  7597. this.data = [];
  7598. }
  7599. };
  7600. SmartArray.prototype.concat = function (array) {
  7601. if (array.length === 0) {
  7602. return;
  7603. }
  7604. if (this.length + array.length > this.data.length) {
  7605. this.data.length = (this.length + array.length) * 2;
  7606. }
  7607. for (var index = 0; index < array.length; index++) {
  7608. this.data[this.length++] = (array.data || array)[index];
  7609. }
  7610. };
  7611. SmartArray.prototype.indexOf = function (value) {
  7612. var position = this.data.indexOf(value);
  7613. if (position >= this.length) {
  7614. return -1;
  7615. }
  7616. return position;
  7617. };
  7618. SmartArray.prototype.contains = function (value) {
  7619. return this.data.indexOf(value) !== -1;
  7620. };
  7621. // Statics
  7622. SmartArray._GlobalId = 0;
  7623. return SmartArray;
  7624. }());
  7625. BABYLON.SmartArray = SmartArray;
  7626. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7627. __extends(SmartArrayNoDuplicate, _super);
  7628. function SmartArrayNoDuplicate() {
  7629. var _this = _super !== null && _super.apply(this, arguments) || this;
  7630. _this._duplicateId = 0;
  7631. return _this;
  7632. }
  7633. SmartArrayNoDuplicate.prototype.push = function (value) {
  7634. _super.prototype.push.call(this, value);
  7635. if (!value.__smartArrayFlags) {
  7636. value.__smartArrayFlags = {};
  7637. }
  7638. value.__smartArrayFlags[this._id] = this._duplicateId;
  7639. };
  7640. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7641. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7642. return false;
  7643. }
  7644. this.push(value);
  7645. return true;
  7646. };
  7647. SmartArrayNoDuplicate.prototype.reset = function () {
  7648. _super.prototype.reset.call(this);
  7649. this._duplicateId++;
  7650. };
  7651. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7652. if (array.length === 0) {
  7653. return;
  7654. }
  7655. if (this.length + array.length > this.data.length) {
  7656. this.data.length = (this.length + array.length) * 2;
  7657. }
  7658. for (var index = 0; index < array.length; index++) {
  7659. var item = (array.data || array)[index];
  7660. this.pushNoDuplicate(item);
  7661. }
  7662. };
  7663. return SmartArrayNoDuplicate;
  7664. }(SmartArray));
  7665. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7666. })(BABYLON || (BABYLON = {}));
  7667. //# sourceMappingURL=babylon.smartArray.js.map
  7668. var BABYLON;
  7669. (function (BABYLON) {
  7670. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7671. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7672. var LoadFileError = /** @class */ (function (_super) {
  7673. __extends(LoadFileError, _super);
  7674. function LoadFileError(message, request) {
  7675. var _this = _super.call(this, message) || this;
  7676. _this.request = request;
  7677. _this.name = "LoadFileError";
  7678. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7679. return _this;
  7680. }
  7681. // Polyfill for Object.setPrototypeOf if necessary.
  7682. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7683. return LoadFileError;
  7684. }(Error));
  7685. BABYLON.LoadFileError = LoadFileError;
  7686. var RetryStrategy = /** @class */ (function () {
  7687. function RetryStrategy() {
  7688. }
  7689. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7690. if (maxRetries === void 0) { maxRetries = 3; }
  7691. if (baseInterval === void 0) { baseInterval = 500; }
  7692. return function (url, request, retryIndex) {
  7693. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7694. return -1;
  7695. }
  7696. return Math.pow(2, retryIndex) * baseInterval;
  7697. };
  7698. };
  7699. return RetryStrategy;
  7700. }());
  7701. BABYLON.RetryStrategy = RetryStrategy;
  7702. // Screenshots
  7703. var screenshotCanvas;
  7704. var cloneValue = function (source, destinationObject) {
  7705. if (!source)
  7706. return null;
  7707. if (source instanceof BABYLON.Mesh) {
  7708. return null;
  7709. }
  7710. if (source instanceof BABYLON.SubMesh) {
  7711. return source.clone(destinationObject);
  7712. }
  7713. else if (source.clone) {
  7714. return source.clone();
  7715. }
  7716. return null;
  7717. };
  7718. var Tools = /** @class */ (function () {
  7719. function Tools() {
  7720. }
  7721. /**
  7722. * Interpolates between a and b via alpha
  7723. * @param a The lower value (returned when alpha = 0)
  7724. * @param b The upper value (returned when alpha = 1)
  7725. * @param alpha The interpolation-factor
  7726. * @return The mixed value
  7727. */
  7728. Tools.Mix = function (a, b, alpha) {
  7729. return a * (1 - alpha) + b * alpha;
  7730. };
  7731. Tools.Instantiate = function (className) {
  7732. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7733. return Tools.RegisteredExternalClasses[className];
  7734. }
  7735. var arr = className.split(".");
  7736. var fn = (window || this);
  7737. for (var i = 0, len = arr.length; i < len; i++) {
  7738. fn = fn[arr[i]];
  7739. }
  7740. if (typeof fn !== "function") {
  7741. return null;
  7742. }
  7743. return fn;
  7744. };
  7745. /**
  7746. * Provides a slice function that will work even on IE
  7747. * @param data defines the array to slice
  7748. * @returns the new sliced array
  7749. */
  7750. Tools.Slice = function (data) {
  7751. if (data.slice) {
  7752. return data.slice();
  7753. }
  7754. return Array.prototype.slice.call(data);
  7755. };
  7756. Tools.SetImmediate = function (action) {
  7757. if (window.setImmediate) {
  7758. window.setImmediate(action);
  7759. }
  7760. else {
  7761. setTimeout(action, 1);
  7762. }
  7763. };
  7764. Tools.IsExponentOfTwo = function (value) {
  7765. var count = 1;
  7766. do {
  7767. count *= 2;
  7768. } while (count < value);
  7769. return count === value;
  7770. };
  7771. /**
  7772. * Find the next highest power of two.
  7773. * @param x Number to start search from.
  7774. * @return Next highest power of two.
  7775. */
  7776. Tools.CeilingPOT = function (x) {
  7777. x--;
  7778. x |= x >> 1;
  7779. x |= x >> 2;
  7780. x |= x >> 4;
  7781. x |= x >> 8;
  7782. x |= x >> 16;
  7783. x++;
  7784. return x;
  7785. };
  7786. /**
  7787. * Find the next lowest power of two.
  7788. * @param x Number to start search from.
  7789. * @return Next lowest power of two.
  7790. */
  7791. Tools.FloorPOT = function (x) {
  7792. x = x | (x >> 1);
  7793. x = x | (x >> 2);
  7794. x = x | (x >> 4);
  7795. x = x | (x >> 8);
  7796. x = x | (x >> 16);
  7797. return x - (x >> 1);
  7798. };
  7799. /**
  7800. * Find the nearest power of two.
  7801. * @param x Number to start search from.
  7802. * @return Next nearest power of two.
  7803. */
  7804. Tools.NearestPOT = function (x) {
  7805. var c = Tools.CeilingPOT(x);
  7806. var f = Tools.FloorPOT(x);
  7807. return (c - x) > (x - f) ? f : c;
  7808. };
  7809. Tools.GetExponentOfTwo = function (value, max, mode) {
  7810. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7811. var pot;
  7812. switch (mode) {
  7813. case BABYLON.Engine.SCALEMODE_FLOOR:
  7814. pot = Tools.FloorPOT(value);
  7815. break;
  7816. case BABYLON.Engine.SCALEMODE_NEAREST:
  7817. pot = Tools.NearestPOT(value);
  7818. break;
  7819. case BABYLON.Engine.SCALEMODE_CEILING:
  7820. default:
  7821. pot = Tools.CeilingPOT(value);
  7822. break;
  7823. }
  7824. return Math.min(pot, max);
  7825. };
  7826. Tools.GetFilename = function (path) {
  7827. var index = path.lastIndexOf("/");
  7828. if (index < 0)
  7829. return path;
  7830. return path.substring(index + 1);
  7831. };
  7832. /**
  7833. * Extracts the "folder" part of a path (everything before the filename).
  7834. * @param uri The URI to extract the info from
  7835. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7836. * @returns The "folder" part of the path
  7837. */
  7838. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7839. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7840. var index = uri.lastIndexOf("/");
  7841. if (index < 0) {
  7842. if (returnUnchangedIfNoSlash) {
  7843. return uri;
  7844. }
  7845. return "";
  7846. }
  7847. return uri.substring(0, index + 1);
  7848. };
  7849. Tools.GetDOMTextContent = function (element) {
  7850. var result = "";
  7851. var child = element.firstChild;
  7852. while (child) {
  7853. if (child.nodeType === 3) {
  7854. result += child.textContent;
  7855. }
  7856. child = child.nextSibling;
  7857. }
  7858. return result;
  7859. };
  7860. Tools.ToDegrees = function (angle) {
  7861. return angle * 180 / Math.PI;
  7862. };
  7863. Tools.ToRadians = function (angle) {
  7864. return angle * Math.PI / 180;
  7865. };
  7866. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7867. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7868. var output = "";
  7869. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7870. var i = 0;
  7871. var bytes = new Uint8Array(buffer);
  7872. while (i < bytes.length) {
  7873. chr1 = bytes[i++];
  7874. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7875. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7876. enc1 = chr1 >> 2;
  7877. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7878. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7879. enc4 = chr3 & 63;
  7880. if (isNaN(chr2)) {
  7881. enc3 = enc4 = 64;
  7882. }
  7883. else if (isNaN(chr3)) {
  7884. enc4 = 64;
  7885. }
  7886. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7887. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7888. }
  7889. return "data:image/png;base64," + output;
  7890. };
  7891. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7892. if (bias === void 0) { bias = null; }
  7893. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7894. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7895. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7896. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7897. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7898. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7899. }
  7900. if (bias) {
  7901. minimum.x -= minimum.x * bias.x + bias.y;
  7902. minimum.y -= minimum.y * bias.x + bias.y;
  7903. minimum.z -= minimum.z * bias.x + bias.y;
  7904. maximum.x += maximum.x * bias.x + bias.y;
  7905. maximum.y += maximum.y * bias.x + bias.y;
  7906. maximum.z += maximum.z * bias.x + bias.y;
  7907. }
  7908. return {
  7909. minimum: minimum,
  7910. maximum: maximum
  7911. };
  7912. };
  7913. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7914. if (bias === void 0) { bias = null; }
  7915. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7916. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7917. if (!stride) {
  7918. stride = 3;
  7919. }
  7920. for (var index = start; index < start + count; index++) {
  7921. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7922. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7923. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7924. }
  7925. if (bias) {
  7926. minimum.x -= minimum.x * bias.x + bias.y;
  7927. minimum.y -= minimum.y * bias.x + bias.y;
  7928. minimum.z -= minimum.z * bias.x + bias.y;
  7929. maximum.x += maximum.x * bias.x + bias.y;
  7930. maximum.y += maximum.y * bias.x + bias.y;
  7931. maximum.z += maximum.z * bias.x + bias.y;
  7932. }
  7933. return {
  7934. minimum: minimum,
  7935. maximum: maximum
  7936. };
  7937. };
  7938. Tools.Vector2ArrayFeeder = function (array) {
  7939. return function (index) {
  7940. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7941. var length = isFloatArray ? array.length / 2 : array.length;
  7942. if (index >= length) {
  7943. return null;
  7944. }
  7945. if (isFloatArray) {
  7946. var fa = array;
  7947. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7948. }
  7949. var a = array;
  7950. return a[index];
  7951. };
  7952. };
  7953. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7954. if (bias === void 0) { bias = null; }
  7955. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7956. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7957. var i = 0;
  7958. var cur = feeder(i++);
  7959. while (cur) {
  7960. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7961. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7962. cur = feeder(i++);
  7963. }
  7964. if (bias) {
  7965. minimum.x -= minimum.x * bias.x + bias.y;
  7966. minimum.y -= minimum.y * bias.x + bias.y;
  7967. maximum.x += maximum.x * bias.x + bias.y;
  7968. maximum.y += maximum.y * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7976. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7977. return null;
  7978. return Array.isArray(obj) ? obj : [obj];
  7979. };
  7980. // Misc.
  7981. Tools.GetPointerPrefix = function () {
  7982. var eventPrefix = "pointer";
  7983. // Check if pointer events are supported
  7984. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7985. eventPrefix = "mouse";
  7986. }
  7987. return eventPrefix;
  7988. };
  7989. /**
  7990. * @param func - the function to be called
  7991. * @param requester - the object that will request the next frame. Falls back to window.
  7992. */
  7993. Tools.QueueNewFrame = function (func, requester) {
  7994. if (!Tools.IsWindowObjectExist()) {
  7995. return setTimeout(func, 16);
  7996. }
  7997. if (!requester) {
  7998. requester = window;
  7999. }
  8000. if (requester.requestAnimationFrame) {
  8001. return requester.requestAnimationFrame(func);
  8002. }
  8003. else if (requester.msRequestAnimationFrame) {
  8004. return requester.msRequestAnimationFrame(func);
  8005. }
  8006. else if (requester.webkitRequestAnimationFrame) {
  8007. return requester.webkitRequestAnimationFrame(func);
  8008. }
  8009. else if (requester.mozRequestAnimationFrame) {
  8010. return requester.mozRequestAnimationFrame(func);
  8011. }
  8012. else if (requester.oRequestAnimationFrame) {
  8013. return requester.oRequestAnimationFrame(func);
  8014. }
  8015. else {
  8016. return window.setTimeout(func, 16);
  8017. }
  8018. };
  8019. Tools.RequestFullscreen = function (element) {
  8020. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8021. if (!requestFunction)
  8022. return;
  8023. requestFunction.call(element);
  8024. };
  8025. Tools.ExitFullscreen = function () {
  8026. if (document.exitFullscreen) {
  8027. document.exitFullscreen();
  8028. }
  8029. else if (document.mozCancelFullScreen) {
  8030. document.mozCancelFullScreen();
  8031. }
  8032. else if (document.webkitCancelFullScreen) {
  8033. document.webkitCancelFullScreen();
  8034. }
  8035. else if (document.msCancelFullScreen) {
  8036. document.msCancelFullScreen();
  8037. }
  8038. };
  8039. Tools.SetCorsBehavior = function (url, element) {
  8040. if (url && url.indexOf("data:") === 0) {
  8041. return;
  8042. }
  8043. if (Tools.CorsBehavior) {
  8044. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8045. element.crossOrigin = Tools.CorsBehavior;
  8046. }
  8047. else {
  8048. var result = Tools.CorsBehavior(url);
  8049. if (result) {
  8050. element.crossOrigin = result;
  8051. }
  8052. }
  8053. }
  8054. };
  8055. // External files
  8056. Tools.CleanUrl = function (url) {
  8057. url = url.replace(/#/mg, "%23");
  8058. return url;
  8059. };
  8060. Tools.LoadImage = function (url, onLoad, onError, database) {
  8061. if (url instanceof ArrayBuffer) {
  8062. url = Tools.EncodeArrayBufferTobase64(url);
  8063. }
  8064. url = Tools.CleanUrl(url);
  8065. url = Tools.PreprocessUrl(url);
  8066. var img = new Image();
  8067. Tools.SetCorsBehavior(url, img);
  8068. var loadHandler = function () {
  8069. img.removeEventListener("load", loadHandler);
  8070. img.removeEventListener("error", errorHandler);
  8071. onLoad(img);
  8072. };
  8073. var errorHandler = function (err) {
  8074. img.removeEventListener("load", loadHandler);
  8075. img.removeEventListener("error", errorHandler);
  8076. Tools.Error("Error while trying to load image: " + url);
  8077. if (onError) {
  8078. onError("Error while trying to load image: " + url, err);
  8079. }
  8080. };
  8081. img.addEventListener("load", loadHandler);
  8082. img.addEventListener("error", errorHandler);
  8083. var noIndexedDB = function () {
  8084. img.src = url;
  8085. };
  8086. var loadFromIndexedDB = function () {
  8087. if (database) {
  8088. database.loadImageFromDB(url, img);
  8089. }
  8090. };
  8091. //ANY database to do!
  8092. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8093. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8094. }
  8095. else {
  8096. if (url.indexOf("file:") !== -1) {
  8097. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8098. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8099. try {
  8100. var blobURL;
  8101. try {
  8102. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8103. }
  8104. catch (ex) {
  8105. // Chrome doesn't support oneTimeOnly parameter
  8106. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8107. }
  8108. img.src = blobURL;
  8109. }
  8110. catch (e) {
  8111. img.src = "";
  8112. }
  8113. return img;
  8114. }
  8115. }
  8116. noIndexedDB();
  8117. }
  8118. return img;
  8119. };
  8120. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8121. url = Tools.CleanUrl(url);
  8122. url = Tools.PreprocessUrl(url);
  8123. // If file and file input are set
  8124. if (url.indexOf("file:") !== -1) {
  8125. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8126. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8127. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8128. }
  8129. }
  8130. var loadUrl = Tools.BaseUrl + url;
  8131. var aborted = false;
  8132. var fileRequest = {
  8133. onCompleteObservable: new BABYLON.Observable(),
  8134. abort: function () { return aborted = true; },
  8135. };
  8136. var requestFile = function () {
  8137. var request = new XMLHttpRequest();
  8138. var retryHandle = null;
  8139. fileRequest.abort = function () {
  8140. aborted = true;
  8141. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8142. request.abort();
  8143. }
  8144. if (retryHandle !== null) {
  8145. clearTimeout(retryHandle);
  8146. retryHandle = null;
  8147. }
  8148. };
  8149. var retryLoop = function (retryIndex) {
  8150. request.open('GET', loadUrl, true);
  8151. if (useArrayBuffer) {
  8152. request.responseType = "arraybuffer";
  8153. }
  8154. if (onProgress) {
  8155. request.addEventListener("progress", onProgress);
  8156. }
  8157. var onLoadEnd = function () {
  8158. request.removeEventListener("loadend", onLoadEnd);
  8159. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8160. fileRequest.onCompleteObservable.clear();
  8161. };
  8162. request.addEventListener("loadend", onLoadEnd);
  8163. var onReadyStateChange = function () {
  8164. if (aborted) {
  8165. return;
  8166. }
  8167. // In case of undefined state in some browsers.
  8168. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8169. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8170. request.removeEventListener("readystatechange", onReadyStateChange);
  8171. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8172. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8173. return;
  8174. }
  8175. var retryStrategy = Tools.DefaultRetryStrategy;
  8176. if (retryStrategy) {
  8177. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8178. if (waitTime !== -1) {
  8179. // Prevent the request from completing for retry.
  8180. request.removeEventListener("loadend", onLoadEnd);
  8181. request = new XMLHttpRequest();
  8182. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8183. return;
  8184. }
  8185. }
  8186. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8187. if (onError) {
  8188. onError(request, e);
  8189. }
  8190. else {
  8191. throw e;
  8192. }
  8193. }
  8194. };
  8195. request.addEventListener("readystatechange", onReadyStateChange);
  8196. request.send();
  8197. };
  8198. retryLoop(0);
  8199. };
  8200. // Caching all files
  8201. if (database && database.enableSceneOffline) {
  8202. var noIndexedDB_1 = function () {
  8203. if (!aborted) {
  8204. requestFile();
  8205. }
  8206. };
  8207. var loadFromIndexedDB = function () {
  8208. // TODO: database needs to support aborting and should return a IFileRequest
  8209. if (aborted) {
  8210. return;
  8211. }
  8212. if (database) {
  8213. database.loadFileFromDB(url, function (data) {
  8214. if (!aborted) {
  8215. onSuccess(data);
  8216. }
  8217. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8218. }, onProgress ? function (event) {
  8219. if (!aborted) {
  8220. onProgress(event);
  8221. }
  8222. } : undefined, noIndexedDB_1, useArrayBuffer);
  8223. }
  8224. };
  8225. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8226. }
  8227. else {
  8228. requestFile();
  8229. }
  8230. return fileRequest;
  8231. };
  8232. /**
  8233. * Load a script (identified by an url). When the url returns, the
  8234. * content of this file is added into a new script element, attached to the DOM (body element)
  8235. */
  8236. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8237. var head = document.getElementsByTagName('head')[0];
  8238. var script = document.createElement('script');
  8239. script.type = 'text/javascript';
  8240. script.src = scriptUrl;
  8241. script.onload = function () {
  8242. if (onSuccess) {
  8243. onSuccess();
  8244. }
  8245. };
  8246. script.onerror = function (e) {
  8247. if (onError) {
  8248. onError("Unable to load script", e);
  8249. }
  8250. };
  8251. head.appendChild(script);
  8252. };
  8253. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8254. var reader = new FileReader();
  8255. var request = {
  8256. onCompleteObservable: new BABYLON.Observable(),
  8257. abort: function () { return reader.abort(); },
  8258. };
  8259. reader.onloadend = function (e) {
  8260. request.onCompleteObservable.notifyObservers(request);
  8261. };
  8262. reader.onload = function (e) {
  8263. //target doesn't have result from ts 1.3
  8264. callback(e.target['result']);
  8265. };
  8266. reader.onprogress = progressCallback;
  8267. reader.readAsDataURL(fileToLoad);
  8268. return request;
  8269. };
  8270. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8271. var reader = new FileReader();
  8272. var request = {
  8273. onCompleteObservable: new BABYLON.Observable(),
  8274. abort: function () { return reader.abort(); },
  8275. };
  8276. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8277. reader.onerror = function (e) {
  8278. Tools.Log("Error while reading file: " + fileToLoad.name);
  8279. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8280. };
  8281. reader.onload = function (e) {
  8282. //target doesn't have result from ts 1.3
  8283. callback(e.target['result']);
  8284. };
  8285. if (progressCallBack) {
  8286. reader.onprogress = progressCallBack;
  8287. }
  8288. if (!useArrayBuffer) {
  8289. // Asynchronous read
  8290. reader.readAsText(fileToLoad);
  8291. }
  8292. else {
  8293. reader.readAsArrayBuffer(fileToLoad);
  8294. }
  8295. return request;
  8296. };
  8297. //returns a downloadable url to a file content.
  8298. Tools.FileAsURL = function (content) {
  8299. var fileBlob = new Blob([content]);
  8300. var url = window.URL || window.webkitURL;
  8301. var link = url.createObjectURL(fileBlob);
  8302. return link;
  8303. };
  8304. // Misc.
  8305. Tools.Format = function (value, decimals) {
  8306. if (decimals === void 0) { decimals = 2; }
  8307. return value.toFixed(decimals);
  8308. };
  8309. Tools.CheckExtends = function (v, min, max) {
  8310. if (v.x < min.x)
  8311. min.x = v.x;
  8312. if (v.y < min.y)
  8313. min.y = v.y;
  8314. if (v.z < min.z)
  8315. min.z = v.z;
  8316. if (v.x > max.x)
  8317. max.x = v.x;
  8318. if (v.y > max.y)
  8319. max.y = v.y;
  8320. if (v.z > max.z)
  8321. max.z = v.z;
  8322. };
  8323. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8324. for (var prop in source) {
  8325. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8326. continue;
  8327. }
  8328. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8329. continue;
  8330. }
  8331. var sourceValue = source[prop];
  8332. var typeOfSourceValue = typeof sourceValue;
  8333. if (typeOfSourceValue === "function") {
  8334. continue;
  8335. }
  8336. if (typeOfSourceValue === "object") {
  8337. if (sourceValue instanceof Array) {
  8338. destination[prop] = [];
  8339. if (sourceValue.length > 0) {
  8340. if (typeof sourceValue[0] == "object") {
  8341. for (var index = 0; index < sourceValue.length; index++) {
  8342. var clonedValue = cloneValue(sourceValue[index], destination);
  8343. if (destination[prop].indexOf(clonedValue) === -1) {
  8344. destination[prop].push(clonedValue);
  8345. }
  8346. }
  8347. }
  8348. else {
  8349. destination[prop] = sourceValue.slice(0);
  8350. }
  8351. }
  8352. }
  8353. else {
  8354. destination[prop] = cloneValue(sourceValue, destination);
  8355. }
  8356. }
  8357. else {
  8358. destination[prop] = sourceValue;
  8359. }
  8360. }
  8361. };
  8362. Tools.IsEmpty = function (obj) {
  8363. for (var i in obj) {
  8364. if (obj.hasOwnProperty(i)) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. Tools.RegisterTopRootEvents = function (events) {
  8371. for (var index = 0; index < events.length; index++) {
  8372. var event = events[index];
  8373. window.addEventListener(event.name, event.handler, false);
  8374. try {
  8375. if (window.parent) {
  8376. window.parent.addEventListener(event.name, event.handler, false);
  8377. }
  8378. }
  8379. catch (e) {
  8380. // Silently fails...
  8381. }
  8382. }
  8383. };
  8384. Tools.UnregisterTopRootEvents = function (events) {
  8385. for (var index = 0; index < events.length; index++) {
  8386. var event = events[index];
  8387. window.removeEventListener(event.name, event.handler);
  8388. try {
  8389. if (window.parent) {
  8390. window.parent.removeEventListener(event.name, event.handler);
  8391. }
  8392. }
  8393. catch (e) {
  8394. // Silently fails...
  8395. }
  8396. }
  8397. };
  8398. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8399. if (mimeType === void 0) { mimeType = "image/png"; }
  8400. // Read the contents of the framebuffer
  8401. var numberOfChannelsByLine = width * 4;
  8402. var halfHeight = height / 2;
  8403. //Reading datas from WebGL
  8404. var data = engine.readPixels(0, 0, width, height);
  8405. //To flip image on Y axis.
  8406. for (var i = 0; i < halfHeight; i++) {
  8407. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8408. var currentCell = j + i * numberOfChannelsByLine;
  8409. var targetLine = height - i - 1;
  8410. var targetCell = j + targetLine * numberOfChannelsByLine;
  8411. var temp = data[currentCell];
  8412. data[currentCell] = data[targetCell];
  8413. data[targetCell] = temp;
  8414. }
  8415. }
  8416. // Create a 2D canvas to store the result
  8417. if (!screenshotCanvas) {
  8418. screenshotCanvas = document.createElement('canvas');
  8419. }
  8420. screenshotCanvas.width = width;
  8421. screenshotCanvas.height = height;
  8422. var context = screenshotCanvas.getContext('2d');
  8423. if (context) {
  8424. // Copy the pixels to a 2D canvas
  8425. var imageData = context.createImageData(width, height);
  8426. var castData = (imageData.data);
  8427. castData.set(data);
  8428. context.putImageData(imageData, 0, 0);
  8429. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8430. }
  8431. };
  8432. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8433. if (mimeType === void 0) { mimeType = "image/png"; }
  8434. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8435. if (successCallback) {
  8436. successCallback(base64Image);
  8437. }
  8438. else {
  8439. // We need HTMLCanvasElement.toBlob for HD screenshots
  8440. if (!screenshotCanvas.toBlob) {
  8441. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8442. screenshotCanvas.toBlob = function (callback, type, quality) {
  8443. var _this = this;
  8444. setTimeout(function () {
  8445. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8446. for (var i = 0; i < len; i++) {
  8447. arr[i] = binStr.charCodeAt(i);
  8448. }
  8449. callback(new Blob([arr], { type: type || 'image/png' }));
  8450. });
  8451. };
  8452. }
  8453. screenshotCanvas.toBlob(function (blob) {
  8454. var url = URL.createObjectURL(blob);
  8455. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8456. if (("download" in document.createElement("a"))) {
  8457. var a = window.document.createElement("a");
  8458. a.href = url;
  8459. if (fileName) {
  8460. a.setAttribute("download", fileName);
  8461. }
  8462. else {
  8463. var date = new Date();
  8464. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8465. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8466. }
  8467. window.document.body.appendChild(a);
  8468. a.addEventListener("click", function () {
  8469. if (a.parentElement) {
  8470. a.parentElement.removeChild(a);
  8471. }
  8472. });
  8473. a.click();
  8474. }
  8475. else {
  8476. var newWindow = window.open("");
  8477. if (!newWindow)
  8478. return;
  8479. var img = newWindow.document.createElement("img");
  8480. img.onload = function () {
  8481. // no longer need to read the blob so it's revoked
  8482. URL.revokeObjectURL(url);
  8483. };
  8484. img.src = url;
  8485. newWindow.document.body.appendChild(img);
  8486. }
  8487. });
  8488. }
  8489. };
  8490. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8491. if (mimeType === void 0) { mimeType = "image/png"; }
  8492. var width;
  8493. var height;
  8494. // If a precision value is specified
  8495. if (size.precision) {
  8496. width = Math.round(engine.getRenderWidth() * size.precision);
  8497. height = Math.round(width / engine.getAspectRatio(camera));
  8498. }
  8499. else if (size.width && size.height) {
  8500. width = size.width;
  8501. height = size.height;
  8502. }
  8503. else if (size.width && !size.height) {
  8504. width = size.width;
  8505. height = Math.round(width / engine.getAspectRatio(camera));
  8506. }
  8507. else if (size.height && !size.width) {
  8508. height = size.height;
  8509. width = Math.round(height * engine.getAspectRatio(camera));
  8510. }
  8511. else if (!isNaN(size)) {
  8512. height = size;
  8513. width = size;
  8514. }
  8515. else {
  8516. Tools.Error("Invalid 'size' parameter !");
  8517. return;
  8518. }
  8519. if (!screenshotCanvas) {
  8520. screenshotCanvas = document.createElement('canvas');
  8521. }
  8522. screenshotCanvas.width = width;
  8523. screenshotCanvas.height = height;
  8524. var renderContext = screenshotCanvas.getContext("2d");
  8525. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8526. var newWidth = width;
  8527. var newHeight = newWidth / ratio;
  8528. if (newHeight > height) {
  8529. newHeight = height;
  8530. newWidth = newHeight * ratio;
  8531. }
  8532. var offsetX = Math.max(0, width - newWidth) / 2;
  8533. var offsetY = Math.max(0, height - newHeight) / 2;
  8534. var renderingCanvas = engine.getRenderingCanvas();
  8535. if (renderContext && renderingCanvas) {
  8536. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8537. }
  8538. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8539. };
  8540. /**
  8541. * Generates an image screenshot from the specified camera.
  8542. *
  8543. * @param engine The engine to use for rendering
  8544. * @param camera The camera to use for rendering
  8545. * @param size This parameter can be set to a single number or to an object with the
  8546. * following (optional) properties: precision, width, height. If a single number is passed,
  8547. * it will be used for both width and height. If an object is passed, the screenshot size
  8548. * will be derived from the parameters. The precision property is a multiplier allowing
  8549. * rendering at a higher or lower resolution.
  8550. * @param successCallback The callback receives a single parameter which contains the
  8551. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8552. * src parameter of an <img> to display it.
  8553. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8554. * Check your browser for supported MIME types.
  8555. * @param samples Texture samples (default: 1)
  8556. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8557. * @param fileName A name for for the downloaded file.
  8558. * @constructor
  8559. */
  8560. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8561. if (mimeType === void 0) { mimeType = "image/png"; }
  8562. if (samples === void 0) { samples = 1; }
  8563. if (antialiasing === void 0) { antialiasing = false; }
  8564. var width;
  8565. var height;
  8566. //If a precision value is specified
  8567. if (size.precision) {
  8568. width = Math.round(engine.getRenderWidth() * size.precision);
  8569. height = Math.round(width / engine.getAspectRatio(camera));
  8570. size = { width: width, height: height };
  8571. }
  8572. else if (size.width && size.height) {
  8573. width = size.width;
  8574. height = size.height;
  8575. }
  8576. else if (size.width && !size.height) {
  8577. width = size.width;
  8578. height = Math.round(width / engine.getAspectRatio(camera));
  8579. size = { width: width, height: height };
  8580. }
  8581. else if (size.height && !size.width) {
  8582. height = size.height;
  8583. width = Math.round(height * engine.getAspectRatio(camera));
  8584. size = { width: width, height: height };
  8585. }
  8586. else if (!isNaN(size)) {
  8587. height = size;
  8588. width = size;
  8589. }
  8590. else {
  8591. Tools.Error("Invalid 'size' parameter !");
  8592. return;
  8593. }
  8594. var scene = camera.getScene();
  8595. var previousCamera = null;
  8596. if (scene.activeCamera !== camera) {
  8597. previousCamera = scene.activeCamera;
  8598. scene.activeCamera = camera;
  8599. }
  8600. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8601. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8602. texture.renderList = null;
  8603. texture.samples = samples;
  8604. if (antialiasing) {
  8605. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8606. }
  8607. texture.onAfterRenderObservable.add(function () {
  8608. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8609. });
  8610. scene.incrementRenderId();
  8611. scene.resetCachedMaterial();
  8612. texture.render(true);
  8613. texture.dispose();
  8614. if (previousCamera) {
  8615. scene.activeCamera = previousCamera;
  8616. }
  8617. camera.getProjectionMatrix(true); // Force cache refresh;
  8618. };
  8619. // XHR response validator for local file scenario
  8620. Tools.ValidateXHRData = function (xhr, dataType) {
  8621. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8622. if (dataType === void 0) { dataType = 7; }
  8623. try {
  8624. if (dataType & 1) {
  8625. if (xhr.responseText && xhr.responseText.length > 0) {
  8626. return true;
  8627. }
  8628. else if (dataType === 1) {
  8629. return false;
  8630. }
  8631. }
  8632. if (dataType & 2) {
  8633. // Check header width and height since there is no "TGA" magic number
  8634. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8635. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8636. return true;
  8637. }
  8638. else if (dataType === 2) {
  8639. return false;
  8640. }
  8641. }
  8642. if (dataType & 4) {
  8643. // Check for the "DDS" magic number
  8644. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8645. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8646. return true;
  8647. }
  8648. else {
  8649. return false;
  8650. }
  8651. }
  8652. }
  8653. catch (e) {
  8654. // Global protection
  8655. }
  8656. return false;
  8657. };
  8658. /**
  8659. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8660. * Be aware Math.random() could cause collisions, but:
  8661. * "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"
  8662. */
  8663. Tools.RandomId = function () {
  8664. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8665. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8666. return v.toString(16);
  8667. });
  8668. };
  8669. /**
  8670. * Test if the given uri is a base64 string.
  8671. * @param uri The uri to test
  8672. * @return True if the uri is a base64 string or false otherwise.
  8673. */
  8674. Tools.IsBase64 = function (uri) {
  8675. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8676. };
  8677. /**
  8678. * Decode the given base64 uri.
  8679. * @param uri The uri to decode
  8680. * @return The decoded base64 data.
  8681. */
  8682. Tools.DecodeBase64 = function (uri) {
  8683. var decodedString = atob(uri.split(",")[1]);
  8684. var bufferLength = decodedString.length;
  8685. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8686. for (var i = 0; i < bufferLength; i++) {
  8687. bufferView[i] = decodedString.charCodeAt(i);
  8688. }
  8689. return bufferView.buffer;
  8690. };
  8691. Object.defineProperty(Tools, "NoneLogLevel", {
  8692. get: function () {
  8693. return Tools._NoneLogLevel;
  8694. },
  8695. enumerable: true,
  8696. configurable: true
  8697. });
  8698. Object.defineProperty(Tools, "MessageLogLevel", {
  8699. get: function () {
  8700. return Tools._MessageLogLevel;
  8701. },
  8702. enumerable: true,
  8703. configurable: true
  8704. });
  8705. Object.defineProperty(Tools, "WarningLogLevel", {
  8706. get: function () {
  8707. return Tools._WarningLogLevel;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Object.defineProperty(Tools, "ErrorLogLevel", {
  8713. get: function () {
  8714. return Tools._ErrorLogLevel;
  8715. },
  8716. enumerable: true,
  8717. configurable: true
  8718. });
  8719. Object.defineProperty(Tools, "AllLogLevel", {
  8720. get: function () {
  8721. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8722. },
  8723. enumerable: true,
  8724. configurable: true
  8725. });
  8726. Tools._AddLogEntry = function (entry) {
  8727. Tools._LogCache = entry + Tools._LogCache;
  8728. if (Tools.OnNewCacheEntry) {
  8729. Tools.OnNewCacheEntry(entry);
  8730. }
  8731. };
  8732. Tools._FormatMessage = function (message) {
  8733. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8734. var date = new Date();
  8735. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8736. };
  8737. Tools._LogDisabled = function (message) {
  8738. // nothing to do
  8739. };
  8740. Tools._LogEnabled = function (message) {
  8741. var formattedMessage = Tools._FormatMessage(message);
  8742. console.log("BJS - " + formattedMessage);
  8743. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8744. Tools._AddLogEntry(entry);
  8745. };
  8746. Tools._WarnDisabled = function (message) {
  8747. // nothing to do
  8748. };
  8749. Tools._WarnEnabled = function (message) {
  8750. var formattedMessage = Tools._FormatMessage(message);
  8751. console.warn("BJS - " + formattedMessage);
  8752. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8753. Tools._AddLogEntry(entry);
  8754. };
  8755. Tools._ErrorDisabled = function (message) {
  8756. // nothing to do
  8757. };
  8758. Tools._ErrorEnabled = function (message) {
  8759. Tools.errorsCount++;
  8760. var formattedMessage = Tools._FormatMessage(message);
  8761. console.error("BJS - " + formattedMessage);
  8762. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8763. Tools._AddLogEntry(entry);
  8764. };
  8765. Object.defineProperty(Tools, "LogCache", {
  8766. get: function () {
  8767. return Tools._LogCache;
  8768. },
  8769. enumerable: true,
  8770. configurable: true
  8771. });
  8772. Tools.ClearLogCache = function () {
  8773. Tools._LogCache = "";
  8774. Tools.errorsCount = 0;
  8775. };
  8776. Object.defineProperty(Tools, "LogLevels", {
  8777. set: function (level) {
  8778. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8779. Tools.Log = Tools._LogEnabled;
  8780. }
  8781. else {
  8782. Tools.Log = Tools._LogDisabled;
  8783. }
  8784. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8785. Tools.Warn = Tools._WarnEnabled;
  8786. }
  8787. else {
  8788. Tools.Warn = Tools._WarnDisabled;
  8789. }
  8790. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8791. Tools.Error = Tools._ErrorEnabled;
  8792. }
  8793. else {
  8794. Tools.Error = Tools._ErrorDisabled;
  8795. }
  8796. },
  8797. enumerable: true,
  8798. configurable: true
  8799. });
  8800. Tools.IsWindowObjectExist = function () {
  8801. return (typeof window) !== "undefined";
  8802. };
  8803. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8804. get: function () {
  8805. return Tools._PerformanceNoneLogLevel;
  8806. },
  8807. enumerable: true,
  8808. configurable: true
  8809. });
  8810. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8811. get: function () {
  8812. return Tools._PerformanceUserMarkLogLevel;
  8813. },
  8814. enumerable: true,
  8815. configurable: true
  8816. });
  8817. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8818. get: function () {
  8819. return Tools._PerformanceConsoleLogLevel;
  8820. },
  8821. enumerable: true,
  8822. configurable: true
  8823. });
  8824. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8825. set: function (level) {
  8826. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8827. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8828. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8829. return;
  8830. }
  8831. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8832. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8833. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8834. return;
  8835. }
  8836. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8837. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8838. },
  8839. enumerable: true,
  8840. configurable: true
  8841. });
  8842. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8843. };
  8844. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8845. };
  8846. Tools._StartUserMark = function (counterName, condition) {
  8847. if (condition === void 0) { condition = true; }
  8848. if (!Tools._performance) {
  8849. if (!Tools.IsWindowObjectExist()) {
  8850. return;
  8851. }
  8852. Tools._performance = window.performance;
  8853. }
  8854. if (!condition || !Tools._performance.mark) {
  8855. return;
  8856. }
  8857. Tools._performance.mark(counterName + "-Begin");
  8858. };
  8859. Tools._EndUserMark = function (counterName, condition) {
  8860. if (condition === void 0) { condition = true; }
  8861. if (!condition || !Tools._performance.mark) {
  8862. return;
  8863. }
  8864. Tools._performance.mark(counterName + "-End");
  8865. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8866. };
  8867. Tools._StartPerformanceConsole = function (counterName, condition) {
  8868. if (condition === void 0) { condition = true; }
  8869. if (!condition) {
  8870. return;
  8871. }
  8872. Tools._StartUserMark(counterName, condition);
  8873. if (console.time) {
  8874. console.time(counterName);
  8875. }
  8876. };
  8877. Tools._EndPerformanceConsole = function (counterName, condition) {
  8878. if (condition === void 0) { condition = true; }
  8879. if (!condition) {
  8880. return;
  8881. }
  8882. Tools._EndUserMark(counterName, condition);
  8883. if (console.time) {
  8884. console.timeEnd(counterName);
  8885. }
  8886. };
  8887. Object.defineProperty(Tools, "Now", {
  8888. get: function () {
  8889. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8890. return window.performance.now();
  8891. }
  8892. return new Date().getTime();
  8893. },
  8894. enumerable: true,
  8895. configurable: true
  8896. });
  8897. /**
  8898. * This method will return the name of the class used to create the instance of the given object.
  8899. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8900. * @param object the object to get the class name from
  8901. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8902. */
  8903. Tools.GetClassName = function (object, isType) {
  8904. if (isType === void 0) { isType = false; }
  8905. var name = null;
  8906. if (!isType && object.getClassName) {
  8907. name = object.getClassName();
  8908. }
  8909. else {
  8910. if (object instanceof Object) {
  8911. var classObj = isType ? object : Object.getPrototypeOf(object);
  8912. name = classObj.constructor["__bjsclassName__"];
  8913. }
  8914. if (!name) {
  8915. name = typeof object;
  8916. }
  8917. }
  8918. return name;
  8919. };
  8920. Tools.First = function (array, predicate) {
  8921. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8922. var el = array_1[_i];
  8923. if (predicate(el)) {
  8924. return el;
  8925. }
  8926. }
  8927. return null;
  8928. };
  8929. /**
  8930. * This method will return the name of the full name of the class, including its owning module (if any).
  8931. * 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).
  8932. * @param object the object to get the class name from
  8933. * @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.
  8934. */
  8935. Tools.getFullClassName = function (object, isType) {
  8936. if (isType === void 0) { isType = false; }
  8937. var className = null;
  8938. var moduleName = null;
  8939. if (!isType && object.getClassName) {
  8940. className = object.getClassName();
  8941. }
  8942. else {
  8943. if (object instanceof Object) {
  8944. var classObj = isType ? object : Object.getPrototypeOf(object);
  8945. className = classObj.constructor["__bjsclassName__"];
  8946. moduleName = classObj.constructor["__bjsmoduleName__"];
  8947. }
  8948. if (!className) {
  8949. className = typeof object;
  8950. }
  8951. }
  8952. if (!className) {
  8953. return null;
  8954. }
  8955. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8956. };
  8957. /**
  8958. * 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.
  8959. * @param array
  8960. */
  8961. Tools.arrayOrStringFeeder = function (array) {
  8962. return function (index) {
  8963. if (index >= array.length) {
  8964. return null;
  8965. }
  8966. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8967. if (val && val.getHashCode) {
  8968. val = val.getHashCode();
  8969. }
  8970. if (typeof val === "string") {
  8971. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8972. }
  8973. return val;
  8974. };
  8975. };
  8976. /**
  8977. * Compute the hashCode of a stream of number
  8978. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8979. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8980. * @return the hash code computed
  8981. */
  8982. Tools.hashCodeFromStream = function (feeder) {
  8983. // Based from here: http://stackoverflow.com/a/7616484/802124
  8984. var hash = 0;
  8985. var index = 0;
  8986. var chr = feeder(index++);
  8987. while (chr != null) {
  8988. hash = ((hash << 5) - hash) + chr;
  8989. hash |= 0; // Convert to 32bit integer
  8990. chr = feeder(index++);
  8991. }
  8992. return hash;
  8993. };
  8994. /**
  8995. * Returns a promise that resolves after the given amount of time.
  8996. * @param delay Number of milliseconds to delay
  8997. * @returns Promise that resolves after the given amount of time
  8998. */
  8999. Tools.DelayAsync = function (delay) {
  9000. return new Promise(function (resolve) {
  9001. setTimeout(function () {
  9002. resolve();
  9003. }, delay);
  9004. });
  9005. };
  9006. Tools.BaseUrl = "";
  9007. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9008. /**
  9009. * Default behaviour for cors in the application.
  9010. * It can be a string if the expected behavior is identical in the entire app.
  9011. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9012. */
  9013. Tools.CorsBehavior = "anonymous";
  9014. Tools.UseFallbackTexture = true;
  9015. /**
  9016. * Use this object to register external classes like custom textures or material
  9017. * to allow the laoders to instantiate them
  9018. */
  9019. Tools.RegisteredExternalClasses = {};
  9020. // Used in case of a texture loading problem
  9021. 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";
  9022. Tools.PreprocessUrl = function (url) {
  9023. return url;
  9024. };
  9025. // Logs
  9026. Tools._NoneLogLevel = 0;
  9027. Tools._MessageLogLevel = 1;
  9028. Tools._WarningLogLevel = 2;
  9029. Tools._ErrorLogLevel = 4;
  9030. Tools._LogCache = "";
  9031. Tools.errorsCount = 0;
  9032. Tools.Log = Tools._LogEnabled;
  9033. Tools.Warn = Tools._WarnEnabled;
  9034. Tools.Error = Tools._ErrorEnabled;
  9035. // Performances
  9036. Tools._PerformanceNoneLogLevel = 0;
  9037. Tools._PerformanceUserMarkLogLevel = 1;
  9038. Tools._PerformanceConsoleLogLevel = 2;
  9039. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9040. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9041. return Tools;
  9042. }());
  9043. BABYLON.Tools = Tools;
  9044. /**
  9045. * This class is used to track a performance counter which is number based.
  9046. * The user has access to many properties which give statistics of different nature
  9047. *
  9048. * The implementer can track two kinds of Performance Counter: time and count
  9049. * 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.
  9050. * 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.
  9051. */
  9052. var PerfCounter = /** @class */ (function () {
  9053. function PerfCounter() {
  9054. this._startMonitoringTime = 0;
  9055. this._min = 0;
  9056. this._max = 0;
  9057. this._average = 0;
  9058. this._lastSecAverage = 0;
  9059. this._current = 0;
  9060. this._totalValueCount = 0;
  9061. this._totalAccumulated = 0;
  9062. this._lastSecAccumulated = 0;
  9063. this._lastSecTime = 0;
  9064. this._lastSecValueCount = 0;
  9065. }
  9066. Object.defineProperty(PerfCounter.prototype, "min", {
  9067. /**
  9068. * Returns the smallest value ever
  9069. */
  9070. get: function () {
  9071. return this._min;
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(PerfCounter.prototype, "max", {
  9077. /**
  9078. * Returns the biggest value ever
  9079. */
  9080. get: function () {
  9081. return this._max;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(PerfCounter.prototype, "average", {
  9087. /**
  9088. * Returns the average value since the performance counter is running
  9089. */
  9090. get: function () {
  9091. return this._average;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9097. /**
  9098. * Returns the average value of the last second the counter was monitored
  9099. */
  9100. get: function () {
  9101. return this._lastSecAverage;
  9102. },
  9103. enumerable: true,
  9104. configurable: true
  9105. });
  9106. Object.defineProperty(PerfCounter.prototype, "current", {
  9107. /**
  9108. * Returns the current value
  9109. */
  9110. get: function () {
  9111. return this._current;
  9112. },
  9113. enumerable: true,
  9114. configurable: true
  9115. });
  9116. Object.defineProperty(PerfCounter.prototype, "total", {
  9117. get: function () {
  9118. return this._totalAccumulated;
  9119. },
  9120. enumerable: true,
  9121. configurable: true
  9122. });
  9123. Object.defineProperty(PerfCounter.prototype, "count", {
  9124. get: function () {
  9125. return this._totalValueCount;
  9126. },
  9127. enumerable: true,
  9128. configurable: true
  9129. });
  9130. /**
  9131. * Call this method to start monitoring a new frame.
  9132. * 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.
  9133. */
  9134. PerfCounter.prototype.fetchNewFrame = function () {
  9135. this._totalValueCount++;
  9136. this._current = 0;
  9137. this._lastSecValueCount++;
  9138. };
  9139. /**
  9140. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9141. * @param newCount the count value to add to the monitored count
  9142. * @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.
  9143. */
  9144. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9145. if (!PerfCounter.Enabled) {
  9146. return;
  9147. }
  9148. this._current += newCount;
  9149. if (fetchResult) {
  9150. this._fetchResult();
  9151. }
  9152. };
  9153. /**
  9154. * Start monitoring this performance counter
  9155. */
  9156. PerfCounter.prototype.beginMonitoring = function () {
  9157. if (!PerfCounter.Enabled) {
  9158. return;
  9159. }
  9160. this._startMonitoringTime = Tools.Now;
  9161. };
  9162. /**
  9163. * Compute the time lapsed since the previous beginMonitoring() call.
  9164. * @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
  9165. */
  9166. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9167. if (newFrame === void 0) { newFrame = true; }
  9168. if (!PerfCounter.Enabled) {
  9169. return;
  9170. }
  9171. if (newFrame) {
  9172. this.fetchNewFrame();
  9173. }
  9174. var currentTime = Tools.Now;
  9175. this._current = currentTime - this._startMonitoringTime;
  9176. if (newFrame) {
  9177. this._fetchResult();
  9178. }
  9179. };
  9180. PerfCounter.prototype._fetchResult = function () {
  9181. this._totalAccumulated += this._current;
  9182. this._lastSecAccumulated += this._current;
  9183. // Min/Max update
  9184. this._min = Math.min(this._min, this._current);
  9185. this._max = Math.max(this._max, this._current);
  9186. this._average = this._totalAccumulated / this._totalValueCount;
  9187. // Reset last sec?
  9188. var now = Tools.Now;
  9189. if ((now - this._lastSecTime) > 1000) {
  9190. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9191. this._lastSecTime = now;
  9192. this._lastSecAccumulated = 0;
  9193. this._lastSecValueCount = 0;
  9194. }
  9195. };
  9196. PerfCounter.Enabled = true;
  9197. return PerfCounter;
  9198. }());
  9199. BABYLON.PerfCounter = PerfCounter;
  9200. /**
  9201. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9202. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9203. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9204. * @param name The name of the class, case should be preserved
  9205. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9206. */
  9207. function className(name, module) {
  9208. return function (target) {
  9209. target["__bjsclassName__"] = name;
  9210. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9211. };
  9212. }
  9213. BABYLON.className = className;
  9214. /**
  9215. * An implementation of a loop for asynchronous functions.
  9216. */
  9217. var AsyncLoop = /** @class */ (function () {
  9218. /**
  9219. * Constroctor.
  9220. * @param iterations the number of iterations.
  9221. * @param _fn the function to run each iteration
  9222. * @param _successCallback the callback that will be called upon succesful execution
  9223. * @param offset starting offset.
  9224. */
  9225. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9226. if (offset === void 0) { offset = 0; }
  9227. this.iterations = iterations;
  9228. this._fn = _fn;
  9229. this._successCallback = _successCallback;
  9230. this.index = offset - 1;
  9231. this._done = false;
  9232. }
  9233. /**
  9234. * Execute the next iteration. Must be called after the last iteration was finished.
  9235. */
  9236. AsyncLoop.prototype.executeNext = function () {
  9237. if (!this._done) {
  9238. if (this.index + 1 < this.iterations) {
  9239. ++this.index;
  9240. this._fn(this);
  9241. }
  9242. else {
  9243. this.breakLoop();
  9244. }
  9245. }
  9246. };
  9247. /**
  9248. * Break the loop and run the success callback.
  9249. */
  9250. AsyncLoop.prototype.breakLoop = function () {
  9251. this._done = true;
  9252. this._successCallback();
  9253. };
  9254. /**
  9255. * Helper function
  9256. */
  9257. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9258. if (offset === void 0) { offset = 0; }
  9259. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9260. loop.executeNext();
  9261. return loop;
  9262. };
  9263. /**
  9264. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9265. * @param iterations total number of iterations
  9266. * @param syncedIterations number of synchronous iterations in each async iteration.
  9267. * @param fn the function to call each iteration.
  9268. * @param callback a success call back that will be called when iterating stops.
  9269. * @param breakFunction a break condition (optional)
  9270. * @param timeout timeout settings for the setTimeout function. default - 0.
  9271. * @constructor
  9272. */
  9273. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9274. if (timeout === void 0) { timeout = 0; }
  9275. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9276. if (breakFunction && breakFunction())
  9277. loop.breakLoop();
  9278. else {
  9279. setTimeout(function () {
  9280. for (var i = 0; i < syncedIterations; ++i) {
  9281. var iteration = (loop.index * syncedIterations) + i;
  9282. if (iteration >= iterations)
  9283. break;
  9284. fn(iteration);
  9285. if (breakFunction && breakFunction()) {
  9286. loop.breakLoop();
  9287. break;
  9288. }
  9289. }
  9290. loop.executeNext();
  9291. }, timeout);
  9292. }
  9293. }, callback);
  9294. };
  9295. return AsyncLoop;
  9296. }());
  9297. BABYLON.AsyncLoop = AsyncLoop;
  9298. })(BABYLON || (BABYLON = {}));
  9299. //# sourceMappingURL=babylon.tools.js.map
  9300. var BABYLON;
  9301. (function (BABYLON) {
  9302. var PromiseStates;
  9303. (function (PromiseStates) {
  9304. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9305. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9306. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9307. })(PromiseStates || (PromiseStates = {}));
  9308. var FulFillmentAgregator = /** @class */ (function () {
  9309. function FulFillmentAgregator() {
  9310. this.count = 0;
  9311. this.target = 0;
  9312. this.results = [];
  9313. }
  9314. return FulFillmentAgregator;
  9315. }());
  9316. var InternalPromise = /** @class */ (function () {
  9317. function InternalPromise(resolver) {
  9318. var _this = this;
  9319. this._state = PromiseStates.Pending;
  9320. this._children = new Array();
  9321. this._rejectWasConsumed = false;
  9322. if (!resolver) {
  9323. return;
  9324. }
  9325. try {
  9326. resolver(function (value) {
  9327. _this._resolve(value);
  9328. }, function (reason) {
  9329. _this._reject(reason);
  9330. });
  9331. }
  9332. catch (e) {
  9333. this._reject(e);
  9334. }
  9335. }
  9336. InternalPromise.prototype.catch = function (onRejected) {
  9337. return this.then(undefined, onRejected);
  9338. };
  9339. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9340. var _this = this;
  9341. var newPromise = new InternalPromise();
  9342. newPromise._onFulfilled = onFulfilled;
  9343. newPromise._onRejected = onRejected;
  9344. // Composition
  9345. this._children.push(newPromise);
  9346. if (this._state !== PromiseStates.Pending) {
  9347. BABYLON.Tools.SetImmediate(function () {
  9348. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9349. var returnedValue = newPromise._resolve(_this._result);
  9350. if (returnedValue !== undefined && returnedValue !== null) {
  9351. if (returnedValue._state !== undefined) {
  9352. var returnedPromise = returnedValue;
  9353. newPromise._children.push(returnedPromise);
  9354. newPromise = returnedPromise;
  9355. }
  9356. else {
  9357. newPromise._result = returnedValue;
  9358. }
  9359. }
  9360. }
  9361. else {
  9362. newPromise._reject(_this._reason);
  9363. }
  9364. });
  9365. }
  9366. return newPromise;
  9367. };
  9368. InternalPromise.prototype._moveChildren = function (children) {
  9369. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9370. if (this._state === PromiseStates.Fulfilled) {
  9371. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9372. var child = _b[_i];
  9373. child._resolve(this._result);
  9374. }
  9375. }
  9376. else if (this._state === PromiseStates.Rejected) {
  9377. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9378. var child = _d[_c];
  9379. child._reject(this._reason);
  9380. }
  9381. }
  9382. var _a;
  9383. };
  9384. InternalPromise.prototype._resolve = function (value) {
  9385. try {
  9386. this._state = PromiseStates.Fulfilled;
  9387. this._result = value;
  9388. var returnedValue = null;
  9389. if (this._onFulfilled) {
  9390. returnedValue = this._onFulfilled(value);
  9391. }
  9392. if (returnedValue !== undefined && returnedValue !== null) {
  9393. if (returnedValue._state !== undefined) {
  9394. // Transmit children
  9395. var returnedPromise = returnedValue;
  9396. returnedPromise._moveChildren(this._children);
  9397. }
  9398. else {
  9399. value = returnedValue;
  9400. }
  9401. }
  9402. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9403. var child = _a[_i];
  9404. child._resolve(value);
  9405. }
  9406. this._children.length = 0;
  9407. delete this._onFulfilled;
  9408. delete this._onRejected;
  9409. return returnedValue;
  9410. }
  9411. catch (e) {
  9412. this._reject(e, true);
  9413. }
  9414. return null;
  9415. };
  9416. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9417. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9418. this._state = PromiseStates.Rejected;
  9419. this._reason = reason;
  9420. if (this._onRejected && !onLocalThrow) {
  9421. try {
  9422. this._onRejected(reason);
  9423. this._rejectWasConsumed = true;
  9424. }
  9425. catch (e) {
  9426. reason = e;
  9427. }
  9428. }
  9429. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9430. var child = _a[_i];
  9431. if (this._rejectWasConsumed) {
  9432. child._resolve(null);
  9433. }
  9434. else {
  9435. child._reject(reason);
  9436. }
  9437. }
  9438. this._children.length = 0;
  9439. delete this._onFulfilled;
  9440. delete this._onRejected;
  9441. };
  9442. InternalPromise.resolve = function (value) {
  9443. var newPromise = new InternalPromise();
  9444. newPromise._resolve(value);
  9445. return newPromise;
  9446. };
  9447. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9448. promise.then(function (value) {
  9449. agregator.results[index] = value;
  9450. agregator.count++;
  9451. if (agregator.count === agregator.target) {
  9452. agregator.rootPromise._resolve(agregator.results);
  9453. }
  9454. return null;
  9455. }, function (reason) {
  9456. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9457. agregator.rootPromise._reject(reason);
  9458. }
  9459. });
  9460. };
  9461. InternalPromise.all = function (promises) {
  9462. var newPromise = new InternalPromise();
  9463. var agregator = new FulFillmentAgregator();
  9464. agregator.target = promises.length;
  9465. agregator.rootPromise = newPromise;
  9466. if (promises.length) {
  9467. for (var index = 0; index < promises.length; index++) {
  9468. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9469. }
  9470. }
  9471. else {
  9472. newPromise._resolve([]);
  9473. }
  9474. return newPromise;
  9475. };
  9476. return InternalPromise;
  9477. }());
  9478. /**
  9479. * Helper class that provides a small promise polyfill
  9480. */
  9481. var PromisePolyfill = /** @class */ (function () {
  9482. function PromisePolyfill() {
  9483. }
  9484. /**
  9485. * Static function used to check if the polyfill is required
  9486. * If this is the case then the function will inject the polyfill to window.Promise
  9487. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9488. */
  9489. PromisePolyfill.Apply = function (force) {
  9490. if (force === void 0) { force = false; }
  9491. if (force || typeof Promise === 'undefined') {
  9492. var root = window;
  9493. root.Promise = InternalPromise;
  9494. }
  9495. };
  9496. return PromisePolyfill;
  9497. }());
  9498. BABYLON.PromisePolyfill = PromisePolyfill;
  9499. })(BABYLON || (BABYLON = {}));
  9500. //# sourceMappingURL=babylon.promise.js.map
  9501. var BABYLON;
  9502. (function (BABYLON) {
  9503. var _AlphaState = /** @class */ (function () {
  9504. /**
  9505. * Initializes the state.
  9506. */
  9507. function _AlphaState() {
  9508. this._isAlphaBlendDirty = false;
  9509. this._isBlendFunctionParametersDirty = false;
  9510. this._isBlendEquationParametersDirty = false;
  9511. this._isBlendConstantsDirty = false;
  9512. this._alphaBlend = false;
  9513. this._blendFunctionParameters = new Array(4);
  9514. this._blendEquationParameters = new Array(2);
  9515. this._blendConstants = new Array(4);
  9516. this.reset();
  9517. }
  9518. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9519. get: function () {
  9520. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9526. get: function () {
  9527. return this._alphaBlend;
  9528. },
  9529. set: function (value) {
  9530. if (this._alphaBlend === value) {
  9531. return;
  9532. }
  9533. this._alphaBlend = value;
  9534. this._isAlphaBlendDirty = true;
  9535. },
  9536. enumerable: true,
  9537. configurable: true
  9538. });
  9539. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9540. if (this._blendConstants[0] === r &&
  9541. this._blendConstants[1] === g &&
  9542. this._blendConstants[2] === b &&
  9543. this._blendConstants[3] === a) {
  9544. return;
  9545. }
  9546. this._blendConstants[0] = r;
  9547. this._blendConstants[1] = g;
  9548. this._blendConstants[2] = b;
  9549. this._blendConstants[3] = a;
  9550. this._isBlendConstantsDirty = true;
  9551. };
  9552. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9553. if (this._blendFunctionParameters[0] === value0 &&
  9554. this._blendFunctionParameters[1] === value1 &&
  9555. this._blendFunctionParameters[2] === value2 &&
  9556. this._blendFunctionParameters[3] === value3) {
  9557. return;
  9558. }
  9559. this._blendFunctionParameters[0] = value0;
  9560. this._blendFunctionParameters[1] = value1;
  9561. this._blendFunctionParameters[2] = value2;
  9562. this._blendFunctionParameters[3] = value3;
  9563. this._isBlendFunctionParametersDirty = true;
  9564. };
  9565. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9566. if (this._blendEquationParameters[0] === rgb &&
  9567. this._blendEquationParameters[1] === alpha) {
  9568. return;
  9569. }
  9570. this._blendEquationParameters[0] = rgb;
  9571. this._blendEquationParameters[1] = alpha;
  9572. this._isBlendEquationParametersDirty = true;
  9573. };
  9574. _AlphaState.prototype.reset = function () {
  9575. this._alphaBlend = false;
  9576. this._blendFunctionParameters[0] = null;
  9577. this._blendFunctionParameters[1] = null;
  9578. this._blendFunctionParameters[2] = null;
  9579. this._blendFunctionParameters[3] = null;
  9580. this._blendEquationParameters[0] = null;
  9581. this._blendEquationParameters[1] = null;
  9582. this._blendConstants[0] = null;
  9583. this._blendConstants[1] = null;
  9584. this._blendConstants[2] = null;
  9585. this._blendConstants[3] = null;
  9586. this._isAlphaBlendDirty = true;
  9587. this._isBlendFunctionParametersDirty = false;
  9588. this._isBlendEquationParametersDirty = false;
  9589. this._isBlendConstantsDirty = false;
  9590. };
  9591. _AlphaState.prototype.apply = function (gl) {
  9592. if (!this.isDirty) {
  9593. return;
  9594. }
  9595. // Alpha blend
  9596. if (this._isAlphaBlendDirty) {
  9597. if (this._alphaBlend) {
  9598. gl.enable(gl.BLEND);
  9599. }
  9600. else {
  9601. gl.disable(gl.BLEND);
  9602. }
  9603. this._isAlphaBlendDirty = false;
  9604. }
  9605. // Alpha function
  9606. if (this._isBlendFunctionParametersDirty) {
  9607. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9608. this._isBlendFunctionParametersDirty = false;
  9609. }
  9610. // Alpha equation
  9611. if (this._isBlendEquationParametersDirty) {
  9612. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9613. this._isBlendEquationParametersDirty = false;
  9614. }
  9615. // Constants
  9616. if (this._isBlendConstantsDirty) {
  9617. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9618. this._isBlendConstantsDirty = false;
  9619. }
  9620. };
  9621. return _AlphaState;
  9622. }());
  9623. BABYLON._AlphaState = _AlphaState;
  9624. })(BABYLON || (BABYLON = {}));
  9625. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9626. var BABYLON;
  9627. (function (BABYLON) {
  9628. var _DepthCullingState = /** @class */ (function () {
  9629. /**
  9630. * Initializes the state.
  9631. */
  9632. function _DepthCullingState() {
  9633. this._isDepthTestDirty = false;
  9634. this._isDepthMaskDirty = false;
  9635. this._isDepthFuncDirty = false;
  9636. this._isCullFaceDirty = false;
  9637. this._isCullDirty = false;
  9638. this._isZOffsetDirty = false;
  9639. this._isFrontFaceDirty = false;
  9640. this.reset();
  9641. }
  9642. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9643. get: function () {
  9644. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9650. get: function () {
  9651. return this._zOffset;
  9652. },
  9653. set: function (value) {
  9654. if (this._zOffset === value) {
  9655. return;
  9656. }
  9657. this._zOffset = value;
  9658. this._isZOffsetDirty = true;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9664. get: function () {
  9665. return this._cullFace;
  9666. },
  9667. set: function (value) {
  9668. if (this._cullFace === value) {
  9669. return;
  9670. }
  9671. this._cullFace = value;
  9672. this._isCullFaceDirty = true;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9678. get: function () {
  9679. return this._cull;
  9680. },
  9681. set: function (value) {
  9682. if (this._cull === value) {
  9683. return;
  9684. }
  9685. this._cull = value;
  9686. this._isCullDirty = true;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9692. get: function () {
  9693. return this._depthFunc;
  9694. },
  9695. set: function (value) {
  9696. if (this._depthFunc === value) {
  9697. return;
  9698. }
  9699. this._depthFunc = value;
  9700. this._isDepthFuncDirty = true;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9706. get: function () {
  9707. return this._depthMask;
  9708. },
  9709. set: function (value) {
  9710. if (this._depthMask === value) {
  9711. return;
  9712. }
  9713. this._depthMask = value;
  9714. this._isDepthMaskDirty = true;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9720. get: function () {
  9721. return this._depthTest;
  9722. },
  9723. set: function (value) {
  9724. if (this._depthTest === value) {
  9725. return;
  9726. }
  9727. this._depthTest = value;
  9728. this._isDepthTestDirty = true;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9734. get: function () {
  9735. return this._frontFace;
  9736. },
  9737. set: function (value) {
  9738. if (this._frontFace === value) {
  9739. return;
  9740. }
  9741. this._frontFace = value;
  9742. this._isFrontFaceDirty = true;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. _DepthCullingState.prototype.reset = function () {
  9748. this._depthMask = true;
  9749. this._depthTest = true;
  9750. this._depthFunc = null;
  9751. this._cullFace = null;
  9752. this._cull = null;
  9753. this._zOffset = 0;
  9754. this._frontFace = null;
  9755. this._isDepthTestDirty = true;
  9756. this._isDepthMaskDirty = true;
  9757. this._isDepthFuncDirty = false;
  9758. this._isCullFaceDirty = false;
  9759. this._isCullDirty = false;
  9760. this._isZOffsetDirty = false;
  9761. this._isFrontFaceDirty = false;
  9762. };
  9763. _DepthCullingState.prototype.apply = function (gl) {
  9764. if (!this.isDirty) {
  9765. return;
  9766. }
  9767. // Cull
  9768. if (this._isCullDirty) {
  9769. if (this.cull) {
  9770. gl.enable(gl.CULL_FACE);
  9771. }
  9772. else {
  9773. gl.disable(gl.CULL_FACE);
  9774. }
  9775. this._isCullDirty = false;
  9776. }
  9777. // Cull face
  9778. if (this._isCullFaceDirty) {
  9779. gl.cullFace(this.cullFace);
  9780. this._isCullFaceDirty = false;
  9781. }
  9782. // Depth mask
  9783. if (this._isDepthMaskDirty) {
  9784. gl.depthMask(this.depthMask);
  9785. this._isDepthMaskDirty = false;
  9786. }
  9787. // Depth test
  9788. if (this._isDepthTestDirty) {
  9789. if (this.depthTest) {
  9790. gl.enable(gl.DEPTH_TEST);
  9791. }
  9792. else {
  9793. gl.disable(gl.DEPTH_TEST);
  9794. }
  9795. this._isDepthTestDirty = false;
  9796. }
  9797. // Depth func
  9798. if (this._isDepthFuncDirty) {
  9799. gl.depthFunc(this.depthFunc);
  9800. this._isDepthFuncDirty = false;
  9801. }
  9802. // zOffset
  9803. if (this._isZOffsetDirty) {
  9804. if (this.zOffset) {
  9805. gl.enable(gl.POLYGON_OFFSET_FILL);
  9806. gl.polygonOffset(this.zOffset, 0);
  9807. }
  9808. else {
  9809. gl.disable(gl.POLYGON_OFFSET_FILL);
  9810. }
  9811. this._isZOffsetDirty = false;
  9812. }
  9813. // Front face
  9814. if (this._isFrontFaceDirty) {
  9815. gl.frontFace(this.frontFace);
  9816. this._isFrontFaceDirty = false;
  9817. }
  9818. };
  9819. return _DepthCullingState;
  9820. }());
  9821. BABYLON._DepthCullingState = _DepthCullingState;
  9822. })(BABYLON || (BABYLON = {}));
  9823. //# sourceMappingURL=babylon.depthCullingState.js.map
  9824. var BABYLON;
  9825. (function (BABYLON) {
  9826. var _StencilState = /** @class */ (function () {
  9827. function _StencilState() {
  9828. this._isStencilTestDirty = false;
  9829. this._isStencilMaskDirty = false;
  9830. this._isStencilFuncDirty = false;
  9831. this._isStencilOpDirty = false;
  9832. this.reset();
  9833. }
  9834. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9835. get: function () {
  9836. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9842. get: function () {
  9843. return this._stencilFunc;
  9844. },
  9845. set: function (value) {
  9846. if (this._stencilFunc === value) {
  9847. return;
  9848. }
  9849. this._stencilFunc = value;
  9850. this._isStencilFuncDirty = true;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9856. get: function () {
  9857. return this._stencilFuncRef;
  9858. },
  9859. set: function (value) {
  9860. if (this._stencilFuncRef === value) {
  9861. return;
  9862. }
  9863. this._stencilFuncRef = value;
  9864. this._isStencilFuncDirty = true;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9870. get: function () {
  9871. return this._stencilFuncMask;
  9872. },
  9873. set: function (value) {
  9874. if (this._stencilFuncMask === value) {
  9875. return;
  9876. }
  9877. this._stencilFuncMask = value;
  9878. this._isStencilFuncDirty = true;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9884. get: function () {
  9885. return this._stencilOpStencilFail;
  9886. },
  9887. set: function (value) {
  9888. if (this._stencilOpStencilFail === value) {
  9889. return;
  9890. }
  9891. this._stencilOpStencilFail = value;
  9892. this._isStencilOpDirty = true;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9898. get: function () {
  9899. return this._stencilOpDepthFail;
  9900. },
  9901. set: function (value) {
  9902. if (this._stencilOpDepthFail === value) {
  9903. return;
  9904. }
  9905. this._stencilOpDepthFail = value;
  9906. this._isStencilOpDirty = true;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9912. get: function () {
  9913. return this._stencilOpStencilDepthPass;
  9914. },
  9915. set: function (value) {
  9916. if (this._stencilOpStencilDepthPass === value) {
  9917. return;
  9918. }
  9919. this._stencilOpStencilDepthPass = value;
  9920. this._isStencilOpDirty = true;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9926. get: function () {
  9927. return this._stencilMask;
  9928. },
  9929. set: function (value) {
  9930. if (this._stencilMask === value) {
  9931. return;
  9932. }
  9933. this._stencilMask = value;
  9934. this._isStencilMaskDirty = true;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9940. get: function () {
  9941. return this._stencilTest;
  9942. },
  9943. set: function (value) {
  9944. if (this._stencilTest === value) {
  9945. return;
  9946. }
  9947. this._stencilTest = value;
  9948. this._isStencilTestDirty = true;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. _StencilState.prototype.reset = function () {
  9954. this._stencilTest = false;
  9955. this._stencilMask = 0xFF;
  9956. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9957. this._stencilFuncRef = 1;
  9958. this._stencilFuncMask = 0xFF;
  9959. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9960. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9961. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9962. this._isStencilTestDirty = true;
  9963. this._isStencilMaskDirty = true;
  9964. this._isStencilFuncDirty = true;
  9965. this._isStencilOpDirty = true;
  9966. };
  9967. _StencilState.prototype.apply = function (gl) {
  9968. if (!this.isDirty) {
  9969. return;
  9970. }
  9971. // Stencil test
  9972. if (this._isStencilTestDirty) {
  9973. if (this.stencilTest) {
  9974. gl.enable(gl.STENCIL_TEST);
  9975. }
  9976. else {
  9977. gl.disable(gl.STENCIL_TEST);
  9978. }
  9979. this._isStencilTestDirty = false;
  9980. }
  9981. // Stencil mask
  9982. if (this._isStencilMaskDirty) {
  9983. gl.stencilMask(this.stencilMask);
  9984. this._isStencilMaskDirty = false;
  9985. }
  9986. // Stencil func
  9987. if (this._isStencilFuncDirty) {
  9988. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9989. this._isStencilFuncDirty = false;
  9990. }
  9991. // Stencil op
  9992. if (this._isStencilOpDirty) {
  9993. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9994. this._isStencilOpDirty = false;
  9995. }
  9996. };
  9997. return _StencilState;
  9998. }());
  9999. BABYLON._StencilState = _StencilState;
  10000. })(BABYLON || (BABYLON = {}));
  10001. //# sourceMappingURL=babylon.stencilState.js.map
  10002. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10003. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10004. s = arguments[i];
  10005. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10006. t[p] = s[p];
  10007. }
  10008. return t;
  10009. };
  10010. var BABYLON;
  10011. (function (BABYLON) {
  10012. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10013. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10014. };
  10015. var compileRawShader = function (gl, source, type) {
  10016. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10017. gl.shaderSource(shader, source);
  10018. gl.compileShader(shader);
  10019. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10020. var log = gl.getShaderInfoLog(shader);
  10021. if (log) {
  10022. throw new Error(log);
  10023. }
  10024. }
  10025. if (!shader) {
  10026. throw new Error("Something went wrong while compile the shader.");
  10027. }
  10028. return shader;
  10029. };
  10030. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10031. var magFilter = gl.NEAREST;
  10032. var minFilter = gl.NEAREST;
  10033. switch (samplingMode) {
  10034. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10035. magFilter = gl.LINEAR;
  10036. if (generateMipMaps) {
  10037. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10038. }
  10039. else {
  10040. minFilter = gl.LINEAR;
  10041. }
  10042. break;
  10043. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10044. magFilter = gl.LINEAR;
  10045. if (generateMipMaps) {
  10046. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10047. }
  10048. else {
  10049. minFilter = gl.LINEAR;
  10050. }
  10051. break;
  10052. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10053. magFilter = gl.NEAREST;
  10054. if (generateMipMaps) {
  10055. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10056. }
  10057. else {
  10058. minFilter = gl.NEAREST;
  10059. }
  10060. break;
  10061. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10062. magFilter = gl.NEAREST;
  10063. if (generateMipMaps) {
  10064. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10065. }
  10066. else {
  10067. minFilter = gl.NEAREST;
  10068. }
  10069. break;
  10070. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10071. magFilter = gl.NEAREST;
  10072. if (generateMipMaps) {
  10073. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10074. }
  10075. else {
  10076. minFilter = gl.LINEAR;
  10077. }
  10078. break;
  10079. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10080. magFilter = gl.NEAREST;
  10081. if (generateMipMaps) {
  10082. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10083. }
  10084. else {
  10085. minFilter = gl.LINEAR;
  10086. }
  10087. break;
  10088. case BABYLON.Texture.NEAREST_LINEAR:
  10089. magFilter = gl.NEAREST;
  10090. minFilter = gl.LINEAR;
  10091. break;
  10092. case BABYLON.Texture.NEAREST_NEAREST:
  10093. magFilter = gl.NEAREST;
  10094. minFilter = gl.NEAREST;
  10095. break;
  10096. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10097. magFilter = gl.LINEAR;
  10098. if (generateMipMaps) {
  10099. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10100. }
  10101. else {
  10102. minFilter = gl.NEAREST;
  10103. }
  10104. break;
  10105. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10106. magFilter = gl.LINEAR;
  10107. if (generateMipMaps) {
  10108. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10109. }
  10110. else {
  10111. minFilter = gl.NEAREST;
  10112. }
  10113. break;
  10114. case BABYLON.Texture.LINEAR_LINEAR:
  10115. magFilter = gl.LINEAR;
  10116. minFilter = gl.LINEAR;
  10117. break;
  10118. case BABYLON.Texture.LINEAR_NEAREST:
  10119. magFilter = gl.LINEAR;
  10120. minFilter = gl.NEAREST;
  10121. break;
  10122. }
  10123. return {
  10124. min: minFilter,
  10125. mag: magFilter
  10126. };
  10127. };
  10128. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10129. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10130. var img;
  10131. var onload = function () {
  10132. loadedImages[index] = img;
  10133. loadedImages._internalCount++;
  10134. if (scene) {
  10135. scene._removePendingData(img);
  10136. }
  10137. if (loadedImages._internalCount === 6) {
  10138. onfinish(loadedImages);
  10139. }
  10140. };
  10141. var onerror = function (message, exception) {
  10142. if (scene) {
  10143. scene._removePendingData(img);
  10144. }
  10145. if (onErrorCallBack) {
  10146. onErrorCallBack(message, exception);
  10147. }
  10148. };
  10149. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10150. if (scene) {
  10151. scene._addPendingData(img);
  10152. }
  10153. };
  10154. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10155. if (onError === void 0) { onError = null; }
  10156. var loadedImages = [];
  10157. loadedImages._internalCount = 0;
  10158. for (var index = 0; index < 6; index++) {
  10159. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10160. }
  10161. };
  10162. var BufferPointer = /** @class */ (function () {
  10163. function BufferPointer() {
  10164. }
  10165. return BufferPointer;
  10166. }());
  10167. var InstancingAttributeInfo = /** @class */ (function () {
  10168. function InstancingAttributeInfo() {
  10169. }
  10170. return InstancingAttributeInfo;
  10171. }());
  10172. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10173. /**
  10174. * Define options used to create a render target texture
  10175. */
  10176. var RenderTargetCreationOptions = /** @class */ (function () {
  10177. function RenderTargetCreationOptions() {
  10178. }
  10179. return RenderTargetCreationOptions;
  10180. }());
  10181. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10182. /**
  10183. * Regroup several parameters relative to the browser in use
  10184. */
  10185. var EngineCapabilities = /** @class */ (function () {
  10186. function EngineCapabilities() {
  10187. }
  10188. return EngineCapabilities;
  10189. }());
  10190. BABYLON.EngineCapabilities = EngineCapabilities;
  10191. /**
  10192. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10193. */
  10194. var Engine = /** @class */ (function () {
  10195. /**
  10196. * @constructor
  10197. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10198. * @param antialias defines enable antialiasing (default: false)
  10199. * @param options defines further options to be sent to the getContext() function
  10200. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10201. */
  10202. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10203. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10204. var _this = this;
  10205. // Public members
  10206. this.forcePOTTextures = false;
  10207. this.isFullscreen = false;
  10208. this.isPointerLock = false;
  10209. this.cullBackFaces = true;
  10210. this.renderEvenInBackground = true;
  10211. this.preventCacheWipeBetweenFrames = false;
  10212. // To enable/disable IDB support and avoid XHR on .manifest
  10213. this.enableOfflineSupport = false;
  10214. this.scenes = new Array();
  10215. this.postProcesses = new Array();
  10216. // Observables
  10217. /**
  10218. * Observable event triggered each time the rendering canvas is resized
  10219. */
  10220. this.onResizeObservable = new BABYLON.Observable();
  10221. /**
  10222. * Observable event triggered each time the canvas loses focus
  10223. */
  10224. this.onCanvasBlurObservable = new BABYLON.Observable();
  10225. /**
  10226. * Observable event triggered each time the canvas gains focus
  10227. */
  10228. this.onCanvasFocusObservable = new BABYLON.Observable();
  10229. /**
  10230. * Observable event triggered each time the canvas receives pointerout event
  10231. */
  10232. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10233. /**
  10234. * Observable event triggered before each texture is initialized
  10235. */
  10236. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10237. //WebVR
  10238. this._vrDisplay = undefined;
  10239. this._vrSupported = false;
  10240. this._vrExclusivePointerMode = false;
  10241. // Uniform buffers list
  10242. this.disableUniformBuffers = false;
  10243. this._uniformBuffers = new Array();
  10244. // Observables
  10245. /**
  10246. * Observable raised when the engine begins a new frame
  10247. */
  10248. this.onBeginFrameObservable = new BABYLON.Observable();
  10249. /**
  10250. * Observable raised when the engine ends the current frame
  10251. */
  10252. this.onEndFrameObservable = new BABYLON.Observable();
  10253. /**
  10254. * Observable raised when the engine is about to compile a shader
  10255. */
  10256. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10257. /**
  10258. * Observable raised when the engine has jsut compiled a shader
  10259. */
  10260. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10261. this._windowIsBackground = false;
  10262. this._webGLVersion = 1.0;
  10263. this._badOS = false;
  10264. this._badDesktopOS = false;
  10265. /**
  10266. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10267. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10268. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10269. */
  10270. this.disableTextureBindingOptimization = false;
  10271. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10272. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10273. this.onVRRequestPresentStart = new BABYLON.Observable();
  10274. this._colorWrite = true;
  10275. this._drawCalls = new BABYLON.PerfCounter();
  10276. this._textureCollisions = new BABYLON.PerfCounter();
  10277. this._renderingQueueLaunched = false;
  10278. this._activeRenderLoops = new Array();
  10279. // Deterministic lockstepMaxSteps
  10280. this._deterministicLockstep = false;
  10281. this._lockstepMaxSteps = 4;
  10282. // Lost context
  10283. this.onContextLostObservable = new BABYLON.Observable();
  10284. this.onContextRestoredObservable = new BABYLON.Observable();
  10285. this._contextWasLost = false;
  10286. this._doNotHandleContextLost = false;
  10287. // FPS
  10288. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10289. this._fps = 60;
  10290. this._deltaTime = 0;
  10291. /**
  10292. * Turn this value on if you want to pause FPS computation when in background
  10293. */
  10294. this.disablePerformanceMonitorInBackground = false;
  10295. // States
  10296. this._depthCullingState = new BABYLON._DepthCullingState();
  10297. this._stencilState = new BABYLON._StencilState();
  10298. this._alphaState = new BABYLON._AlphaState();
  10299. this._alphaMode = Engine.ALPHA_DISABLE;
  10300. // Cache
  10301. this._internalTexturesCache = new Array();
  10302. this._activeChannel = 0;
  10303. this._currentTextureChannel = -1;
  10304. this._boundTexturesCache = {};
  10305. this._compiledEffects = {};
  10306. this._vertexAttribArraysEnabled = [];
  10307. this._uintIndicesCurrentlySet = false;
  10308. this._currentBoundBuffer = new Array();
  10309. this._currentBufferPointers = new Array();
  10310. this._currentInstanceLocations = new Array();
  10311. this._currentInstanceBuffers = new Array();
  10312. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10313. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10314. this._vaoRecordInProgress = false;
  10315. this._mustWipeVertexAttributes = false;
  10316. this._nextFreeTextureSlots = new Array();
  10317. this._maxSimultaneousTextures = 0;
  10318. this._activeRequests = new Array();
  10319. // Hardware supported Compressed Textures
  10320. this._texturesSupported = new Array();
  10321. this._onVRFullScreenTriggered = function () {
  10322. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10323. //get the old size before we change
  10324. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10325. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10326. //get the width and height, change the render size
  10327. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10328. _this.setHardwareScalingLevel(1);
  10329. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10330. }
  10331. else {
  10332. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10333. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10334. }
  10335. };
  10336. this._boundUniforms = {};
  10337. // Register promises
  10338. BABYLON.PromisePolyfill.Apply();
  10339. var canvas = null;
  10340. Engine.Instances.push(this);
  10341. if (!canvasOrContext) {
  10342. return;
  10343. }
  10344. options = options || {};
  10345. if (canvasOrContext.getContext) {
  10346. canvas = canvasOrContext;
  10347. this._renderingCanvas = canvas;
  10348. if (antialias != null) {
  10349. options.antialias = antialias;
  10350. }
  10351. if (options.deterministicLockstep === undefined) {
  10352. options.deterministicLockstep = false;
  10353. }
  10354. if (options.lockstepMaxSteps === undefined) {
  10355. options.lockstepMaxSteps = 4;
  10356. }
  10357. if (options.preserveDrawingBuffer === undefined) {
  10358. options.preserveDrawingBuffer = false;
  10359. }
  10360. if (options.audioEngine === undefined) {
  10361. options.audioEngine = true;
  10362. }
  10363. if (options.stencil === undefined) {
  10364. options.stencil = true;
  10365. }
  10366. this._deterministicLockstep = options.deterministicLockstep;
  10367. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10368. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10369. // Exceptions
  10370. if (navigator && navigator.userAgent) {
  10371. var ua = navigator.userAgent;
  10372. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10373. var exception = _a[_i];
  10374. var key = exception.key;
  10375. var targets = exception.targets;
  10376. if (ua.indexOf(key) > -1) {
  10377. if (exception.capture && exception.captureConstraint) {
  10378. var capture = exception.capture;
  10379. var constraint = exception.captureConstraint;
  10380. var regex = new RegExp(capture);
  10381. var matches = regex.exec(ua);
  10382. if (matches && matches.length > 0) {
  10383. var capturedValue = parseInt(matches[matches.length - 1]);
  10384. if (capturedValue >= constraint) {
  10385. continue;
  10386. }
  10387. }
  10388. }
  10389. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10390. var target = targets_1[_b];
  10391. switch (target) {
  10392. case "uniformBuffer":
  10393. this.disableUniformBuffers = true;
  10394. break;
  10395. case "textureBindingOptimization":
  10396. this.disableTextureBindingOptimization = true;
  10397. break;
  10398. }
  10399. }
  10400. break;
  10401. }
  10402. }
  10403. }
  10404. // GL
  10405. if (!options.disableWebGL2Support) {
  10406. try {
  10407. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10408. if (this._gl) {
  10409. this._webGLVersion = 2.0;
  10410. }
  10411. }
  10412. catch (e) {
  10413. // Do nothing
  10414. }
  10415. }
  10416. if (!this._gl) {
  10417. if (!canvas) {
  10418. throw new Error("The provided canvas is null or undefined.");
  10419. }
  10420. try {
  10421. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10422. }
  10423. catch (e) {
  10424. throw new Error("WebGL not supported");
  10425. }
  10426. }
  10427. if (!this._gl) {
  10428. throw new Error("WebGL not supported");
  10429. }
  10430. this._onCanvasFocus = function () {
  10431. _this.onCanvasFocusObservable.notifyObservers(_this);
  10432. };
  10433. this._onCanvasBlur = function () {
  10434. _this.onCanvasBlurObservable.notifyObservers(_this);
  10435. };
  10436. canvas.addEventListener("focus", this._onCanvasFocus);
  10437. canvas.addEventListener("blur", this._onCanvasBlur);
  10438. this._onBlur = function () {
  10439. if (_this.disablePerformanceMonitorInBackground) {
  10440. _this._performanceMonitor.disable();
  10441. }
  10442. _this._windowIsBackground = true;
  10443. };
  10444. this._onFocus = function () {
  10445. if (_this.disablePerformanceMonitorInBackground) {
  10446. _this._performanceMonitor.enable();
  10447. }
  10448. _this._windowIsBackground = false;
  10449. };
  10450. this._onCanvasPointerOut = function () {
  10451. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10452. };
  10453. window.addEventListener("blur", this._onBlur);
  10454. window.addEventListener("focus", this._onFocus);
  10455. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10456. // Context lost
  10457. if (!this._doNotHandleContextLost) {
  10458. this._onContextLost = function (evt) {
  10459. evt.preventDefault();
  10460. _this._contextWasLost = true;
  10461. BABYLON.Tools.Warn("WebGL context lost.");
  10462. _this.onContextLostObservable.notifyObservers(_this);
  10463. };
  10464. this._onContextRestored = function (evt) {
  10465. // Adding a timeout to avoid race condition at browser level
  10466. setTimeout(function () {
  10467. // Rebuild gl context
  10468. _this._initGLContext();
  10469. // Rebuild effects
  10470. _this._rebuildEffects();
  10471. // Rebuild textures
  10472. _this._rebuildInternalTextures();
  10473. // Rebuild buffers
  10474. _this._rebuildBuffers();
  10475. // Cache
  10476. _this.wipeCaches(true);
  10477. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10478. _this.onContextRestoredObservable.notifyObservers(_this);
  10479. _this._contextWasLost = false;
  10480. }, 0);
  10481. };
  10482. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10483. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10484. }
  10485. }
  10486. else {
  10487. this._gl = canvasOrContext;
  10488. this._renderingCanvas = this._gl.canvas;
  10489. if (this._gl.renderbufferStorageMultisample) {
  10490. this._webGLVersion = 2.0;
  10491. }
  10492. options.stencil = this._gl.getContextAttributes().stencil;
  10493. }
  10494. // Viewport
  10495. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10496. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10497. this.resize();
  10498. this._isStencilEnable = options.stencil ? true : false;
  10499. this._initGLContext();
  10500. if (canvas) {
  10501. // Fullscreen
  10502. this._onFullscreenChange = function () {
  10503. if (document.fullscreen !== undefined) {
  10504. _this.isFullscreen = document.fullscreen;
  10505. }
  10506. else if (document.mozFullScreen !== undefined) {
  10507. _this.isFullscreen = document.mozFullScreen;
  10508. }
  10509. else if (document.webkitIsFullScreen !== undefined) {
  10510. _this.isFullscreen = document.webkitIsFullScreen;
  10511. }
  10512. else if (document.msIsFullScreen !== undefined) {
  10513. _this.isFullscreen = document.msIsFullScreen;
  10514. }
  10515. // Pointer lock
  10516. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10517. canvas.requestPointerLock = canvas.requestPointerLock ||
  10518. canvas.msRequestPointerLock ||
  10519. canvas.mozRequestPointerLock ||
  10520. canvas.webkitRequestPointerLock;
  10521. if (canvas.requestPointerLock) {
  10522. canvas.requestPointerLock();
  10523. }
  10524. }
  10525. };
  10526. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10527. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10528. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10529. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10530. // Pointer lock
  10531. this._onPointerLockChange = function () {
  10532. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10533. document.webkitPointerLockElement === canvas ||
  10534. document.msPointerLockElement === canvas ||
  10535. document.pointerLockElement === canvas);
  10536. };
  10537. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10538. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10539. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10540. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10541. this._onVRDisplayPointerRestricted = function () {
  10542. if (canvas) {
  10543. canvas.requestPointerLock();
  10544. }
  10545. };
  10546. this._onVRDisplayPointerUnrestricted = function () {
  10547. document.exitPointerLock();
  10548. };
  10549. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10550. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10551. }
  10552. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10553. Engine.audioEngine = new BABYLON.AudioEngine();
  10554. }
  10555. // Prepare buffer pointers
  10556. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10557. this._currentBufferPointers[i] = new BufferPointer();
  10558. }
  10559. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10560. // Load WebVR Devices
  10561. if (options.autoEnableWebVR) {
  10562. this.initWebVR();
  10563. }
  10564. // Detect if we are running on a faulty buggy OS.
  10565. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10566. // Detect if we are running on a faulty buggy desktop OS.
  10567. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10568. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10569. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10570. }
  10571. Object.defineProperty(Engine, "LastCreatedEngine", {
  10572. get: function () {
  10573. if (Engine.Instances.length === 0) {
  10574. return null;
  10575. }
  10576. return Engine.Instances[Engine.Instances.length - 1];
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(Engine, "LastCreatedScene", {
  10582. get: function () {
  10583. var lastCreatedEngine = Engine.LastCreatedEngine;
  10584. if (!lastCreatedEngine) {
  10585. return null;
  10586. }
  10587. if (lastCreatedEngine.scenes.length === 0) {
  10588. return null;
  10589. }
  10590. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. /**
  10596. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10597. */
  10598. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10599. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10600. var engine = Engine.Instances[engineIndex];
  10601. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10602. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10603. }
  10604. }
  10605. };
  10606. Object.defineProperty(Engine, "NEVER", {
  10607. get: function () {
  10608. return Engine._NEVER;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(Engine, "ALWAYS", {
  10614. get: function () {
  10615. return Engine._ALWAYS;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(Engine, "LESS", {
  10621. get: function () {
  10622. return Engine._LESS;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(Engine, "EQUAL", {
  10628. get: function () {
  10629. return Engine._EQUAL;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(Engine, "LEQUAL", {
  10635. get: function () {
  10636. return Engine._LEQUAL;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(Engine, "GREATER", {
  10642. get: function () {
  10643. return Engine._GREATER;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(Engine, "GEQUAL", {
  10649. get: function () {
  10650. return Engine._GEQUAL;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "NOTEQUAL", {
  10656. get: function () {
  10657. return Engine._NOTEQUAL;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "KEEP", {
  10663. get: function () {
  10664. return Engine._KEEP;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "REPLACE", {
  10670. get: function () {
  10671. return Engine._REPLACE;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "INCR", {
  10677. get: function () {
  10678. return Engine._INCR;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "DECR", {
  10684. get: function () {
  10685. return Engine._DECR;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "INVERT", {
  10691. get: function () {
  10692. return Engine._INVERT;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "INCR_WRAP", {
  10698. get: function () {
  10699. return Engine._INCR_WRAP;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "DECR_WRAP", {
  10705. get: function () {
  10706. return Engine._DECR_WRAP;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10712. get: function () {
  10713. return Engine._ALPHA_DISABLE;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10719. get: function () {
  10720. return Engine._ALPHA_ONEONE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "ALPHA_ADD", {
  10726. get: function () {
  10727. return Engine._ALPHA_ADD;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10733. get: function () {
  10734. return Engine._ALPHA_COMBINE;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10740. get: function () {
  10741. return Engine._ALPHA_SUBTRACT;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10747. get: function () {
  10748. return Engine._ALPHA_MULTIPLY;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10754. get: function () {
  10755. return Engine._ALPHA_MAXIMIZED;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10761. get: function () {
  10762. return Engine._ALPHA_PREMULTIPLIED;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10768. get: function () {
  10769. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10775. get: function () {
  10776. return Engine._ALPHA_INTERPOLATE;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10782. get: function () {
  10783. return Engine._ALPHA_SCREENMODE;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10789. get: function () {
  10790. return Engine._DELAYLOADSTATE_NONE;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10796. get: function () {
  10797. return Engine._DELAYLOADSTATE_LOADED;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10803. get: function () {
  10804. return Engine._DELAYLOADSTATE_LOADING;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10810. get: function () {
  10811. return Engine._DELAYLOADSTATE_NOTLOADED;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10817. get: function () {
  10818. return Engine._TEXTUREFORMAT_ALPHA;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10824. get: function () {
  10825. return Engine._TEXTUREFORMAT_LUMINANCE;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10831. /**
  10832. * R32F
  10833. */
  10834. get: function () {
  10835. return Engine._TEXTUREFORMAT_R32F;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10841. /**
  10842. * RG32F
  10843. */
  10844. get: function () {
  10845. return Engine._TEXTUREFORMAT_RG32F;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10851. /**
  10852. * RGB32F
  10853. */
  10854. get: function () {
  10855. return Engine._TEXTUREFORMAT_RGB32F;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10861. get: function () {
  10862. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10868. get: function () {
  10869. return Engine._TEXTUREFORMAT_RGB;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10875. get: function () {
  10876. return Engine._TEXTUREFORMAT_RGBA;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10882. get: function () {
  10883. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10889. get: function () {
  10890. return Engine._TEXTURETYPE_FLOAT;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10896. get: function () {
  10897. return Engine._TEXTURETYPE_HALF_FLOAT;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10903. get: function () {
  10904. return Engine._SCALEMODE_FLOOR;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10910. get: function () {
  10911. return Engine._SCALEMODE_NEAREST;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10917. get: function () {
  10918. return Engine._SCALEMODE_CEILING;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Engine, "Version", {
  10924. get: function () {
  10925. return "3.2.0-alpha7";
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10931. get: function () {
  10932. return this._vrExclusivePointerMode;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10938. get: function () {
  10939. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10945. get: function () {
  10946. return this._webGLVersion < 2 || this.forcePOTTextures;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine.prototype, "badOS", {
  10952. get: function () {
  10953. return this._badOS;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10959. get: function () {
  10960. return this._badDesktopOS;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10966. get: function () {
  10967. return this._performanceMonitor;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10973. get: function () {
  10974. return this._texturesSupported;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10980. get: function () {
  10981. return this._textureFormatInUse;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine.prototype, "currentViewport", {
  10987. get: function () {
  10988. return this._cachedViewport;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10994. // Empty texture
  10995. get: function () {
  10996. if (!this._emptyTexture) {
  10997. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10998. }
  10999. return this._emptyTexture;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11005. get: function () {
  11006. if (!this._emptyTexture3D) {
  11007. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11008. }
  11009. return this._emptyTexture3D;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11015. get: function () {
  11016. if (!this._emptyCubeTexture) {
  11017. var faceData = new Uint8Array(4);
  11018. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11019. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11020. }
  11021. return this._emptyCubeTexture;
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. Engine.prototype._rebuildInternalTextures = function () {
  11027. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11028. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11029. var internalTexture = currentState_1[_i];
  11030. internalTexture._rebuild();
  11031. }
  11032. };
  11033. Engine.prototype._rebuildEffects = function () {
  11034. for (var key in this._compiledEffects) {
  11035. var effect = this._compiledEffects[key];
  11036. effect._prepareEffect();
  11037. }
  11038. BABYLON.Effect.ResetCache();
  11039. };
  11040. Engine.prototype._rebuildBuffers = function () {
  11041. // Index / Vertex
  11042. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11043. var scene = _a[_i];
  11044. scene.resetCachedMaterial();
  11045. scene._rebuildGeometries();
  11046. scene._rebuildTextures();
  11047. }
  11048. // Uniforms
  11049. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11050. var uniformBuffer = _c[_b];
  11051. uniformBuffer._rebuild();
  11052. }
  11053. };
  11054. Engine.prototype._initGLContext = function () {
  11055. // Caps
  11056. this._caps = new EngineCapabilities();
  11057. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11058. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11059. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11060. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11061. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11062. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11063. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11064. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11065. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11066. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11067. // Infos
  11068. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11069. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11070. if (rendererInfo != null) {
  11071. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11072. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11073. }
  11074. if (!this._glVendor) {
  11075. this._glVendor = "Unknown vendor";
  11076. }
  11077. if (!this._glRenderer) {
  11078. this._glRenderer = "Unknown renderer";
  11079. }
  11080. // Constants
  11081. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11082. if (this._gl.RGBA16F !== 0x881A) {
  11083. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11084. }
  11085. if (this._gl.RGBA32F !== 0x8814) {
  11086. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11087. }
  11088. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11089. this._gl.DEPTH24_STENCIL8 = 35056;
  11090. }
  11091. // Extensions
  11092. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11093. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11094. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11095. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11096. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11097. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11098. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11099. 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');
  11100. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11101. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11102. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11103. this._caps.highPrecisionShaderSupported = true;
  11104. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11105. if (this._caps.timerQuery) {
  11106. if (this._webGLVersion === 1) {
  11107. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11108. }
  11109. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11110. }
  11111. // Checks if some of the format renders first to allow the use of webgl inspector.
  11112. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11113. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11114. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11115. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11116. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11117. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11118. if (this._webGLVersion > 1) {
  11119. this._gl.HALF_FLOAT_OES = 0x140B;
  11120. }
  11121. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11122. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11123. // Draw buffers
  11124. if (this._webGLVersion > 1) {
  11125. this._caps.drawBuffersExtension = true;
  11126. }
  11127. else {
  11128. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11129. if (drawBuffersExtension !== null) {
  11130. this._caps.drawBuffersExtension = true;
  11131. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11132. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11133. for (var i = 0; i < 16; i++) {
  11134. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11135. }
  11136. }
  11137. else {
  11138. this._caps.drawBuffersExtension = false;
  11139. }
  11140. }
  11141. // Depth Texture
  11142. if (this._webGLVersion > 1) {
  11143. this._caps.depthTextureExtension = true;
  11144. }
  11145. else {
  11146. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11147. if (depthTextureExtension != null) {
  11148. this._caps.depthTextureExtension = true;
  11149. }
  11150. }
  11151. // Vertex array object
  11152. if (this._webGLVersion > 1) {
  11153. this._caps.vertexArrayObject = true;
  11154. }
  11155. else {
  11156. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11157. if (vertexArrayObjectExtension != null) {
  11158. this._caps.vertexArrayObject = true;
  11159. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11160. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11161. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11162. }
  11163. else {
  11164. this._caps.vertexArrayObject = false;
  11165. }
  11166. }
  11167. // Instances count
  11168. if (this._webGLVersion > 1) {
  11169. this._caps.instancedArrays = true;
  11170. }
  11171. else {
  11172. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11173. if (instanceExtension != null) {
  11174. this._caps.instancedArrays = true;
  11175. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11176. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11177. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11178. }
  11179. else {
  11180. this._caps.instancedArrays = false;
  11181. }
  11182. }
  11183. // Intelligently add supported compressed formats in order to check for.
  11184. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11185. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11186. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11187. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11188. if (this._caps.astc)
  11189. this.texturesSupported.push('-astc.ktx');
  11190. if (this._caps.s3tc)
  11191. this.texturesSupported.push('-dxt.ktx');
  11192. if (this._caps.pvrtc)
  11193. this.texturesSupported.push('-pvrtc.ktx');
  11194. if (this._caps.etc2)
  11195. this.texturesSupported.push('-etc2.ktx');
  11196. if (this._caps.etc1)
  11197. this.texturesSupported.push('-etc1.ktx');
  11198. if (this._gl.getShaderPrecisionFormat) {
  11199. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11200. if (highp) {
  11201. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11202. }
  11203. }
  11204. // Depth buffer
  11205. this.setDepthBuffer(true);
  11206. this.setDepthFunctionToLessOrEqual();
  11207. this.setDepthWrite(true);
  11208. // Texture maps
  11209. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11210. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11211. this._nextFreeTextureSlots.push(slot);
  11212. }
  11213. };
  11214. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11215. get: function () {
  11216. return this._webGLVersion;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11222. /**
  11223. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11224. */
  11225. get: function () {
  11226. return this._isStencilEnable;
  11227. },
  11228. enumerable: true,
  11229. configurable: true
  11230. });
  11231. Engine.prototype._prepareWorkingCanvas = function () {
  11232. if (this._workingCanvas) {
  11233. return;
  11234. }
  11235. this._workingCanvas = document.createElement("canvas");
  11236. var context = this._workingCanvas.getContext("2d");
  11237. if (context) {
  11238. this._workingContext = context;
  11239. }
  11240. };
  11241. Engine.prototype.resetTextureCache = function () {
  11242. for (var key in this._boundTexturesCache) {
  11243. var boundTexture = this._boundTexturesCache[key];
  11244. if (boundTexture) {
  11245. this._removeDesignatedSlot(boundTexture);
  11246. }
  11247. this._boundTexturesCache[key] = null;
  11248. }
  11249. if (!this.disableTextureBindingOptimization) {
  11250. this._nextFreeTextureSlots = [];
  11251. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11252. this._nextFreeTextureSlots.push(slot);
  11253. }
  11254. }
  11255. this._currentTextureChannel = -1;
  11256. };
  11257. Engine.prototype.isDeterministicLockStep = function () {
  11258. return this._deterministicLockstep;
  11259. };
  11260. Engine.prototype.getLockstepMaxSteps = function () {
  11261. return this._lockstepMaxSteps;
  11262. };
  11263. Engine.prototype.getGlInfo = function () {
  11264. return {
  11265. vendor: this._glVendor,
  11266. renderer: this._glRenderer,
  11267. version: this._glVersion
  11268. };
  11269. };
  11270. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11271. if (useScreen === void 0) { useScreen = false; }
  11272. var viewport = camera.viewport;
  11273. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11274. };
  11275. Engine.prototype.getRenderWidth = function (useScreen) {
  11276. if (useScreen === void 0) { useScreen = false; }
  11277. if (!useScreen && this._currentRenderTarget) {
  11278. return this._currentRenderTarget.width;
  11279. }
  11280. return this._gl.drawingBufferWidth;
  11281. };
  11282. Engine.prototype.getRenderHeight = function (useScreen) {
  11283. if (useScreen === void 0) { useScreen = false; }
  11284. if (!useScreen && this._currentRenderTarget) {
  11285. return this._currentRenderTarget.height;
  11286. }
  11287. return this._gl.drawingBufferHeight;
  11288. };
  11289. Engine.prototype.getRenderingCanvas = function () {
  11290. return this._renderingCanvas;
  11291. };
  11292. Engine.prototype.getRenderingCanvasClientRect = function () {
  11293. if (!this._renderingCanvas) {
  11294. return null;
  11295. }
  11296. return this._renderingCanvas.getBoundingClientRect();
  11297. };
  11298. Engine.prototype.setHardwareScalingLevel = function (level) {
  11299. this._hardwareScalingLevel = level;
  11300. this.resize();
  11301. };
  11302. Engine.prototype.getHardwareScalingLevel = function () {
  11303. return this._hardwareScalingLevel;
  11304. };
  11305. Engine.prototype.getLoadedTexturesCache = function () {
  11306. return this._internalTexturesCache;
  11307. };
  11308. Engine.prototype.getCaps = function () {
  11309. return this._caps;
  11310. };
  11311. Object.defineProperty(Engine.prototype, "drawCalls", {
  11312. /** The number of draw calls submitted last frame */
  11313. get: function () {
  11314. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11315. return 0;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11321. get: function () {
  11322. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11323. return null;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Engine.prototype.getDepthFunction = function () {
  11329. return this._depthCullingState.depthFunc;
  11330. };
  11331. Engine.prototype.setDepthFunction = function (depthFunc) {
  11332. this._depthCullingState.depthFunc = depthFunc;
  11333. };
  11334. Engine.prototype.setDepthFunctionToGreater = function () {
  11335. this._depthCullingState.depthFunc = this._gl.GREATER;
  11336. };
  11337. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11338. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11339. };
  11340. Engine.prototype.setDepthFunctionToLess = function () {
  11341. this._depthCullingState.depthFunc = this._gl.LESS;
  11342. };
  11343. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11344. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11345. };
  11346. Engine.prototype.getStencilBuffer = function () {
  11347. return this._stencilState.stencilTest;
  11348. };
  11349. Engine.prototype.setStencilBuffer = function (enable) {
  11350. this._stencilState.stencilTest = enable;
  11351. };
  11352. Engine.prototype.getStencilMask = function () {
  11353. return this._stencilState.stencilMask;
  11354. };
  11355. Engine.prototype.setStencilMask = function (mask) {
  11356. this._stencilState.stencilMask = mask;
  11357. };
  11358. Engine.prototype.getStencilFunction = function () {
  11359. return this._stencilState.stencilFunc;
  11360. };
  11361. Engine.prototype.getStencilFunctionReference = function () {
  11362. return this._stencilState.stencilFuncRef;
  11363. };
  11364. Engine.prototype.getStencilFunctionMask = function () {
  11365. return this._stencilState.stencilFuncMask;
  11366. };
  11367. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11368. this._stencilState.stencilFunc = stencilFunc;
  11369. };
  11370. Engine.prototype.setStencilFunctionReference = function (reference) {
  11371. this._stencilState.stencilFuncRef = reference;
  11372. };
  11373. Engine.prototype.setStencilFunctionMask = function (mask) {
  11374. this._stencilState.stencilFuncMask = mask;
  11375. };
  11376. Engine.prototype.getStencilOperationFail = function () {
  11377. return this._stencilState.stencilOpStencilFail;
  11378. };
  11379. Engine.prototype.getStencilOperationDepthFail = function () {
  11380. return this._stencilState.stencilOpDepthFail;
  11381. };
  11382. Engine.prototype.getStencilOperationPass = function () {
  11383. return this._stencilState.stencilOpStencilDepthPass;
  11384. };
  11385. Engine.prototype.setStencilOperationFail = function (operation) {
  11386. this._stencilState.stencilOpStencilFail = operation;
  11387. };
  11388. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11389. this._stencilState.stencilOpDepthFail = operation;
  11390. };
  11391. Engine.prototype.setStencilOperationPass = function (operation) {
  11392. this._stencilState.stencilOpStencilDepthPass = operation;
  11393. };
  11394. Engine.prototype.setDitheringState = function (value) {
  11395. if (value) {
  11396. this._gl.enable(this._gl.DITHER);
  11397. }
  11398. else {
  11399. this._gl.disable(this._gl.DITHER);
  11400. }
  11401. };
  11402. Engine.prototype.setRasterizerState = function (value) {
  11403. if (value) {
  11404. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11405. }
  11406. else {
  11407. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11408. }
  11409. };
  11410. /**
  11411. * stop executing a render loop function and remove it from the execution array
  11412. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11413. */
  11414. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11415. if (!renderFunction) {
  11416. this._activeRenderLoops = [];
  11417. return;
  11418. }
  11419. var index = this._activeRenderLoops.indexOf(renderFunction);
  11420. if (index >= 0) {
  11421. this._activeRenderLoops.splice(index, 1);
  11422. }
  11423. };
  11424. Engine.prototype._renderLoop = function () {
  11425. if (!this._contextWasLost) {
  11426. var shouldRender = true;
  11427. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11428. shouldRender = false;
  11429. }
  11430. if (shouldRender) {
  11431. // Start new frame
  11432. this.beginFrame();
  11433. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11434. var renderFunction = this._activeRenderLoops[index];
  11435. renderFunction();
  11436. }
  11437. // Present
  11438. this.endFrame();
  11439. }
  11440. }
  11441. if (this._activeRenderLoops.length > 0) {
  11442. // Register new frame
  11443. var requester = null;
  11444. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11445. requester = this._vrDisplay;
  11446. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11447. }
  11448. else {
  11449. this._renderingQueueLaunched = false;
  11450. }
  11451. };
  11452. /**
  11453. * Register and execute a render loop. The engine can have more than one render function.
  11454. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11455. * @example
  11456. * engine.runRenderLoop(function () {
  11457. * scene.render()
  11458. * })
  11459. */
  11460. Engine.prototype.runRenderLoop = function (renderFunction) {
  11461. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11462. return;
  11463. }
  11464. this._activeRenderLoops.push(renderFunction);
  11465. if (!this._renderingQueueLaunched) {
  11466. this._renderingQueueLaunched = true;
  11467. this._bindedRenderFunction = this._renderLoop.bind(this);
  11468. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11469. }
  11470. };
  11471. /**
  11472. * Toggle full screen mode.
  11473. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11474. * @param {any} options - an options object to be sent to the requestFullscreen function
  11475. */
  11476. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11477. if (this.isFullscreen) {
  11478. BABYLON.Tools.ExitFullscreen();
  11479. }
  11480. else {
  11481. this._pointerLockRequested = requestPointerLock;
  11482. if (this._renderingCanvas) {
  11483. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11484. }
  11485. }
  11486. };
  11487. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11488. if (stencil === void 0) { stencil = false; }
  11489. this.applyStates();
  11490. var mode = 0;
  11491. if (backBuffer && color) {
  11492. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11493. mode |= this._gl.COLOR_BUFFER_BIT;
  11494. }
  11495. if (depth) {
  11496. this._gl.clearDepth(1.0);
  11497. mode |= this._gl.DEPTH_BUFFER_BIT;
  11498. }
  11499. if (stencil) {
  11500. this._gl.clearStencil(0);
  11501. mode |= this._gl.STENCIL_BUFFER_BIT;
  11502. }
  11503. this._gl.clear(mode);
  11504. };
  11505. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11506. var gl = this._gl;
  11507. // Save state
  11508. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11509. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11510. // Change state
  11511. gl.enable(gl.SCISSOR_TEST);
  11512. gl.scissor(x, y, width, height);
  11513. // Clear
  11514. this.clear(clearColor, true, true, true);
  11515. // Restore state
  11516. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11517. if (curScissor === true) {
  11518. gl.enable(gl.SCISSOR_TEST);
  11519. }
  11520. else {
  11521. gl.disable(gl.SCISSOR_TEST);
  11522. }
  11523. };
  11524. /**
  11525. * Set the WebGL's viewport
  11526. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11527. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11528. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11529. */
  11530. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11531. var width = requiredWidth || this.getRenderWidth();
  11532. var height = requiredHeight || this.getRenderHeight();
  11533. var x = viewport.x || 0;
  11534. var y = viewport.y || 0;
  11535. this._cachedViewport = viewport;
  11536. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11537. };
  11538. /**
  11539. * Directly set the WebGL Viewport
  11540. * The x, y, width & height are directly passed to the WebGL call
  11541. * @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.
  11542. */
  11543. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11544. var currentViewport = this._cachedViewport;
  11545. this._cachedViewport = null;
  11546. this._gl.viewport(x, y, width, height);
  11547. return currentViewport;
  11548. };
  11549. Engine.prototype.beginFrame = function () {
  11550. this.onBeginFrameObservable.notifyObservers(this);
  11551. this._measureFps();
  11552. };
  11553. Engine.prototype.endFrame = function () {
  11554. //force a flush in case we are using a bad OS.
  11555. if (this._badOS) {
  11556. this.flushFramebuffer();
  11557. }
  11558. //submit frame to the vr device, if enabled
  11559. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11560. // TODO: We should only submit the frame if we read frameData successfully.
  11561. this._vrDisplay.submitFrame();
  11562. }
  11563. this.onEndFrameObservable.notifyObservers(this);
  11564. };
  11565. /**
  11566. * resize the view according to the canvas' size.
  11567. * @example
  11568. * window.addEventListener("resize", function () {
  11569. * engine.resize();
  11570. * });
  11571. */
  11572. Engine.prototype.resize = function () {
  11573. // We're not resizing the size of the canvas while in VR mode & presenting
  11574. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11575. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11576. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11577. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11578. }
  11579. };
  11580. /**
  11581. * force a specific size of the canvas
  11582. * @param {number} width - the new canvas' width
  11583. * @param {number} height - the new canvas' height
  11584. */
  11585. Engine.prototype.setSize = function (width, height) {
  11586. if (!this._renderingCanvas) {
  11587. return;
  11588. }
  11589. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11590. return;
  11591. }
  11592. this._renderingCanvas.width = width;
  11593. this._renderingCanvas.height = height;
  11594. for (var index = 0; index < this.scenes.length; index++) {
  11595. var scene = this.scenes[index];
  11596. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11597. var cam = scene.cameras[camIndex];
  11598. cam._currentRenderId = 0;
  11599. }
  11600. }
  11601. if (this.onResizeObservable.hasObservers) {
  11602. this.onResizeObservable.notifyObservers(this);
  11603. }
  11604. };
  11605. // WebVR functions
  11606. Engine.prototype.isVRDevicePresent = function () {
  11607. return !!this._vrDisplay;
  11608. };
  11609. Engine.prototype.getVRDevice = function () {
  11610. return this._vrDisplay;
  11611. };
  11612. /**
  11613. * Initializes a webVR display and starts listening to display change events.
  11614. * The onVRDisplayChangedObservable will be notified upon these changes.
  11615. * @returns The onVRDisplayChangedObservable.
  11616. */
  11617. Engine.prototype.initWebVR = function () {
  11618. this.initWebVRAsync();
  11619. return this.onVRDisplayChangedObservable;
  11620. };
  11621. /**
  11622. * Initializes a webVR display and starts listening to display change events.
  11623. * The onVRDisplayChangedObservable will be notified upon these changes.
  11624. * @returns A promise containing a VRDisplay and if vr is supported.
  11625. */
  11626. Engine.prototype.initWebVRAsync = function () {
  11627. var _this = this;
  11628. var notifyObservers = function () {
  11629. var eventArgs = {
  11630. vrDisplay: _this._vrDisplay,
  11631. vrSupported: _this._vrSupported
  11632. };
  11633. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11634. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11635. };
  11636. if (!this._onVrDisplayConnect) {
  11637. this._onVrDisplayConnect = function (event) {
  11638. _this._vrDisplay = event.display;
  11639. notifyObservers();
  11640. };
  11641. this._onVrDisplayDisconnect = function () {
  11642. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11643. _this._vrDisplay = undefined;
  11644. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11645. notifyObservers();
  11646. };
  11647. this._onVrDisplayPresentChange = function () {
  11648. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11649. };
  11650. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11651. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11652. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11653. }
  11654. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11655. this._webVRInitPromise.then(notifyObservers);
  11656. return this._webVRInitPromise;
  11657. };
  11658. Engine.prototype.enableVR = function () {
  11659. var _this = this;
  11660. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11661. var onResolved = function () {
  11662. _this.onVRRequestPresentComplete.notifyObservers(true);
  11663. _this._onVRFullScreenTriggered();
  11664. };
  11665. var onRejected = function () {
  11666. _this.onVRRequestPresentComplete.notifyObservers(false);
  11667. };
  11668. this.onVRRequestPresentStart.notifyObservers(this);
  11669. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11670. }
  11671. };
  11672. Engine.prototype.disableVR = function () {
  11673. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11674. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11675. }
  11676. };
  11677. Engine.prototype._getVRDisplaysAsync = function () {
  11678. var _this = this;
  11679. return new Promise(function (res, rej) {
  11680. if (navigator.getVRDisplays) {
  11681. navigator.getVRDisplays().then(function (devices) {
  11682. _this._vrSupported = true;
  11683. // note that devices may actually be an empty array. This is fine;
  11684. // we expect this._vrDisplay to be undefined in this case.
  11685. _this._vrDisplay = devices[0];
  11686. res({
  11687. vrDisplay: _this._vrDisplay,
  11688. vrSupported: _this._vrSupported
  11689. });
  11690. });
  11691. }
  11692. else {
  11693. _this._vrDisplay = undefined;
  11694. _this._vrSupported = false;
  11695. res({
  11696. vrDisplay: _this._vrDisplay,
  11697. vrSupported: _this._vrSupported
  11698. });
  11699. }
  11700. });
  11701. };
  11702. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11703. if (this._currentRenderTarget) {
  11704. this.unBindFramebuffer(this._currentRenderTarget);
  11705. }
  11706. this._currentRenderTarget = texture;
  11707. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11708. var gl = this._gl;
  11709. if (texture.isCube) {
  11710. if (faceIndex === undefined) {
  11711. faceIndex = 0;
  11712. }
  11713. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11714. }
  11715. if (this._cachedViewport && !forceFullscreenViewport) {
  11716. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11717. }
  11718. else {
  11719. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11720. }
  11721. this.wipeCaches();
  11722. };
  11723. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11724. if (this._currentFramebuffer !== framebuffer) {
  11725. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11726. this._currentFramebuffer = framebuffer;
  11727. }
  11728. };
  11729. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11730. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11731. this._currentRenderTarget = null;
  11732. // If MSAA, we need to bitblt back to main texture
  11733. var gl = this._gl;
  11734. if (texture._MSAAFramebuffer) {
  11735. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11736. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11737. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11738. }
  11739. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11740. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11741. gl.generateMipmap(gl.TEXTURE_2D);
  11742. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11743. }
  11744. if (onBeforeUnbind) {
  11745. if (texture._MSAAFramebuffer) {
  11746. // Bind the correct framebuffer
  11747. this.bindUnboundFramebuffer(texture._framebuffer);
  11748. }
  11749. onBeforeUnbind();
  11750. }
  11751. this.bindUnboundFramebuffer(null);
  11752. };
  11753. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11754. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11755. this._currentRenderTarget = null;
  11756. // If MSAA, we need to bitblt back to main texture
  11757. var gl = this._gl;
  11758. if (textures[0]._MSAAFramebuffer) {
  11759. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11760. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11761. var attachments = textures[0]._attachments;
  11762. if (!attachments) {
  11763. attachments = new Array(textures.length);
  11764. textures[0]._attachments = attachments;
  11765. }
  11766. for (var i = 0; i < textures.length; i++) {
  11767. var texture = textures[i];
  11768. for (var j = 0; j < attachments.length; j++) {
  11769. attachments[j] = gl.NONE;
  11770. }
  11771. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11772. gl.readBuffer(attachments[i]);
  11773. gl.drawBuffers(attachments);
  11774. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11775. }
  11776. for (var i = 0; i < attachments.length; i++) {
  11777. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11778. }
  11779. gl.drawBuffers(attachments);
  11780. }
  11781. for (var i = 0; i < textures.length; i++) {
  11782. var texture = textures[i];
  11783. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11784. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11785. gl.generateMipmap(gl.TEXTURE_2D);
  11786. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11787. }
  11788. }
  11789. if (onBeforeUnbind) {
  11790. if (textures[0]._MSAAFramebuffer) {
  11791. // Bind the correct framebuffer
  11792. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11793. }
  11794. onBeforeUnbind();
  11795. }
  11796. this.bindUnboundFramebuffer(null);
  11797. };
  11798. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11799. if (texture.generateMipMaps) {
  11800. var gl = this._gl;
  11801. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11802. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11803. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11804. }
  11805. };
  11806. Engine.prototype.flushFramebuffer = function () {
  11807. this._gl.flush();
  11808. };
  11809. Engine.prototype.restoreDefaultFramebuffer = function () {
  11810. if (this._currentRenderTarget) {
  11811. this.unBindFramebuffer(this._currentRenderTarget);
  11812. }
  11813. else {
  11814. this.bindUnboundFramebuffer(null);
  11815. }
  11816. if (this._cachedViewport) {
  11817. this.setViewport(this._cachedViewport);
  11818. }
  11819. this.wipeCaches();
  11820. };
  11821. // UBOs
  11822. Engine.prototype.createUniformBuffer = function (elements) {
  11823. var ubo = this._gl.createBuffer();
  11824. if (!ubo) {
  11825. throw new Error("Unable to create uniform buffer");
  11826. }
  11827. this.bindUniformBuffer(ubo);
  11828. if (elements instanceof Float32Array) {
  11829. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11830. }
  11831. else {
  11832. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11833. }
  11834. this.bindUniformBuffer(null);
  11835. ubo.references = 1;
  11836. return ubo;
  11837. };
  11838. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11839. var ubo = this._gl.createBuffer();
  11840. if (!ubo) {
  11841. throw new Error("Unable to create dynamic uniform buffer");
  11842. }
  11843. this.bindUniformBuffer(ubo);
  11844. if (elements instanceof Float32Array) {
  11845. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11846. }
  11847. else {
  11848. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11849. }
  11850. this.bindUniformBuffer(null);
  11851. ubo.references = 1;
  11852. return ubo;
  11853. };
  11854. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11855. this.bindUniformBuffer(uniformBuffer);
  11856. if (offset === undefined) {
  11857. offset = 0;
  11858. }
  11859. if (count === undefined) {
  11860. if (elements instanceof Float32Array) {
  11861. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11862. }
  11863. else {
  11864. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11865. }
  11866. }
  11867. else {
  11868. if (elements instanceof Float32Array) {
  11869. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11870. }
  11871. else {
  11872. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11873. }
  11874. }
  11875. this.bindUniformBuffer(null);
  11876. };
  11877. // VBOs
  11878. Engine.prototype._resetVertexBufferBinding = function () {
  11879. this.bindArrayBuffer(null);
  11880. this._cachedVertexBuffers = null;
  11881. };
  11882. Engine.prototype.createVertexBuffer = function (vertices) {
  11883. var vbo = this._gl.createBuffer();
  11884. if (!vbo) {
  11885. throw new Error("Unable to create vertex buffer");
  11886. }
  11887. this.bindArrayBuffer(vbo);
  11888. if (vertices instanceof Float32Array) {
  11889. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11890. }
  11891. else {
  11892. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11893. }
  11894. this._resetVertexBufferBinding();
  11895. vbo.references = 1;
  11896. return vbo;
  11897. };
  11898. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11899. var vbo = this._gl.createBuffer();
  11900. if (!vbo) {
  11901. throw new Error("Unable to create dynamic vertex buffer");
  11902. }
  11903. this.bindArrayBuffer(vbo);
  11904. if (vertices instanceof Float32Array) {
  11905. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11906. }
  11907. else {
  11908. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11909. }
  11910. this._resetVertexBufferBinding();
  11911. vbo.references = 1;
  11912. return vbo;
  11913. };
  11914. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11915. if (offset === void 0) { offset = 0; }
  11916. // Force cache update
  11917. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11918. this.bindIndexBuffer(indexBuffer);
  11919. var arrayBuffer;
  11920. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11921. arrayBuffer = indices;
  11922. }
  11923. else {
  11924. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11925. }
  11926. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11927. this._resetIndexBufferBinding();
  11928. };
  11929. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11930. this.bindArrayBuffer(vertexBuffer);
  11931. if (offset === undefined) {
  11932. offset = 0;
  11933. }
  11934. if (count === undefined) {
  11935. if (vertices instanceof Float32Array) {
  11936. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11937. }
  11938. else {
  11939. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11940. }
  11941. }
  11942. else {
  11943. if (vertices instanceof Float32Array) {
  11944. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11945. }
  11946. else {
  11947. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11948. }
  11949. }
  11950. this._resetVertexBufferBinding();
  11951. };
  11952. Engine.prototype._resetIndexBufferBinding = function () {
  11953. this.bindIndexBuffer(null);
  11954. this._cachedIndexBuffer = null;
  11955. };
  11956. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11957. var vbo = this._gl.createBuffer();
  11958. if (!vbo) {
  11959. throw new Error("Unable to create index buffer");
  11960. }
  11961. this.bindIndexBuffer(vbo);
  11962. // Check for 32 bits indices
  11963. var arrayBuffer;
  11964. var need32Bits = false;
  11965. if (indices instanceof Uint16Array) {
  11966. arrayBuffer = indices;
  11967. }
  11968. else {
  11969. //check 32 bit support
  11970. if (this._caps.uintIndices) {
  11971. if (indices instanceof Uint32Array) {
  11972. arrayBuffer = indices;
  11973. need32Bits = true;
  11974. }
  11975. else {
  11976. //number[] or Int32Array, check if 32 bit is necessary
  11977. for (var index = 0; index < indices.length; index++) {
  11978. if (indices[index] > 65535) {
  11979. need32Bits = true;
  11980. break;
  11981. }
  11982. }
  11983. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11984. }
  11985. }
  11986. else {
  11987. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11988. arrayBuffer = new Uint16Array(indices);
  11989. }
  11990. }
  11991. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11992. this._resetIndexBufferBinding();
  11993. vbo.references = 1;
  11994. vbo.is32Bits = need32Bits;
  11995. return vbo;
  11996. };
  11997. Engine.prototype.bindArrayBuffer = function (buffer) {
  11998. if (!this._vaoRecordInProgress) {
  11999. this._unbindVertexArrayObject();
  12000. }
  12001. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12002. };
  12003. Engine.prototype.bindUniformBuffer = function (buffer) {
  12004. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12005. };
  12006. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12007. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12008. };
  12009. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12010. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12011. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12012. };
  12013. ;
  12014. Engine.prototype.bindIndexBuffer = function (buffer) {
  12015. if (!this._vaoRecordInProgress) {
  12016. this._unbindVertexArrayObject();
  12017. }
  12018. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12019. };
  12020. Engine.prototype.bindBuffer = function (buffer, target) {
  12021. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12022. this._gl.bindBuffer(target, buffer);
  12023. this._currentBoundBuffer[target] = buffer;
  12024. }
  12025. };
  12026. Engine.prototype.updateArrayBuffer = function (data) {
  12027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12028. };
  12029. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12030. var pointer = this._currentBufferPointers[indx];
  12031. var changed = false;
  12032. if (!pointer.active) {
  12033. changed = true;
  12034. pointer.active = true;
  12035. pointer.index = indx;
  12036. pointer.size = size;
  12037. pointer.type = type;
  12038. pointer.normalized = normalized;
  12039. pointer.stride = stride;
  12040. pointer.offset = offset;
  12041. pointer.buffer = buffer;
  12042. }
  12043. else {
  12044. if (pointer.buffer !== buffer) {
  12045. pointer.buffer = buffer;
  12046. changed = true;
  12047. }
  12048. if (pointer.size !== size) {
  12049. pointer.size = size;
  12050. changed = true;
  12051. }
  12052. if (pointer.type !== type) {
  12053. pointer.type = type;
  12054. changed = true;
  12055. }
  12056. if (pointer.normalized !== normalized) {
  12057. pointer.normalized = normalized;
  12058. changed = true;
  12059. }
  12060. if (pointer.stride !== stride) {
  12061. pointer.stride = stride;
  12062. changed = true;
  12063. }
  12064. if (pointer.offset !== offset) {
  12065. pointer.offset = offset;
  12066. changed = true;
  12067. }
  12068. }
  12069. if (changed || this._vaoRecordInProgress) {
  12070. this.bindArrayBuffer(buffer);
  12071. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12072. }
  12073. };
  12074. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12075. if (indexBuffer == null) {
  12076. return;
  12077. }
  12078. if (this._cachedIndexBuffer !== indexBuffer) {
  12079. this._cachedIndexBuffer = indexBuffer;
  12080. this.bindIndexBuffer(indexBuffer);
  12081. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12082. }
  12083. };
  12084. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12085. var attributes = effect.getAttributesNames();
  12086. if (!this._vaoRecordInProgress) {
  12087. this._unbindVertexArrayObject();
  12088. }
  12089. this.unbindAllAttributes();
  12090. for (var index = 0; index < attributes.length; index++) {
  12091. var order = effect.getAttributeLocation(index);
  12092. if (order >= 0) {
  12093. var vertexBuffer = vertexBuffers[attributes[index]];
  12094. if (!vertexBuffer) {
  12095. continue;
  12096. }
  12097. this._gl.enableVertexAttribArray(order);
  12098. if (!this._vaoRecordInProgress) {
  12099. this._vertexAttribArraysEnabled[order] = true;
  12100. }
  12101. var buffer = vertexBuffer.getBuffer();
  12102. if (buffer) {
  12103. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12104. if (vertexBuffer.getIsInstanced()) {
  12105. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12106. if (!this._vaoRecordInProgress) {
  12107. this._currentInstanceLocations.push(order);
  12108. this._currentInstanceBuffers.push(buffer);
  12109. }
  12110. }
  12111. }
  12112. }
  12113. }
  12114. };
  12115. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12116. var vao = this._gl.createVertexArray();
  12117. this._vaoRecordInProgress = true;
  12118. this._gl.bindVertexArray(vao);
  12119. this._mustWipeVertexAttributes = true;
  12120. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12121. this.bindIndexBuffer(indexBuffer);
  12122. this._vaoRecordInProgress = false;
  12123. this._gl.bindVertexArray(null);
  12124. return vao;
  12125. };
  12126. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12127. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12128. this._cachedVertexArrayObject = vertexArrayObject;
  12129. this._gl.bindVertexArray(vertexArrayObject);
  12130. this._cachedVertexBuffers = null;
  12131. this._cachedIndexBuffer = null;
  12132. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12133. this._mustWipeVertexAttributes = true;
  12134. }
  12135. };
  12136. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12137. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12138. this._cachedVertexBuffers = vertexBuffer;
  12139. this._cachedEffectForVertexBuffers = effect;
  12140. var attributesCount = effect.getAttributesCount();
  12141. this._unbindVertexArrayObject();
  12142. this.unbindAllAttributes();
  12143. var offset = 0;
  12144. for (var index = 0; index < attributesCount; index++) {
  12145. if (index < vertexDeclaration.length) {
  12146. var order = effect.getAttributeLocation(index);
  12147. if (order >= 0) {
  12148. this._gl.enableVertexAttribArray(order);
  12149. this._vertexAttribArraysEnabled[order] = true;
  12150. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12151. }
  12152. offset += vertexDeclaration[index] * 4;
  12153. }
  12154. }
  12155. }
  12156. this._bindIndexBufferWithCache(indexBuffer);
  12157. };
  12158. Engine.prototype._unbindVertexArrayObject = function () {
  12159. if (!this._cachedVertexArrayObject) {
  12160. return;
  12161. }
  12162. this._cachedVertexArrayObject = null;
  12163. this._gl.bindVertexArray(null);
  12164. };
  12165. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12166. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12167. this._cachedVertexBuffers = vertexBuffers;
  12168. this._cachedEffectForVertexBuffers = effect;
  12169. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12170. }
  12171. this._bindIndexBufferWithCache(indexBuffer);
  12172. };
  12173. Engine.prototype.unbindInstanceAttributes = function () {
  12174. var boundBuffer;
  12175. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12176. var instancesBuffer = this._currentInstanceBuffers[i];
  12177. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12178. boundBuffer = instancesBuffer;
  12179. this.bindArrayBuffer(instancesBuffer);
  12180. }
  12181. var offsetLocation = this._currentInstanceLocations[i];
  12182. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12183. }
  12184. this._currentInstanceBuffers.length = 0;
  12185. this._currentInstanceLocations.length = 0;
  12186. };
  12187. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12188. this._gl.deleteVertexArray(vao);
  12189. };
  12190. Engine.prototype._releaseBuffer = function (buffer) {
  12191. buffer.references--;
  12192. if (buffer.references === 0) {
  12193. this._gl.deleteBuffer(buffer);
  12194. return true;
  12195. }
  12196. return false;
  12197. };
  12198. Engine.prototype.createInstancesBuffer = function (capacity) {
  12199. var buffer = this._gl.createBuffer();
  12200. if (!buffer) {
  12201. throw new Error("Unable to create instance buffer");
  12202. }
  12203. buffer.capacity = capacity;
  12204. this.bindArrayBuffer(buffer);
  12205. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12206. return buffer;
  12207. };
  12208. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12209. this._gl.deleteBuffer(buffer);
  12210. };
  12211. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12212. this.bindArrayBuffer(instancesBuffer);
  12213. if (data) {
  12214. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12215. }
  12216. if (offsetLocations[0].index !== undefined) {
  12217. var stride = 0;
  12218. for (var i = 0; i < offsetLocations.length; i++) {
  12219. var ai = offsetLocations[i];
  12220. stride += ai.attributeSize * 4;
  12221. }
  12222. for (var i = 0; i < offsetLocations.length; i++) {
  12223. var ai = offsetLocations[i];
  12224. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12225. this._gl.enableVertexAttribArray(ai.index);
  12226. this._vertexAttribArraysEnabled[ai.index] = true;
  12227. }
  12228. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12229. this._gl.vertexAttribDivisor(ai.index, 1);
  12230. this._currentInstanceLocations.push(ai.index);
  12231. this._currentInstanceBuffers.push(instancesBuffer);
  12232. }
  12233. }
  12234. else {
  12235. for (var index = 0; index < 4; index++) {
  12236. var offsetLocation = offsetLocations[index];
  12237. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12238. this._gl.enableVertexAttribArray(offsetLocation);
  12239. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12240. }
  12241. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12242. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12243. this._currentInstanceLocations.push(offsetLocation);
  12244. this._currentInstanceBuffers.push(instancesBuffer);
  12245. }
  12246. }
  12247. };
  12248. Engine.prototype.applyStates = function () {
  12249. this._depthCullingState.apply(this._gl);
  12250. this._stencilState.apply(this._gl);
  12251. this._alphaState.apply(this._gl);
  12252. };
  12253. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12254. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12255. };
  12256. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12257. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12258. };
  12259. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12260. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12261. };
  12262. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12263. // Apply states
  12264. this.applyStates();
  12265. this._drawCalls.addCount(1, false);
  12266. // Render
  12267. var drawMode = this.DrawMode(fillMode);
  12268. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12269. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12270. if (instancesCount) {
  12271. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12272. }
  12273. else {
  12274. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12275. }
  12276. };
  12277. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12278. // Apply states
  12279. this.applyStates();
  12280. this._drawCalls.addCount(1, false);
  12281. var drawMode = this.DrawMode(fillMode);
  12282. if (instancesCount) {
  12283. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12284. }
  12285. else {
  12286. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12287. }
  12288. };
  12289. Engine.prototype.DrawMode = function (fillMode) {
  12290. switch (fillMode) {
  12291. // Triangle views
  12292. case BABYLON.Material.TriangleFillMode:
  12293. return this._gl.TRIANGLES;
  12294. case BABYLON.Material.PointFillMode:
  12295. return this._gl.POINTS;
  12296. case BABYLON.Material.WireFrameFillMode:
  12297. return this._gl.LINES;
  12298. // Draw modes
  12299. case BABYLON.Material.PointListDrawMode:
  12300. return this._gl.POINTS;
  12301. case BABYLON.Material.LineListDrawMode:
  12302. return this._gl.LINES;
  12303. case BABYLON.Material.LineLoopDrawMode:
  12304. return this._gl.LINE_LOOP;
  12305. case BABYLON.Material.LineStripDrawMode:
  12306. return this._gl.LINE_STRIP;
  12307. case BABYLON.Material.TriangleStripDrawMode:
  12308. return this._gl.TRIANGLE_STRIP;
  12309. case BABYLON.Material.TriangleFanDrawMode:
  12310. return this._gl.TRIANGLE_FAN;
  12311. default:
  12312. return this._gl.TRIANGLES;
  12313. }
  12314. };
  12315. // Shaders
  12316. Engine.prototype._releaseEffect = function (effect) {
  12317. if (this._compiledEffects[effect._key]) {
  12318. delete this._compiledEffects[effect._key];
  12319. this._deleteProgram(effect.getProgram());
  12320. }
  12321. };
  12322. Engine.prototype._deleteProgram = function (program) {
  12323. if (program) {
  12324. program.__SPECTOR_rebuildProgram = null;
  12325. if (program.transformFeedback) {
  12326. this.deleteTransformFeedback(program.transformFeedback);
  12327. program.transformFeedback = null;
  12328. }
  12329. this._gl.deleteProgram(program);
  12330. }
  12331. };
  12332. /**
  12333. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12334. * @param samplers An array of string used to represent textures
  12335. */
  12336. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12337. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12338. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12339. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12340. if (this._compiledEffects[name]) {
  12341. var compiledEffect = this._compiledEffects[name];
  12342. if (onCompiled && compiledEffect.isReady()) {
  12343. onCompiled(compiledEffect);
  12344. }
  12345. return compiledEffect;
  12346. }
  12347. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12348. effect._key = name;
  12349. this._compiledEffects[name] = effect;
  12350. return effect;
  12351. };
  12352. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12353. if (uniformsNames === void 0) { uniformsNames = []; }
  12354. if (samplers === void 0) { samplers = []; }
  12355. if (defines === void 0) { defines = ""; }
  12356. return this.createEffect({
  12357. vertex: "particles",
  12358. fragmentElement: fragmentName
  12359. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12360. };
  12361. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12362. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12363. context = context || this._gl;
  12364. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12365. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12366. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12367. };
  12368. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12369. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12370. context = context || this._gl;
  12371. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12372. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12373. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12374. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12375. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12376. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12377. return program;
  12378. };
  12379. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12380. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12381. var shaderProgram = context.createProgram();
  12382. if (!shaderProgram) {
  12383. throw new Error("Unable to create program");
  12384. }
  12385. context.attachShader(shaderProgram, vertexShader);
  12386. context.attachShader(shaderProgram, fragmentShader);
  12387. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12388. var transformFeedback = this.createTransformFeedback();
  12389. this.bindTransformFeedback(transformFeedback);
  12390. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12391. shaderProgram.transformFeedback = transformFeedback;
  12392. }
  12393. context.linkProgram(shaderProgram);
  12394. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12395. this.bindTransformFeedback(null);
  12396. }
  12397. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12398. if (!linked) {
  12399. context.validateProgram(shaderProgram);
  12400. var error = context.getProgramInfoLog(shaderProgram);
  12401. if (error) {
  12402. throw new Error(error);
  12403. }
  12404. }
  12405. context.deleteShader(vertexShader);
  12406. context.deleteShader(fragmentShader);
  12407. return shaderProgram;
  12408. };
  12409. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12410. var results = new Array();
  12411. for (var index = 0; index < uniformsNames.length; index++) {
  12412. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12413. }
  12414. return results;
  12415. };
  12416. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12417. var results = [];
  12418. for (var index = 0; index < attributesNames.length; index++) {
  12419. try {
  12420. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12421. }
  12422. catch (e) {
  12423. results.push(-1);
  12424. }
  12425. }
  12426. return results;
  12427. };
  12428. Engine.prototype.enableEffect = function (effect) {
  12429. if (!effect) {
  12430. return;
  12431. }
  12432. // Use program
  12433. this.bindSamplers(effect);
  12434. this._currentEffect = effect;
  12435. if (effect.onBind) {
  12436. effect.onBind(effect);
  12437. }
  12438. effect.onBindObservable.notifyObservers(effect);
  12439. };
  12440. Engine.prototype.setIntArray = function (uniform, array) {
  12441. if (!uniform)
  12442. return;
  12443. this._gl.uniform1iv(uniform, array);
  12444. };
  12445. Engine.prototype.setIntArray2 = function (uniform, array) {
  12446. if (!uniform || array.length % 2 !== 0)
  12447. return;
  12448. this._gl.uniform2iv(uniform, array);
  12449. };
  12450. Engine.prototype.setIntArray3 = function (uniform, array) {
  12451. if (!uniform || array.length % 3 !== 0)
  12452. return;
  12453. this._gl.uniform3iv(uniform, array);
  12454. };
  12455. Engine.prototype.setIntArray4 = function (uniform, array) {
  12456. if (!uniform || array.length % 4 !== 0)
  12457. return;
  12458. this._gl.uniform4iv(uniform, array);
  12459. };
  12460. Engine.prototype.setFloatArray = function (uniform, array) {
  12461. if (!uniform)
  12462. return;
  12463. this._gl.uniform1fv(uniform, array);
  12464. };
  12465. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12466. if (!uniform || array.length % 2 !== 0)
  12467. return;
  12468. this._gl.uniform2fv(uniform, array);
  12469. };
  12470. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12471. if (!uniform || array.length % 3 !== 0)
  12472. return;
  12473. this._gl.uniform3fv(uniform, array);
  12474. };
  12475. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12476. if (!uniform || array.length % 4 !== 0)
  12477. return;
  12478. this._gl.uniform4fv(uniform, array);
  12479. };
  12480. Engine.prototype.setArray = function (uniform, array) {
  12481. if (!uniform)
  12482. return;
  12483. this._gl.uniform1fv(uniform, array);
  12484. };
  12485. Engine.prototype.setArray2 = function (uniform, array) {
  12486. if (!uniform || array.length % 2 !== 0)
  12487. return;
  12488. this._gl.uniform2fv(uniform, array);
  12489. };
  12490. Engine.prototype.setArray3 = function (uniform, array) {
  12491. if (!uniform || array.length % 3 !== 0)
  12492. return;
  12493. this._gl.uniform3fv(uniform, array);
  12494. };
  12495. Engine.prototype.setArray4 = function (uniform, array) {
  12496. if (!uniform || array.length % 4 !== 0)
  12497. return;
  12498. this._gl.uniform4fv(uniform, array);
  12499. };
  12500. Engine.prototype.setMatrices = function (uniform, matrices) {
  12501. if (!uniform)
  12502. return;
  12503. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12504. };
  12505. Engine.prototype.setMatrix = function (uniform, matrix) {
  12506. if (!uniform)
  12507. return;
  12508. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12509. };
  12510. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12511. if (!uniform)
  12512. return;
  12513. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12514. };
  12515. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12516. if (!uniform)
  12517. return;
  12518. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12519. };
  12520. Engine.prototype.setInt = function (uniform, value) {
  12521. if (!uniform)
  12522. return;
  12523. this._gl.uniform1i(uniform, value);
  12524. };
  12525. Engine.prototype.setFloat = function (uniform, value) {
  12526. if (!uniform)
  12527. return;
  12528. this._gl.uniform1f(uniform, value);
  12529. };
  12530. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12531. if (!uniform)
  12532. return;
  12533. this._gl.uniform2f(uniform, x, y);
  12534. };
  12535. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12536. if (!uniform)
  12537. return;
  12538. this._gl.uniform3f(uniform, x, y, z);
  12539. };
  12540. Engine.prototype.setBool = function (uniform, bool) {
  12541. if (!uniform)
  12542. return;
  12543. this._gl.uniform1i(uniform, bool);
  12544. };
  12545. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12546. if (!uniform)
  12547. return;
  12548. this._gl.uniform4f(uniform, x, y, z, w);
  12549. };
  12550. Engine.prototype.setColor3 = function (uniform, color3) {
  12551. if (!uniform)
  12552. return;
  12553. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12554. };
  12555. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12556. if (!uniform)
  12557. return;
  12558. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12559. };
  12560. /**
  12561. * Sets a Color4 on a uniform variable
  12562. * @param uniform defines the uniform location
  12563. * @param color4 defines the value to be set
  12564. */
  12565. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12566. if (!uniform)
  12567. return;
  12568. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12569. };
  12570. // States
  12571. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12572. if (zOffset === void 0) { zOffset = 0; }
  12573. if (reverseSide === void 0) { reverseSide = false; }
  12574. // Culling
  12575. if (this._depthCullingState.cull !== culling || force) {
  12576. this._depthCullingState.cull = culling;
  12577. }
  12578. // Cull face
  12579. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12580. if (this._depthCullingState.cullFace !== cullFace || force) {
  12581. this._depthCullingState.cullFace = cullFace;
  12582. }
  12583. // Z offset
  12584. this.setZOffset(zOffset);
  12585. // Front face
  12586. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12587. if (this._depthCullingState.frontFace !== frontFace || force) {
  12588. this._depthCullingState.frontFace = frontFace;
  12589. }
  12590. };
  12591. Engine.prototype.setZOffset = function (value) {
  12592. this._depthCullingState.zOffset = value;
  12593. };
  12594. Engine.prototype.getZOffset = function () {
  12595. return this._depthCullingState.zOffset;
  12596. };
  12597. Engine.prototype.setDepthBuffer = function (enable) {
  12598. this._depthCullingState.depthTest = enable;
  12599. };
  12600. Engine.prototype.getDepthWrite = function () {
  12601. return this._depthCullingState.depthMask;
  12602. };
  12603. Engine.prototype.setDepthWrite = function (enable) {
  12604. this._depthCullingState.depthMask = enable;
  12605. };
  12606. Engine.prototype.setColorWrite = function (enable) {
  12607. this._gl.colorMask(enable, enable, enable, enable);
  12608. this._colorWrite = enable;
  12609. };
  12610. Engine.prototype.getColorWrite = function () {
  12611. return this._colorWrite;
  12612. };
  12613. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12614. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12615. };
  12616. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12617. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12618. if (this._alphaMode === mode) {
  12619. return;
  12620. }
  12621. switch (mode) {
  12622. case Engine.ALPHA_DISABLE:
  12623. this._alphaState.alphaBlend = false;
  12624. break;
  12625. case Engine.ALPHA_PREMULTIPLIED:
  12626. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12627. this._alphaState.alphaBlend = true;
  12628. break;
  12629. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12630. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12631. this._alphaState.alphaBlend = true;
  12632. break;
  12633. case Engine.ALPHA_COMBINE:
  12634. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12635. this._alphaState.alphaBlend = true;
  12636. break;
  12637. case Engine.ALPHA_ONEONE:
  12638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12639. this._alphaState.alphaBlend = true;
  12640. break;
  12641. case Engine.ALPHA_ADD:
  12642. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12643. this._alphaState.alphaBlend = true;
  12644. break;
  12645. case Engine.ALPHA_SUBTRACT:
  12646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12647. this._alphaState.alphaBlend = true;
  12648. break;
  12649. case Engine.ALPHA_MULTIPLY:
  12650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12651. this._alphaState.alphaBlend = true;
  12652. break;
  12653. case Engine.ALPHA_MAXIMIZED:
  12654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12655. this._alphaState.alphaBlend = true;
  12656. break;
  12657. case Engine.ALPHA_INTERPOLATE:
  12658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12659. this._alphaState.alphaBlend = true;
  12660. break;
  12661. case Engine.ALPHA_SCREENMODE:
  12662. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12663. this._alphaState.alphaBlend = true;
  12664. break;
  12665. }
  12666. if (!noDepthWriteChange) {
  12667. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12668. }
  12669. this._alphaMode = mode;
  12670. };
  12671. Engine.prototype.getAlphaMode = function () {
  12672. return this._alphaMode;
  12673. };
  12674. // Textures
  12675. Engine.prototype.wipeCaches = function (bruteForce) {
  12676. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12677. return;
  12678. }
  12679. this._currentEffect = null;
  12680. // 6/8/2017: deltakosh: Should not be required anymore.
  12681. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12682. if (bruteForce) {
  12683. this.resetTextureCache();
  12684. this._currentProgram = null;
  12685. this._stencilState.reset();
  12686. this._depthCullingState.reset();
  12687. this.setDepthFunctionToLessOrEqual();
  12688. this._alphaState.reset();
  12689. }
  12690. this._resetVertexBufferBinding();
  12691. this._cachedIndexBuffer = null;
  12692. this._cachedEffectForVertexBuffers = null;
  12693. this._unbindVertexArrayObject();
  12694. this.bindIndexBuffer(null);
  12695. };
  12696. /**
  12697. * Set the compressed texture format to use, based on the formats you have, and the formats
  12698. * supported by the hardware / browser.
  12699. *
  12700. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12701. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12702. * to API arguments needed to compressed textures. This puts the burden on the container
  12703. * generator to house the arcane code for determining these for current & future formats.
  12704. *
  12705. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12706. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12707. *
  12708. * Note: The result of this call is not taken into account when a texture is base64.
  12709. *
  12710. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12711. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12712. *
  12713. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12714. * @returns The extension selected.
  12715. */
  12716. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12717. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12718. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12719. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12720. return this._textureFormatInUse = this._texturesSupported[i];
  12721. }
  12722. }
  12723. }
  12724. // actively set format to nothing, to allow this to be called more than once
  12725. // and possibly fail the 2nd time
  12726. this._textureFormatInUse = null;
  12727. return null;
  12728. };
  12729. Engine.prototype._createTexture = function () {
  12730. var texture = this._gl.createTexture();
  12731. if (!texture) {
  12732. throw new Error("Unable to create texture");
  12733. }
  12734. return texture;
  12735. };
  12736. /**
  12737. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12738. * @param {string} urlArg- This contains one of the following:
  12739. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12740. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12741. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12742. *
  12743. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12744. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12745. * @param {Scene} scene- Needed for loading to the correct scene.
  12746. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12747. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12748. * @param {callback} onError- Optional callback to be called upon failure.
  12749. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12750. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12751. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12752. *
  12753. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12754. */
  12755. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12756. var _this = this;
  12757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12758. if (onLoad === void 0) { onLoad = null; }
  12759. if (onError === void 0) { onError = null; }
  12760. if (buffer === void 0) { buffer = null; }
  12761. if (fallBack === void 0) { fallBack = null; }
  12762. if (format === void 0) { format = null; }
  12763. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12764. var fromData = url.substr(0, 5) === "data:";
  12765. var fromBlob = url.substr(0, 5) === "blob:";
  12766. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12767. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12768. // establish the file extension, if possible
  12769. var lastDot = url.lastIndexOf('.');
  12770. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12771. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12772. var isTGA = (extension.indexOf(".tga") === 0);
  12773. // determine if a ktx file should be substituted
  12774. var isKTX = false;
  12775. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12776. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12777. isKTX = true;
  12778. }
  12779. if (scene) {
  12780. scene._addPendingData(texture);
  12781. }
  12782. texture.url = url;
  12783. texture.generateMipMaps = !noMipmap;
  12784. texture.samplingMode = samplingMode;
  12785. texture.invertY = invertY;
  12786. if (!this._doNotHandleContextLost) {
  12787. // Keep a link to the buffer only if we plan to handle context lost
  12788. texture._buffer = buffer;
  12789. }
  12790. var onLoadObserver = null;
  12791. if (onLoad && !fallBack) {
  12792. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12793. }
  12794. if (!fallBack)
  12795. this._internalTexturesCache.push(texture);
  12796. var onerror = function (message, exception) {
  12797. if (scene) {
  12798. scene._removePendingData(texture);
  12799. }
  12800. if (onLoadObserver) {
  12801. texture.onLoadedObservable.remove(onLoadObserver);
  12802. }
  12803. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12804. if (isKTX) {
  12805. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12806. }
  12807. else if (BABYLON.Tools.UseFallbackTexture) {
  12808. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12809. }
  12810. if (onError) {
  12811. onError(message || "Unknown error", exception);
  12812. }
  12813. };
  12814. var callback = null;
  12815. // processing for non-image formats
  12816. if (isKTX || isTGA || isDDS) {
  12817. if (isKTX) {
  12818. callback = function (data) {
  12819. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12820. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12821. ktx.uploadLevels(_this._gl, !noMipmap);
  12822. return false;
  12823. }, samplingMode);
  12824. };
  12825. }
  12826. else if (isTGA) {
  12827. callback = function (arrayBuffer) {
  12828. var data = new Uint8Array(arrayBuffer);
  12829. var header = BABYLON.TGATools.GetTGAHeader(data);
  12830. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12831. BABYLON.TGATools.UploadContent(_this._gl, data);
  12832. return false;
  12833. }, samplingMode);
  12834. };
  12835. }
  12836. else if (isDDS) {
  12837. callback = function (data) {
  12838. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12839. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12840. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12841. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12842. return false;
  12843. }, samplingMode);
  12844. };
  12845. }
  12846. if (!buffer) {
  12847. this._loadFile(url, function (data) {
  12848. if (callback) {
  12849. callback(data);
  12850. }
  12851. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12852. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12853. });
  12854. }
  12855. else {
  12856. if (callback) {
  12857. callback(buffer);
  12858. }
  12859. }
  12860. // image format processing
  12861. }
  12862. else {
  12863. var onload = function (img) {
  12864. if (fromBlob && !_this._doNotHandleContextLost) {
  12865. // We need to store the image if we need to rebuild the texture
  12866. // in case of a webgl context lost
  12867. texture._buffer = img;
  12868. }
  12869. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12870. var gl = _this._gl;
  12871. var isPot = (img.width === potWidth && img.height === potHeight);
  12872. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12873. if (isPot) {
  12874. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12875. return false;
  12876. }
  12877. // Using shaders to rescale because canvas.drawImage is lossy
  12878. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12879. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12880. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12885. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12886. _this._releaseTexture(source);
  12887. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12888. continuationCallback();
  12889. });
  12890. return true;
  12891. }, samplingMode);
  12892. };
  12893. if (!fromData || isBase64)
  12894. if (buffer instanceof HTMLImageElement) {
  12895. onload(buffer);
  12896. }
  12897. else {
  12898. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12899. }
  12900. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12901. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12902. else
  12903. onload(buffer);
  12904. }
  12905. return texture;
  12906. };
  12907. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12908. var _this = this;
  12909. var rtt = this.createRenderTargetTexture({
  12910. width: destination.width,
  12911. height: destination.height,
  12912. }, {
  12913. generateMipMaps: false,
  12914. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12915. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12916. generateDepthBuffer: false,
  12917. generateStencilBuffer: false
  12918. });
  12919. if (!this._rescalePostProcess) {
  12920. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12921. }
  12922. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12923. _this._rescalePostProcess.onApply = function (effect) {
  12924. effect._bindTexture("textureSampler", source);
  12925. };
  12926. var hostingScene = scene;
  12927. if (!hostingScene) {
  12928. hostingScene = _this.scenes[_this.scenes.length - 1];
  12929. }
  12930. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12931. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12932. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12933. _this.unBindFramebuffer(rtt);
  12934. _this._releaseTexture(rtt);
  12935. if (onComplete) {
  12936. onComplete();
  12937. }
  12938. });
  12939. };
  12940. Engine.prototype._getInternalFormat = function (format) {
  12941. var internalFormat = this._gl.RGBA;
  12942. switch (format) {
  12943. case Engine.TEXTUREFORMAT_ALPHA:
  12944. internalFormat = this._gl.ALPHA;
  12945. break;
  12946. case Engine.TEXTUREFORMAT_LUMINANCE:
  12947. internalFormat = this._gl.LUMINANCE;
  12948. break;
  12949. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12950. internalFormat = this._gl.LUMINANCE_ALPHA;
  12951. break;
  12952. case Engine.TEXTUREFORMAT_RGB:
  12953. case Engine.TEXTUREFORMAT_RGB32F:
  12954. internalFormat = this._gl.RGB;
  12955. break;
  12956. case Engine.TEXTUREFORMAT_RGBA:
  12957. internalFormat = this._gl.RGBA;
  12958. break;
  12959. case Engine.TEXTUREFORMAT_R32F:
  12960. internalFormat = this._gl.RED;
  12961. break;
  12962. case Engine.TEXTUREFORMAT_RG32F:
  12963. internalFormat = this._gl.RG;
  12964. break;
  12965. }
  12966. return internalFormat;
  12967. };
  12968. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12969. if (compression === void 0) { compression = null; }
  12970. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12971. if (!texture) {
  12972. return;
  12973. }
  12974. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  12975. var internalFormat = this._getInternalFormat(format);
  12976. var textureType = this._getWebGLTextureType(type);
  12977. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12978. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12979. if (!this._doNotHandleContextLost) {
  12980. texture._bufferView = data;
  12981. texture.format = format;
  12982. texture.type = type;
  12983. texture.invertY = invertY;
  12984. texture._compression = compression;
  12985. }
  12986. if (texture.width % 4 !== 0) {
  12987. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12988. }
  12989. if (compression && data) {
  12990. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12991. }
  12992. else {
  12993. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12994. }
  12995. if (texture.generateMipMaps) {
  12996. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12997. }
  12998. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12999. // this.resetTextureCache();
  13000. texture.isReady = true;
  13001. };
  13002. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13003. if (compression === void 0) { compression = null; }
  13004. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13005. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13006. texture.baseWidth = width;
  13007. texture.baseHeight = height;
  13008. texture.width = width;
  13009. texture.height = height;
  13010. texture.format = format;
  13011. texture.generateMipMaps = generateMipMaps;
  13012. texture.samplingMode = samplingMode;
  13013. texture.invertY = invertY;
  13014. texture._compression = compression;
  13015. texture.type = type;
  13016. if (!this._doNotHandleContextLost) {
  13017. texture._bufferView = data;
  13018. }
  13019. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13020. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13021. // Filters
  13022. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13024. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13025. if (generateMipMaps) {
  13026. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13027. }
  13028. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13029. this._internalTexturesCache.push(texture);
  13030. return texture;
  13031. };
  13032. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13033. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13034. texture.baseWidth = width;
  13035. texture.baseHeight = height;
  13036. if (generateMipMaps) {
  13037. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13038. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13039. }
  13040. // this.resetTextureCache();
  13041. texture.width = width;
  13042. texture.height = height;
  13043. texture.isReady = false;
  13044. texture.generateMipMaps = generateMipMaps;
  13045. texture.samplingMode = samplingMode;
  13046. this.updateTextureSamplingMode(samplingMode, texture);
  13047. this._internalTexturesCache.push(texture);
  13048. return texture;
  13049. };
  13050. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13051. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13052. if (texture.isCube) {
  13053. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13054. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13055. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13057. }
  13058. else if (texture.is3D) {
  13059. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13060. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13061. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13062. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13063. }
  13064. else {
  13065. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13066. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13067. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13068. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13069. }
  13070. texture.samplingMode = samplingMode;
  13071. };
  13072. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13073. if (premulAlpha === void 0) { premulAlpha = false; }
  13074. if (!texture) {
  13075. return;
  13076. }
  13077. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13078. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13079. if (premulAlpha) {
  13080. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13081. }
  13082. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13083. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13084. if (texture.generateMipMaps) {
  13085. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13086. }
  13087. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13088. if (premulAlpha) {
  13089. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13090. }
  13091. texture.isReady = true;
  13092. };
  13093. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13094. if (!texture || texture._isDisabled) {
  13095. return;
  13096. }
  13097. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13098. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13099. try {
  13100. // Testing video texture support
  13101. if (this._videoTextureSupported === undefined) {
  13102. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13103. if (this._gl.getError() !== 0) {
  13104. this._videoTextureSupported = false;
  13105. }
  13106. else {
  13107. this._videoTextureSupported = true;
  13108. }
  13109. }
  13110. // Copy video through the current working canvas if video texture is not supported
  13111. if (!this._videoTextureSupported) {
  13112. if (!texture._workingCanvas) {
  13113. texture._workingCanvas = document.createElement("canvas");
  13114. var context = texture._workingCanvas.getContext("2d");
  13115. if (!context) {
  13116. throw new Error("Unable to get 2d context");
  13117. }
  13118. texture._workingContext = context;
  13119. texture._workingCanvas.width = texture.width;
  13120. texture._workingCanvas.height = texture.height;
  13121. }
  13122. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13123. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13124. }
  13125. else {
  13126. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13127. }
  13128. if (texture.generateMipMaps) {
  13129. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13130. }
  13131. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13132. // this.resetTextureCache();
  13133. texture.isReady = true;
  13134. }
  13135. catch (ex) {
  13136. // Something unexpected
  13137. // Let's disable the texture
  13138. texture._isDisabled = true;
  13139. }
  13140. };
  13141. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13142. var fullOptions = new RenderTargetCreationOptions();
  13143. if (options !== undefined && typeof options === "object") {
  13144. fullOptions.generateMipMaps = options.generateMipMaps;
  13145. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13146. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13147. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13148. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13149. }
  13150. else {
  13151. fullOptions.generateMipMaps = options;
  13152. fullOptions.generateDepthBuffer = true;
  13153. fullOptions.generateStencilBuffer = false;
  13154. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13155. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13156. }
  13157. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13158. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13159. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13160. }
  13161. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13162. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13163. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13164. }
  13165. var gl = this._gl;
  13166. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13167. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13168. var width = size.width || size;
  13169. var height = size.height || size;
  13170. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13171. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13172. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13173. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13174. }
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13179. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13180. // Create the framebuffer
  13181. var framebuffer = gl.createFramebuffer();
  13182. this.bindUnboundFramebuffer(framebuffer);
  13183. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13184. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13185. if (fullOptions.generateMipMaps) {
  13186. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13187. }
  13188. // Unbind
  13189. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13190. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13191. this.bindUnboundFramebuffer(null);
  13192. texture._framebuffer = framebuffer;
  13193. texture.baseWidth = width;
  13194. texture.baseHeight = height;
  13195. texture.width = width;
  13196. texture.height = height;
  13197. texture.isReady = true;
  13198. texture.samples = 1;
  13199. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13200. texture.samplingMode = fullOptions.samplingMode;
  13201. texture.type = fullOptions.type;
  13202. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13203. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13204. // this.resetTextureCache();
  13205. this._internalTexturesCache.push(texture);
  13206. return texture;
  13207. };
  13208. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13209. var generateMipMaps = false;
  13210. var generateDepthBuffer = true;
  13211. var generateStencilBuffer = false;
  13212. var generateDepthTexture = false;
  13213. var textureCount = 1;
  13214. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13215. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13216. var types = [], samplingModes = [];
  13217. if (options !== undefined) {
  13218. generateMipMaps = options.generateMipMaps;
  13219. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13220. generateStencilBuffer = options.generateStencilBuffer;
  13221. generateDepthTexture = options.generateDepthTexture;
  13222. textureCount = options.textureCount || 1;
  13223. if (options.types) {
  13224. types = options.types;
  13225. }
  13226. if (options.samplingModes) {
  13227. samplingModes = options.samplingModes;
  13228. }
  13229. }
  13230. var gl = this._gl;
  13231. // Create the framebuffer
  13232. var framebuffer = gl.createFramebuffer();
  13233. this.bindUnboundFramebuffer(framebuffer);
  13234. var width = size.width || size;
  13235. var height = size.height || size;
  13236. var textures = [];
  13237. var attachments = [];
  13238. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13239. for (var i = 0; i < textureCount; i++) {
  13240. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13241. var type = types[i] || defaultType;
  13242. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13243. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13244. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13245. }
  13246. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13247. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13248. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13249. }
  13250. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13251. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13252. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13253. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13254. }
  13255. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13256. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13257. textures.push(texture);
  13258. attachments.push(attachment);
  13259. gl.activeTexture(gl["TEXTURE" + i]);
  13260. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13265. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13266. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13267. if (generateMipMaps) {
  13268. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13269. }
  13270. // Unbind
  13271. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13272. texture._framebuffer = framebuffer;
  13273. texture._depthStencilBuffer = depthStencilBuffer;
  13274. texture.baseWidth = width;
  13275. texture.baseHeight = height;
  13276. texture.width = width;
  13277. texture.height = height;
  13278. texture.isReady = true;
  13279. texture.samples = 1;
  13280. texture.generateMipMaps = generateMipMaps;
  13281. texture.samplingMode = samplingMode;
  13282. texture.type = type;
  13283. texture._generateDepthBuffer = generateDepthBuffer;
  13284. texture._generateStencilBuffer = generateStencilBuffer;
  13285. texture._attachments = attachments;
  13286. this._internalTexturesCache.push(texture);
  13287. }
  13288. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13289. // Depth texture
  13290. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13291. gl.activeTexture(gl.TEXTURE0);
  13292. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13297. 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);
  13298. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13299. depthTexture._framebuffer = framebuffer;
  13300. depthTexture.baseWidth = width;
  13301. depthTexture.baseHeight = height;
  13302. depthTexture.width = width;
  13303. depthTexture.height = height;
  13304. depthTexture.isReady = true;
  13305. depthTexture.samples = 1;
  13306. depthTexture.generateMipMaps = generateMipMaps;
  13307. depthTexture.samplingMode = gl.NEAREST;
  13308. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13309. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13310. textures.push(depthTexture);
  13311. this._internalTexturesCache.push(depthTexture);
  13312. }
  13313. gl.drawBuffers(attachments);
  13314. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13315. this.bindUnboundFramebuffer(null);
  13316. this.resetTextureCache();
  13317. return textures;
  13318. };
  13319. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13320. if (samples === void 0) { samples = 1; }
  13321. var depthStencilBuffer = null;
  13322. var gl = this._gl;
  13323. // Create the depth/stencil buffer
  13324. if (generateStencilBuffer) {
  13325. depthStencilBuffer = gl.createRenderbuffer();
  13326. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13327. if (samples > 1) {
  13328. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13329. }
  13330. else {
  13331. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13332. }
  13333. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13334. }
  13335. else if (generateDepthBuffer) {
  13336. depthStencilBuffer = gl.createRenderbuffer();
  13337. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13338. if (samples > 1) {
  13339. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13340. }
  13341. else {
  13342. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13343. }
  13344. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13345. }
  13346. return depthStencilBuffer;
  13347. };
  13348. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13349. if (this.webGLVersion < 2 || !texture) {
  13350. return 1;
  13351. }
  13352. if (texture.samples === samples) {
  13353. return samples;
  13354. }
  13355. var gl = this._gl;
  13356. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13357. // Dispose previous render buffers
  13358. if (texture._depthStencilBuffer) {
  13359. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13360. texture._depthStencilBuffer = null;
  13361. }
  13362. if (texture._MSAAFramebuffer) {
  13363. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13364. texture._MSAAFramebuffer = null;
  13365. }
  13366. if (texture._MSAARenderBuffer) {
  13367. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13368. texture._MSAARenderBuffer = null;
  13369. }
  13370. if (samples > 1) {
  13371. var framebuffer = gl.createFramebuffer();
  13372. if (!framebuffer) {
  13373. throw new Error("Unable to create multi sampled framebuffer");
  13374. }
  13375. texture._MSAAFramebuffer = framebuffer;
  13376. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13377. var colorRenderbuffer = gl.createRenderbuffer();
  13378. if (!colorRenderbuffer) {
  13379. throw new Error("Unable to create multi sampled framebuffer");
  13380. }
  13381. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13382. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13383. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13384. texture._MSAARenderBuffer = colorRenderbuffer;
  13385. }
  13386. else {
  13387. this.bindUnboundFramebuffer(texture._framebuffer);
  13388. }
  13389. texture.samples = samples;
  13390. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13391. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13392. this.bindUnboundFramebuffer(null);
  13393. return samples;
  13394. };
  13395. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13396. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13397. return 1;
  13398. }
  13399. if (textures[0].samples === samples) {
  13400. return samples;
  13401. }
  13402. var gl = this._gl;
  13403. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13404. // Dispose previous render buffers
  13405. if (textures[0]._depthStencilBuffer) {
  13406. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13407. textures[0]._depthStencilBuffer = null;
  13408. }
  13409. if (textures[0]._MSAAFramebuffer) {
  13410. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13411. textures[0]._MSAAFramebuffer = null;
  13412. }
  13413. for (var i = 0; i < textures.length; i++) {
  13414. if (textures[i]._MSAARenderBuffer) {
  13415. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13416. textures[i]._MSAARenderBuffer = null;
  13417. }
  13418. }
  13419. if (samples > 1) {
  13420. var framebuffer = gl.createFramebuffer();
  13421. if (!framebuffer) {
  13422. throw new Error("Unable to create multi sampled framebuffer");
  13423. }
  13424. this.bindUnboundFramebuffer(framebuffer);
  13425. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13426. var attachments = [];
  13427. for (var i = 0; i < textures.length; i++) {
  13428. var texture = textures[i];
  13429. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13430. var colorRenderbuffer = gl.createRenderbuffer();
  13431. if (!colorRenderbuffer) {
  13432. throw new Error("Unable to create multi sampled framebuffer");
  13433. }
  13434. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13435. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13436. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13437. texture._MSAAFramebuffer = framebuffer;
  13438. texture._MSAARenderBuffer = colorRenderbuffer;
  13439. texture.samples = samples;
  13440. texture._depthStencilBuffer = depthStencilBuffer;
  13441. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13442. attachments.push(attachment);
  13443. }
  13444. gl.drawBuffers(attachments);
  13445. }
  13446. else {
  13447. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13448. }
  13449. this.bindUnboundFramebuffer(null);
  13450. return samples;
  13451. };
  13452. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13453. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13454. };
  13455. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13456. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13457. };
  13458. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13459. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13460. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13461. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13462. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13463. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13464. }
  13465. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13466. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13467. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13468. }
  13469. var gl = this._gl;
  13470. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13471. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13472. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13473. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13474. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13475. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13476. }
  13477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13481. for (var face = 0; face < 6; face++) {
  13482. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13483. }
  13484. // Create the framebuffer
  13485. var framebuffer = gl.createFramebuffer();
  13486. this.bindUnboundFramebuffer(framebuffer);
  13487. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13488. // MipMaps
  13489. if (fullOptions.generateMipMaps) {
  13490. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13491. }
  13492. // Unbind
  13493. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13494. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13495. this.bindUnboundFramebuffer(null);
  13496. texture._framebuffer = framebuffer;
  13497. texture.width = size;
  13498. texture.height = size;
  13499. texture.isReady = true;
  13500. texture.isCube = true;
  13501. texture.samples = 1;
  13502. texture.generateMipMaps = fullOptions.generateMipMaps;
  13503. texture.samplingMode = fullOptions.samplingMode;
  13504. texture.type = fullOptions.type;
  13505. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13506. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13507. this._internalTexturesCache.push(texture);
  13508. return texture;
  13509. };
  13510. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13511. var _this = this;
  13512. if (onLoad === void 0) { onLoad = null; }
  13513. if (onError === void 0) { onError = null; }
  13514. if (forcedExtension === void 0) { forcedExtension = null; }
  13515. var callback = function (loadData) {
  13516. if (!loadData) {
  13517. if (onLoad) {
  13518. onLoad(null);
  13519. }
  13520. return;
  13521. }
  13522. var texture = loadData.texture;
  13523. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13524. texture._lodGenerationScale = scale;
  13525. texture._lodGenerationOffset = offset;
  13526. if (_this._caps.textureLOD) {
  13527. // Do not add extra process if texture lod is supported.
  13528. if (onLoad) {
  13529. onLoad(texture);
  13530. }
  13531. return;
  13532. }
  13533. var mipSlices = 3;
  13534. var gl = _this._gl;
  13535. var width = loadData.width;
  13536. if (!width) {
  13537. return;
  13538. }
  13539. var textures = [];
  13540. for (var i = 0; i < mipSlices; i++) {
  13541. //compute LOD from even spacing in smoothness (matching shader calculation)
  13542. var smoothness = i / (mipSlices - 1);
  13543. var roughness = 1 - smoothness;
  13544. var minLODIndex = offset; // roughness = 0
  13545. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13546. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13547. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13548. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13549. glTextureFromLod.isCube = true;
  13550. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13555. if (loadData.isDDS) {
  13556. var info = loadData.info;
  13557. var data = loadData.data;
  13558. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13559. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13560. }
  13561. else {
  13562. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13563. }
  13564. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13565. // Wrap in a base texture for easy binding.
  13566. var lodTexture = new BABYLON.BaseTexture(scene);
  13567. lodTexture.isCube = true;
  13568. lodTexture._texture = glTextureFromLod;
  13569. glTextureFromLod.isReady = true;
  13570. textures.push(lodTexture);
  13571. }
  13572. texture._lodTextureHigh = textures[2];
  13573. texture._lodTextureMid = textures[1];
  13574. texture._lodTextureLow = textures[0];
  13575. if (onLoad) {
  13576. onLoad(texture);
  13577. }
  13578. };
  13579. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13580. };
  13581. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13582. var _this = this;
  13583. if (onLoad === void 0) { onLoad = null; }
  13584. if (onError === void 0) { onError = null; }
  13585. if (forcedExtension === void 0) { forcedExtension = null; }
  13586. var gl = this._gl;
  13587. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13588. texture.isCube = true;
  13589. texture.url = rootUrl;
  13590. texture.generateMipMaps = !noMipmap;
  13591. if (!this._doNotHandleContextLost) {
  13592. texture._extension = forcedExtension;
  13593. texture._files = files;
  13594. }
  13595. var isKTX = false;
  13596. var isDDS = false;
  13597. var lastDot = rootUrl.lastIndexOf('.');
  13598. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13599. if (this._textureFormatInUse) {
  13600. extension = this._textureFormatInUse;
  13601. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13602. isKTX = true;
  13603. }
  13604. else {
  13605. isDDS = (extension === ".dds");
  13606. }
  13607. var onerror = function (request, exception) {
  13608. if (onError && request) {
  13609. onError(request.status + " " + request.statusText, exception);
  13610. }
  13611. };
  13612. if (isKTX) {
  13613. this._loadFile(rootUrl, function (data) {
  13614. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13615. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13616. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13617. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13618. ktx.uploadLevels(_this._gl, !noMipmap);
  13619. _this.setCubeMapTextureParams(gl, loadMipmap);
  13620. texture.width = ktx.pixelWidth;
  13621. texture.height = ktx.pixelHeight;
  13622. texture.isReady = true;
  13623. }, undefined, undefined, true, onerror);
  13624. }
  13625. else if (isDDS) {
  13626. if (files && files.length === 6) {
  13627. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13628. var info;
  13629. var loadMipmap = false;
  13630. var width = 0;
  13631. for (var index = 0; index < imgs.length; index++) {
  13632. var data = imgs[index];
  13633. info = BABYLON.DDSTools.GetDDSInfo(data);
  13634. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13635. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13636. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13637. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13638. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13639. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13640. }
  13641. texture.width = info.width;
  13642. texture.height = info.height;
  13643. texture.type = info.textureType;
  13644. width = info.width;
  13645. }
  13646. _this.setCubeMapTextureParams(gl, loadMipmap);
  13647. texture.isReady = true;
  13648. if (onLoad) {
  13649. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13650. }
  13651. }, files, onError);
  13652. }
  13653. else {
  13654. this._loadFile(rootUrl, function (data) {
  13655. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13656. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13657. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13658. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13659. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13660. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13661. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13662. }
  13663. _this.setCubeMapTextureParams(gl, loadMipmap);
  13664. texture.width = info.width;
  13665. texture.height = info.height;
  13666. texture.isReady = true;
  13667. texture.type = info.textureType;
  13668. if (onLoad) {
  13669. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13670. }
  13671. }, undefined, undefined, true, onerror);
  13672. }
  13673. }
  13674. else {
  13675. if (!files) {
  13676. throw new Error("Cannot load cubemap because files were not defined");
  13677. }
  13678. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13679. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13680. var height = width;
  13681. _this._prepareWorkingCanvas();
  13682. if (!_this._workingCanvas || !_this._workingContext) {
  13683. return;
  13684. }
  13685. _this._workingCanvas.width = width;
  13686. _this._workingCanvas.height = height;
  13687. var faces = [
  13688. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13689. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13690. ];
  13691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13693. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13694. for (var index = 0; index < faces.length; index++) {
  13695. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13696. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13697. }
  13698. if (!noMipmap) {
  13699. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13700. }
  13701. _this.setCubeMapTextureParams(gl, !noMipmap);
  13702. texture.width = width;
  13703. texture.height = height;
  13704. texture.isReady = true;
  13705. if (format) {
  13706. texture.format = format;
  13707. }
  13708. texture.onLoadedObservable.notifyObservers(texture);
  13709. texture.onLoadedObservable.clear();
  13710. if (onLoad) {
  13711. onLoad();
  13712. }
  13713. }, files, onError);
  13714. }
  13715. this._internalTexturesCache.push(texture);
  13716. return texture;
  13717. };
  13718. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13723. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13724. // this.resetTextureCache();
  13725. };
  13726. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13727. if (compression === void 0) { compression = null; }
  13728. if (level === void 0) { level = 0; }
  13729. texture._bufferViewArray = data;
  13730. texture.format = format;
  13731. texture.type = type;
  13732. texture.invertY = invertY;
  13733. texture._compression = compression;
  13734. var gl = this._gl;
  13735. var textureType = this._getWebGLTextureType(type);
  13736. var internalFormat = this._getInternalFormat(format);
  13737. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13738. var needConversion = false;
  13739. if (internalFormat === gl.RGB) {
  13740. internalFormat = gl.RGBA;
  13741. needConversion = true;
  13742. }
  13743. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13744. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13745. if (texture.width % 4 !== 0) {
  13746. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13747. }
  13748. // Data are known to be in +X +Y +Z -X -Y -Z
  13749. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13750. var faceData = data[faceIndex];
  13751. if (compression) {
  13752. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13753. }
  13754. else {
  13755. if (needConversion) {
  13756. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13757. }
  13758. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13759. }
  13760. }
  13761. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13762. if (isPot && texture.generateMipMaps && level === 0) {
  13763. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13764. }
  13765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13766. // this.resetTextureCache();
  13767. texture.isReady = true;
  13768. };
  13769. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13770. if (compression === void 0) { compression = null; }
  13771. var gl = this._gl;
  13772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13773. texture.isCube = true;
  13774. texture.generateMipMaps = generateMipMaps;
  13775. texture.format = format;
  13776. texture.type = type;
  13777. if (!this._doNotHandleContextLost) {
  13778. texture._bufferViewArray = data;
  13779. }
  13780. var textureType = this._getWebGLTextureType(type);
  13781. var internalFormat = this._getInternalFormat(format);
  13782. if (internalFormat === gl.RGB) {
  13783. internalFormat = gl.RGBA;
  13784. }
  13785. var width = size;
  13786. var height = width;
  13787. texture.width = width;
  13788. texture.height = height;
  13789. // Double check on POT to generate Mips.
  13790. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13791. if (!isPot) {
  13792. generateMipMaps = false;
  13793. }
  13794. // Upload data if needed. The texture won't be ready until then.
  13795. if (data) {
  13796. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13797. }
  13798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13799. // Filters
  13800. if (data && generateMipMaps) {
  13801. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13802. }
  13803. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13806. }
  13807. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13810. }
  13811. else {
  13812. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13815. }
  13816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13818. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13819. return texture;
  13820. };
  13821. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13822. var _this = this;
  13823. if (onLoad === void 0) { onLoad = null; }
  13824. if (onError === void 0) { onError = null; }
  13825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13826. if (invertY === void 0) { invertY = false; }
  13827. var gl = this._gl;
  13828. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13829. scene._addPendingData(texture);
  13830. texture.url = url;
  13831. this._internalTexturesCache.push(texture);
  13832. var onerror = function (request, exception) {
  13833. scene._removePendingData(texture);
  13834. if (onError && request) {
  13835. onError(request.status + " " + request.statusText, exception);
  13836. }
  13837. };
  13838. var internalCallback = function (data) {
  13839. var width = texture.width;
  13840. var faceDataArrays = callback(data);
  13841. if (!faceDataArrays) {
  13842. return;
  13843. }
  13844. if (mipmmapGenerator) {
  13845. var textureType = _this._getWebGLTextureType(type);
  13846. var internalFormat = _this._getInternalFormat(format);
  13847. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13848. var needConversion = false;
  13849. if (internalFormat === gl.RGB) {
  13850. internalFormat = gl.RGBA;
  13851. needConversion = true;
  13852. }
  13853. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13854. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13855. var mipData = mipmmapGenerator(faceDataArrays);
  13856. for (var level = 0; level < mipData.length; level++) {
  13857. var mipSize = width >> level;
  13858. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13859. var mipFaceData = mipData[level][faceIndex];
  13860. if (needConversion) {
  13861. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13862. }
  13863. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13864. }
  13865. }
  13866. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13867. }
  13868. else {
  13869. texture.generateMipMaps = !noMipmap;
  13870. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13871. }
  13872. texture.isReady = true;
  13873. // this.resetTextureCache();
  13874. scene._removePendingData(texture);
  13875. if (onLoad) {
  13876. onLoad();
  13877. }
  13878. };
  13879. this._loadFile(url, function (data) {
  13880. internalCallback(data);
  13881. }, undefined, scene.database, true, onerror);
  13882. return texture;
  13883. };
  13884. ;
  13885. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13886. if (compression === void 0) { compression = null; }
  13887. var internalFormat = this._getInternalFormat(format);
  13888. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13889. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13890. if (!this._doNotHandleContextLost) {
  13891. texture._bufferView = data;
  13892. texture.format = format;
  13893. texture.invertY = invertY;
  13894. texture._compression = compression;
  13895. }
  13896. if (texture.width % 4 !== 0) {
  13897. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13898. }
  13899. if (compression && data) {
  13900. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13901. }
  13902. else {
  13903. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13904. }
  13905. if (texture.generateMipMaps) {
  13906. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13907. }
  13908. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13909. // this.resetTextureCache();
  13910. texture.isReady = true;
  13911. };
  13912. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13913. if (compression === void 0) { compression = null; }
  13914. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13915. texture.baseWidth = width;
  13916. texture.baseHeight = height;
  13917. texture.baseDepth = depth;
  13918. texture.width = width;
  13919. texture.height = height;
  13920. texture.depth = depth;
  13921. texture.format = format;
  13922. texture.generateMipMaps = generateMipMaps;
  13923. texture.samplingMode = samplingMode;
  13924. texture.is3D = true;
  13925. if (!this._doNotHandleContextLost) {
  13926. texture._bufferView = data;
  13927. }
  13928. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13929. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13930. // Filters
  13931. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13932. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13933. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13934. if (generateMipMaps) {
  13935. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13936. }
  13937. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13938. this._internalTexturesCache.push(texture);
  13939. return texture;
  13940. };
  13941. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13942. var gl = this._gl;
  13943. if (!gl) {
  13944. return;
  13945. }
  13946. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13947. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13949. if (!noMipmap && !isCompressed) {
  13950. gl.generateMipmap(gl.TEXTURE_2D);
  13951. }
  13952. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13953. // this.resetTextureCache();
  13954. if (scene) {
  13955. scene._removePendingData(texture);
  13956. }
  13957. texture.onLoadedObservable.notifyObservers(texture);
  13958. texture.onLoadedObservable.clear();
  13959. };
  13960. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13961. var _this = this;
  13962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13963. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13964. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13965. var gl = this._gl;
  13966. if (!gl) {
  13967. return;
  13968. }
  13969. if (!texture._webGLTexture) {
  13970. // this.resetTextureCache();
  13971. if (scene) {
  13972. scene._removePendingData(texture);
  13973. }
  13974. return;
  13975. }
  13976. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13977. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13978. texture.baseWidth = width;
  13979. texture.baseHeight = height;
  13980. texture.width = potWidth;
  13981. texture.height = potHeight;
  13982. texture.isReady = true;
  13983. if (processFunction(potWidth, potHeight, function () {
  13984. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13985. })) {
  13986. // Returning as texture needs extra async steps
  13987. return;
  13988. }
  13989. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13990. };
  13991. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13992. // Create new RGBA data container.
  13993. var rgbaData;
  13994. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13995. rgbaData = new Float32Array(width * height * 4);
  13996. }
  13997. else {
  13998. rgbaData = new Uint32Array(width * height * 4);
  13999. }
  14000. // Convert each pixel.
  14001. for (var x = 0; x < width; x++) {
  14002. for (var y = 0; y < height; y++) {
  14003. var index = (y * width + x) * 3;
  14004. var newIndex = (y * width + x) * 4;
  14005. // Map Old Value to new value.
  14006. rgbaData[newIndex + 0] = rgbData[index + 0];
  14007. rgbaData[newIndex + 1] = rgbData[index + 1];
  14008. rgbaData[newIndex + 2] = rgbData[index + 2];
  14009. // Add fully opaque alpha channel.
  14010. rgbaData[newIndex + 3] = 1;
  14011. }
  14012. }
  14013. return rgbaData;
  14014. };
  14015. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14016. var gl = this._gl;
  14017. if (texture._framebuffer) {
  14018. gl.deleteFramebuffer(texture._framebuffer);
  14019. texture._framebuffer = null;
  14020. }
  14021. if (texture._depthStencilBuffer) {
  14022. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14023. texture._depthStencilBuffer = null;
  14024. }
  14025. if (texture._MSAAFramebuffer) {
  14026. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14027. texture._MSAAFramebuffer = null;
  14028. }
  14029. if (texture._MSAARenderBuffer) {
  14030. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14031. texture._MSAARenderBuffer = null;
  14032. }
  14033. };
  14034. Engine.prototype._releaseTexture = function (texture) {
  14035. var gl = this._gl;
  14036. this._releaseFramebufferObjects(texture);
  14037. gl.deleteTexture(texture._webGLTexture);
  14038. // Unbind channels
  14039. this.unbindAllTextures();
  14040. var index = this._internalTexturesCache.indexOf(texture);
  14041. if (index !== -1) {
  14042. this._internalTexturesCache.splice(index, 1);
  14043. }
  14044. // Integrated fixed lod samplers.
  14045. if (texture._lodTextureHigh) {
  14046. texture._lodTextureHigh.dispose();
  14047. }
  14048. if (texture._lodTextureMid) {
  14049. texture._lodTextureMid.dispose();
  14050. }
  14051. if (texture._lodTextureLow) {
  14052. texture._lodTextureLow.dispose();
  14053. }
  14054. };
  14055. Engine.prototype.setProgram = function (program) {
  14056. if (this._currentProgram !== program) {
  14057. this._gl.useProgram(program);
  14058. this._currentProgram = program;
  14059. }
  14060. };
  14061. Engine.prototype.bindSamplers = function (effect) {
  14062. this.setProgram(effect.getProgram());
  14063. var samplers = effect.getSamplers();
  14064. for (var index = 0; index < samplers.length; index++) {
  14065. var uniform = effect.getUniform(samplers[index]);
  14066. if (uniform) {
  14067. this._boundUniforms[index] = uniform;
  14068. }
  14069. }
  14070. this._currentEffect = null;
  14071. };
  14072. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14073. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14074. return;
  14075. }
  14076. // Remove
  14077. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14078. // Bind last to it
  14079. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14080. // Bind to dummy
  14081. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14082. };
  14083. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14084. if (!internalTexture) {
  14085. return -1;
  14086. }
  14087. internalTexture._initialSlot = channel;
  14088. if (this.disableTextureBindingOptimization) {
  14089. if (channel !== internalTexture._designatedSlot) {
  14090. this._textureCollisions.addCount(1, false);
  14091. }
  14092. }
  14093. else {
  14094. if (channel !== internalTexture._designatedSlot) {
  14095. if (internalTexture._designatedSlot > -1) {
  14096. return internalTexture._designatedSlot;
  14097. }
  14098. else {
  14099. // No slot for this texture, let's pick a new one (if we find a free slot)
  14100. if (this._nextFreeTextureSlots.length) {
  14101. return this._nextFreeTextureSlots[0];
  14102. }
  14103. // We need to recycle the oldest bound texture, sorry.
  14104. this._textureCollisions.addCount(1, false);
  14105. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14106. }
  14107. }
  14108. }
  14109. return channel;
  14110. };
  14111. Engine.prototype._linkTrackers = function (previous, next) {
  14112. previous.next = next;
  14113. next.previous = previous;
  14114. };
  14115. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14116. var currentSlot = internalTexture._designatedSlot;
  14117. if (currentSlot === -1) {
  14118. return -1;
  14119. }
  14120. internalTexture._designatedSlot = -1;
  14121. if (this.disableTextureBindingOptimization) {
  14122. return -1;
  14123. }
  14124. // Remove from bound list
  14125. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14126. // Free the slot
  14127. this._boundTexturesCache[currentSlot] = null;
  14128. this._nextFreeTextureSlots.push(currentSlot);
  14129. return currentSlot;
  14130. };
  14131. Engine.prototype._activateCurrentTexture = function () {
  14132. if (this._currentTextureChannel !== this._activeChannel) {
  14133. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14134. this._currentTextureChannel = this._activeChannel;
  14135. }
  14136. };
  14137. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14138. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14139. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14140. this._activeChannel = texture._designatedSlot;
  14141. }
  14142. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14143. var isTextureForRendering = texture && texture._initialSlot > -1;
  14144. if (currentTextureBound !== texture) {
  14145. if (currentTextureBound) {
  14146. this._removeDesignatedSlot(currentTextureBound);
  14147. }
  14148. this._activateCurrentTexture();
  14149. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14150. this._boundTexturesCache[this._activeChannel] = texture;
  14151. if (texture) {
  14152. if (!this.disableTextureBindingOptimization) {
  14153. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14154. if (slotIndex > -1) {
  14155. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14156. }
  14157. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14158. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14159. }
  14160. texture._designatedSlot = this._activeChannel;
  14161. }
  14162. }
  14163. else if (forTextureDataUpdate) {
  14164. this._activateCurrentTexture();
  14165. }
  14166. if (isTextureForRendering && !forTextureDataUpdate) {
  14167. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14168. }
  14169. };
  14170. Engine.prototype._bindTexture = function (channel, texture) {
  14171. if (channel < 0) {
  14172. return;
  14173. }
  14174. if (texture) {
  14175. channel = this._getCorrectTextureChannel(channel, texture);
  14176. }
  14177. this._activeChannel = channel;
  14178. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14179. };
  14180. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14181. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14182. };
  14183. Engine.prototype.unbindAllTextures = function () {
  14184. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14185. this._activeChannel = channel;
  14186. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14187. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14188. if (this.webGLVersion > 1) {
  14189. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14190. }
  14191. }
  14192. };
  14193. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14194. if (channel < 0) {
  14195. return;
  14196. }
  14197. if (uniform) {
  14198. this._boundUniforms[channel] = uniform;
  14199. }
  14200. this._setTexture(channel, texture);
  14201. };
  14202. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14203. var uniform = this._boundUniforms[sourceSlot];
  14204. if (uniform._currentState === destination) {
  14205. return;
  14206. }
  14207. this._gl.uniform1i(uniform, destination);
  14208. uniform._currentState = destination;
  14209. };
  14210. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14211. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14212. // Not ready?
  14213. if (!texture) {
  14214. if (this._boundTexturesCache[channel] != null) {
  14215. this._activeChannel = channel;
  14216. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14217. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14218. if (this.webGLVersion > 1) {
  14219. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14220. }
  14221. }
  14222. return false;
  14223. }
  14224. // Video
  14225. if (texture.video) {
  14226. this._activeChannel = channel;
  14227. texture.update();
  14228. }
  14229. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14230. texture.delayLoad();
  14231. return false;
  14232. }
  14233. var internalTexture;
  14234. if (texture.isReady()) {
  14235. internalTexture = texture.getInternalTexture();
  14236. }
  14237. else if (texture.isCube) {
  14238. internalTexture = this.emptyCubeTexture;
  14239. }
  14240. else if (texture.is3D) {
  14241. internalTexture = this.emptyTexture3D;
  14242. }
  14243. else {
  14244. internalTexture = this.emptyTexture;
  14245. }
  14246. if (!isPartOfTextureArray) {
  14247. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14248. }
  14249. if (this._boundTexturesCache[channel] === internalTexture) {
  14250. this._moveBoundTextureOnTop(internalTexture);
  14251. if (!isPartOfTextureArray) {
  14252. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14253. }
  14254. return false;
  14255. }
  14256. this._activeChannel = channel;
  14257. if (internalTexture && internalTexture.is3D) {
  14258. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14259. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14260. internalTexture._cachedWrapU = texture.wrapU;
  14261. switch (texture.wrapU) {
  14262. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14263. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14264. break;
  14265. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14266. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14267. break;
  14268. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14269. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14270. break;
  14271. }
  14272. }
  14273. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14274. internalTexture._cachedWrapV = texture.wrapV;
  14275. switch (texture.wrapV) {
  14276. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14277. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14278. break;
  14279. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14281. break;
  14282. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14283. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14284. break;
  14285. }
  14286. }
  14287. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14288. internalTexture._cachedWrapR = texture.wrapR;
  14289. switch (texture.wrapR) {
  14290. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14291. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14292. break;
  14293. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14294. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14295. break;
  14296. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14297. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14298. break;
  14299. }
  14300. }
  14301. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14302. }
  14303. else if (internalTexture && internalTexture.isCube) {
  14304. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14305. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14306. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14307. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14308. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14309. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14310. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14311. }
  14312. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14313. }
  14314. else {
  14315. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14316. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14317. internalTexture._cachedWrapU = texture.wrapU;
  14318. switch (texture.wrapU) {
  14319. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14321. break;
  14322. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14324. break;
  14325. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14326. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14327. break;
  14328. }
  14329. }
  14330. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14331. internalTexture._cachedWrapV = texture.wrapV;
  14332. switch (texture.wrapV) {
  14333. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14334. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14335. break;
  14336. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14337. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14338. break;
  14339. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14340. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14341. break;
  14342. }
  14343. }
  14344. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14345. }
  14346. return true;
  14347. };
  14348. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14349. if (channel < 0 || !uniform) {
  14350. return;
  14351. }
  14352. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14353. this._textureUnits = new Int32Array(textures.length);
  14354. }
  14355. for (var i = 0; i < textures.length; i++) {
  14356. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14357. }
  14358. this._gl.uniform1iv(uniform, this._textureUnits);
  14359. for (var index = 0; index < textures.length; index++) {
  14360. this._setTexture(this._textureUnits[index], textures[index], true);
  14361. }
  14362. };
  14363. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14364. var internalTexture = texture.getInternalTexture();
  14365. if (!internalTexture) {
  14366. return;
  14367. }
  14368. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14369. var value = texture.anisotropicFilteringLevel;
  14370. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14371. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14372. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14373. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14374. }
  14375. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14376. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14377. internalTexture._cachedAnisotropicFilteringLevel = value;
  14378. }
  14379. };
  14380. Engine.prototype.readPixels = function (x, y, width, height) {
  14381. var data = new Uint8Array(height * width * 4);
  14382. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14383. return data;
  14384. };
  14385. /**
  14386. * Add an externaly attached data from its key.
  14387. * This method call will fail and return false, if such key already exists.
  14388. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14389. * @param key the unique key that identifies the data
  14390. * @param data the data object to associate to the key for this Engine instance
  14391. * @return true if no such key were already present and the data was added successfully, false otherwise
  14392. */
  14393. Engine.prototype.addExternalData = function (key, data) {
  14394. if (!this._externalData) {
  14395. this._externalData = new BABYLON.StringDictionary();
  14396. }
  14397. return this._externalData.add(key, data);
  14398. };
  14399. /**
  14400. * Get an externaly attached data from its key
  14401. * @param key the unique key that identifies the data
  14402. * @return the associated data, if present (can be null), or undefined if not present
  14403. */
  14404. Engine.prototype.getExternalData = function (key) {
  14405. if (!this._externalData) {
  14406. this._externalData = new BABYLON.StringDictionary();
  14407. }
  14408. return this._externalData.get(key);
  14409. };
  14410. /**
  14411. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14412. * @param key the unique key that identifies the data
  14413. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14414. * @return the associated data, can be null if the factory returned null.
  14415. */
  14416. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14417. if (!this._externalData) {
  14418. this._externalData = new BABYLON.StringDictionary();
  14419. }
  14420. return this._externalData.getOrAddWithFactory(key, factory);
  14421. };
  14422. /**
  14423. * Remove an externaly attached data from the Engine instance
  14424. * @param key the unique key that identifies the data
  14425. * @return true if the data was successfully removed, false if it doesn't exist
  14426. */
  14427. Engine.prototype.removeExternalData = function (key) {
  14428. if (!this._externalData) {
  14429. this._externalData = new BABYLON.StringDictionary();
  14430. }
  14431. return this._externalData.remove(key);
  14432. };
  14433. Engine.prototype.unbindAllAttributes = function () {
  14434. if (this._mustWipeVertexAttributes) {
  14435. this._mustWipeVertexAttributes = false;
  14436. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14437. this._gl.disableVertexAttribArray(i);
  14438. this._vertexAttribArraysEnabled[i] = false;
  14439. this._currentBufferPointers[i].active = false;
  14440. }
  14441. return;
  14442. }
  14443. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14444. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14445. continue;
  14446. }
  14447. this._gl.disableVertexAttribArray(i);
  14448. this._vertexAttribArraysEnabled[i] = false;
  14449. this._currentBufferPointers[i].active = false;
  14450. }
  14451. };
  14452. Engine.prototype.releaseEffects = function () {
  14453. for (var name in this._compiledEffects) {
  14454. this._deleteProgram(this._compiledEffects[name]._program);
  14455. }
  14456. this._compiledEffects = {};
  14457. };
  14458. // Dispose
  14459. Engine.prototype.dispose = function () {
  14460. this.hideLoadingUI();
  14461. this.stopRenderLoop();
  14462. // Release postProcesses
  14463. while (this.postProcesses.length) {
  14464. this.postProcesses[0].dispose();
  14465. }
  14466. // Empty texture
  14467. if (this._emptyTexture) {
  14468. this._releaseTexture(this._emptyTexture);
  14469. this._emptyTexture = null;
  14470. }
  14471. if (this._emptyCubeTexture) {
  14472. this._releaseTexture(this._emptyCubeTexture);
  14473. this._emptyCubeTexture = null;
  14474. }
  14475. // Rescale PP
  14476. if (this._rescalePostProcess) {
  14477. this._rescalePostProcess.dispose();
  14478. }
  14479. // Release scenes
  14480. while (this.scenes.length) {
  14481. this.scenes[0].dispose();
  14482. }
  14483. // Release audio engine
  14484. if (Engine.audioEngine) {
  14485. Engine.audioEngine.dispose();
  14486. }
  14487. // Release effects
  14488. this.releaseEffects();
  14489. // Unbind
  14490. this.unbindAllAttributes();
  14491. if (this._dummyFramebuffer) {
  14492. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14493. }
  14494. //WebVR
  14495. this.disableVR();
  14496. // Events
  14497. if (BABYLON.Tools.IsWindowObjectExist()) {
  14498. window.removeEventListener("blur", this._onBlur);
  14499. window.removeEventListener("focus", this._onFocus);
  14500. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14501. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14502. if (this._renderingCanvas) {
  14503. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14504. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14505. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14506. if (!this._doNotHandleContextLost) {
  14507. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14508. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14509. }
  14510. }
  14511. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14512. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14513. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14514. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14515. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14516. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14517. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14518. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14519. if (this._onVrDisplayConnect) {
  14520. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14521. if (this._onVrDisplayDisconnect) {
  14522. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14523. }
  14524. if (this._onVrDisplayPresentChange) {
  14525. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14526. }
  14527. this._onVrDisplayConnect = null;
  14528. this._onVrDisplayDisconnect = null;
  14529. }
  14530. }
  14531. // Remove from Instances
  14532. var index = Engine.Instances.indexOf(this);
  14533. if (index >= 0) {
  14534. Engine.Instances.splice(index, 1);
  14535. }
  14536. this._workingCanvas = null;
  14537. this._workingContext = null;
  14538. this._currentBufferPointers = [];
  14539. this._renderingCanvas = null;
  14540. this._currentProgram = null;
  14541. this.onResizeObservable.clear();
  14542. this.onCanvasBlurObservable.clear();
  14543. this.onCanvasFocusObservable.clear();
  14544. this.onCanvasPointerOutObservable.clear();
  14545. this.onBeginFrameObservable.clear();
  14546. this.onEndFrameObservable.clear();
  14547. BABYLON.Effect.ResetCache();
  14548. // Abort active requests
  14549. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14550. var request = _a[_i];
  14551. request.abort();
  14552. }
  14553. };
  14554. // Loading screen
  14555. Engine.prototype.displayLoadingUI = function () {
  14556. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14557. return;
  14558. }
  14559. var loadingScreen = this.loadingScreen;
  14560. if (loadingScreen) {
  14561. loadingScreen.displayLoadingUI();
  14562. }
  14563. };
  14564. Engine.prototype.hideLoadingUI = function () {
  14565. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14566. return;
  14567. }
  14568. var loadingScreen = this.loadingScreen;
  14569. if (loadingScreen) {
  14570. loadingScreen.hideLoadingUI();
  14571. }
  14572. };
  14573. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14574. get: function () {
  14575. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14576. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14577. return this._loadingScreen;
  14578. },
  14579. set: function (loadingScreen) {
  14580. this._loadingScreen = loadingScreen;
  14581. },
  14582. enumerable: true,
  14583. configurable: true
  14584. });
  14585. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14586. set: function (text) {
  14587. this.loadingScreen.loadingUIText = text;
  14588. },
  14589. enumerable: true,
  14590. configurable: true
  14591. });
  14592. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14593. set: function (color) {
  14594. this.loadingScreen.loadingUIBackgroundColor = color;
  14595. },
  14596. enumerable: true,
  14597. configurable: true
  14598. });
  14599. Engine.prototype.attachContextLostEvent = function (callback) {
  14600. if (this._renderingCanvas) {
  14601. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14602. }
  14603. };
  14604. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14605. if (this._renderingCanvas) {
  14606. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14607. }
  14608. };
  14609. Engine.prototype.getVertexShaderSource = function (program) {
  14610. var shaders = this._gl.getAttachedShaders(program);
  14611. if (!shaders) {
  14612. return null;
  14613. }
  14614. return this._gl.getShaderSource(shaders[0]);
  14615. };
  14616. Engine.prototype.getFragmentShaderSource = function (program) {
  14617. var shaders = this._gl.getAttachedShaders(program);
  14618. if (!shaders) {
  14619. return null;
  14620. }
  14621. return this._gl.getShaderSource(shaders[1]);
  14622. };
  14623. Engine.prototype.getError = function () {
  14624. return this._gl.getError();
  14625. };
  14626. // FPS
  14627. Engine.prototype.getFps = function () {
  14628. return this._fps;
  14629. };
  14630. Engine.prototype.getDeltaTime = function () {
  14631. return this._deltaTime;
  14632. };
  14633. Engine.prototype._measureFps = function () {
  14634. this._performanceMonitor.sampleFrame();
  14635. this._fps = this._performanceMonitor.averageFPS;
  14636. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14637. };
  14638. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14639. if (faceIndex === void 0) { faceIndex = -1; }
  14640. var gl = this._gl;
  14641. if (!this._dummyFramebuffer) {
  14642. var dummy = gl.createFramebuffer();
  14643. if (!dummy) {
  14644. throw new Error("Unable to create dummy framebuffer");
  14645. }
  14646. this._dummyFramebuffer = dummy;
  14647. }
  14648. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14649. if (faceIndex > -1) {
  14650. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14651. }
  14652. else {
  14653. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14654. }
  14655. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14656. var buffer;
  14657. switch (readType) {
  14658. case gl.UNSIGNED_BYTE:
  14659. buffer = new Uint8Array(4 * width * height);
  14660. readType = gl.UNSIGNED_BYTE;
  14661. break;
  14662. default:
  14663. buffer = new Float32Array(4 * width * height);
  14664. readType = gl.FLOAT;
  14665. break;
  14666. }
  14667. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14668. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14669. return buffer;
  14670. };
  14671. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14672. if (this._webGLVersion > 1) {
  14673. return this._caps.colorBufferFloat;
  14674. }
  14675. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14676. };
  14677. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14678. if (this._webGLVersion > 1) {
  14679. return this._caps.colorBufferFloat;
  14680. }
  14681. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14682. };
  14683. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14684. Engine.prototype._canRenderToFramebuffer = function (type) {
  14685. var gl = this._gl;
  14686. //clear existing errors
  14687. while (gl.getError() !== gl.NO_ERROR) { }
  14688. var successful = true;
  14689. var texture = gl.createTexture();
  14690. gl.bindTexture(gl.TEXTURE_2D, texture);
  14691. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14694. var fb = gl.createFramebuffer();
  14695. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14696. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14697. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14698. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14699. successful = successful && (gl.getError() === gl.NO_ERROR);
  14700. //try render by clearing frame buffer's color buffer
  14701. if (successful) {
  14702. gl.clear(gl.COLOR_BUFFER_BIT);
  14703. successful = successful && (gl.getError() === gl.NO_ERROR);
  14704. }
  14705. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14706. if (successful) {
  14707. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14708. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14709. var readFormat = gl.RGBA;
  14710. var readType = gl.UNSIGNED_BYTE;
  14711. var buffer = new Uint8Array(4);
  14712. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14713. successful = successful && (gl.getError() === gl.NO_ERROR);
  14714. }
  14715. //clean up
  14716. gl.deleteTexture(texture);
  14717. gl.deleteFramebuffer(fb);
  14718. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14719. //clear accumulated errors
  14720. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14721. return successful;
  14722. };
  14723. Engine.prototype._getWebGLTextureType = function (type) {
  14724. if (type === Engine.TEXTURETYPE_FLOAT) {
  14725. return this._gl.FLOAT;
  14726. }
  14727. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14728. // Add Half Float Constant.
  14729. return this._gl.HALF_FLOAT_OES;
  14730. }
  14731. return this._gl.UNSIGNED_BYTE;
  14732. };
  14733. ;
  14734. /** @ignore */
  14735. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14736. if (this._webGLVersion === 1) {
  14737. return this._gl.RGBA;
  14738. }
  14739. if (type === Engine.TEXTURETYPE_FLOAT) {
  14740. if (format) {
  14741. switch (format) {
  14742. case Engine.TEXTUREFORMAT_R32F:
  14743. return this._gl.R32F;
  14744. case Engine.TEXTUREFORMAT_RG32F:
  14745. return this._gl.RG32F;
  14746. case Engine.TEXTUREFORMAT_RGB32F:
  14747. return this._gl.RGB32F;
  14748. }
  14749. }
  14750. return this._gl.RGBA32F;
  14751. }
  14752. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14753. return this._gl.RGBA16F;
  14754. }
  14755. return this._gl.RGBA;
  14756. };
  14757. ;
  14758. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14759. if (type === Engine.TEXTURETYPE_FLOAT) {
  14760. return this._gl.RGBA32F;
  14761. }
  14762. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14763. return this._gl.RGBA16F;
  14764. }
  14765. return this._gl.RGBA8;
  14766. };
  14767. ;
  14768. Engine.prototype.createQuery = function () {
  14769. return this._gl.createQuery();
  14770. };
  14771. Engine.prototype.deleteQuery = function (query) {
  14772. this._gl.deleteQuery(query);
  14773. return this;
  14774. };
  14775. Engine.prototype.isQueryResultAvailable = function (query) {
  14776. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14777. };
  14778. Engine.prototype.getQueryResult = function (query) {
  14779. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14780. };
  14781. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14782. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14783. this._gl.beginQuery(glAlgorithm, query);
  14784. return this;
  14785. };
  14786. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14787. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14788. this._gl.endQuery(glAlgorithm);
  14789. return this;
  14790. };
  14791. /* Time queries */
  14792. Engine.prototype._createTimeQuery = function () {
  14793. var timerQuery = this._caps.timerQuery;
  14794. if (timerQuery.createQueryEXT) {
  14795. return timerQuery.createQueryEXT();
  14796. }
  14797. return this.createQuery();
  14798. };
  14799. Engine.prototype._deleteTimeQuery = function (query) {
  14800. var timerQuery = this._caps.timerQuery;
  14801. if (timerQuery.deleteQueryEXT) {
  14802. timerQuery.deleteQueryEXT(query);
  14803. return;
  14804. }
  14805. this.deleteQuery(query);
  14806. };
  14807. Engine.prototype._getTimeQueryResult = function (query) {
  14808. var timerQuery = this._caps.timerQuery;
  14809. if (timerQuery.getQueryObjectEXT) {
  14810. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14811. }
  14812. return this.getQueryResult(query);
  14813. };
  14814. Engine.prototype._getTimeQueryAvailability = function (query) {
  14815. var timerQuery = this._caps.timerQuery;
  14816. if (timerQuery.getQueryObjectEXT) {
  14817. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14818. }
  14819. return this.isQueryResultAvailable(query);
  14820. };
  14821. Engine.prototype.startTimeQuery = function () {
  14822. var timerQuery = this._caps.timerQuery;
  14823. if (!timerQuery) {
  14824. return null;
  14825. }
  14826. var token = new BABYLON._TimeToken();
  14827. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14828. if (this._caps.canUseTimestampForTimerQuery) {
  14829. token._startTimeQuery = this._createTimeQuery();
  14830. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14831. }
  14832. else {
  14833. if (this._currentNonTimestampToken) {
  14834. return this._currentNonTimestampToken;
  14835. }
  14836. token._timeElapsedQuery = this._createTimeQuery();
  14837. if (timerQuery.beginQueryEXT) {
  14838. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14839. }
  14840. else {
  14841. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14842. }
  14843. this._currentNonTimestampToken = token;
  14844. }
  14845. return token;
  14846. };
  14847. Engine.prototype.endTimeQuery = function (token) {
  14848. var timerQuery = this._caps.timerQuery;
  14849. if (!timerQuery || !token) {
  14850. return -1;
  14851. }
  14852. if (this._caps.canUseTimestampForTimerQuery) {
  14853. if (!token._startTimeQuery) {
  14854. return -1;
  14855. }
  14856. if (!token._endTimeQuery) {
  14857. token._endTimeQuery = this._createTimeQuery();
  14858. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14859. }
  14860. }
  14861. else if (!token._timeElapsedQueryEnded) {
  14862. if (!token._timeElapsedQuery) {
  14863. return -1;
  14864. }
  14865. if (timerQuery.endQueryEXT) {
  14866. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14867. }
  14868. else {
  14869. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14870. }
  14871. token._timeElapsedQueryEnded = true;
  14872. }
  14873. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14874. var available = false;
  14875. if (token._endTimeQuery) {
  14876. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14877. }
  14878. else if (token._timeElapsedQuery) {
  14879. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14880. }
  14881. if (available && !disjoint) {
  14882. var result = 0;
  14883. if (this._caps.canUseTimestampForTimerQuery) {
  14884. if (!token._startTimeQuery || !token._endTimeQuery) {
  14885. return -1;
  14886. }
  14887. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14888. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14889. result = timeEnd - timeStart;
  14890. this._deleteTimeQuery(token._startTimeQuery);
  14891. this._deleteTimeQuery(token._endTimeQuery);
  14892. token._startTimeQuery = null;
  14893. token._endTimeQuery = null;
  14894. }
  14895. else {
  14896. if (!token._timeElapsedQuery) {
  14897. return -1;
  14898. }
  14899. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14900. this._deleteTimeQuery(token._timeElapsedQuery);
  14901. token._timeElapsedQuery = null;
  14902. token._timeElapsedQueryEnded = false;
  14903. this._currentNonTimestampToken = null;
  14904. }
  14905. return result;
  14906. }
  14907. return -1;
  14908. };
  14909. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14910. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14911. };
  14912. // Transform feedback
  14913. Engine.prototype.createTransformFeedback = function () {
  14914. return this._gl.createTransformFeedback();
  14915. };
  14916. Engine.prototype.deleteTransformFeedback = function (value) {
  14917. this._gl.deleteTransformFeedback(value);
  14918. };
  14919. Engine.prototype.bindTransformFeedback = function (value) {
  14920. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14921. };
  14922. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14923. if (usePoints === void 0) { usePoints = true; }
  14924. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14925. };
  14926. Engine.prototype.endTransformFeedback = function () {
  14927. this._gl.endTransformFeedback();
  14928. };
  14929. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14930. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14931. };
  14932. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14933. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14934. };
  14935. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14936. var _this = this;
  14937. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14938. this._activeRequests.push(request);
  14939. request.onCompleteObservable.add(function (request) {
  14940. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14941. });
  14942. return request;
  14943. };
  14944. /** @ignore */
  14945. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14946. var _this = this;
  14947. return new Promise(function (resolve, reject) {
  14948. _this._loadFile(url, function (data) {
  14949. resolve(data);
  14950. }, undefined, database, useArrayBuffer, function (request, exception) {
  14951. reject(exception);
  14952. });
  14953. });
  14954. };
  14955. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14956. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14957. var onload = function (data) {
  14958. loadedFiles[index] = data;
  14959. loadedFiles._internalCount++;
  14960. if (loadedFiles._internalCount === 6) {
  14961. onfinish(loadedFiles);
  14962. }
  14963. };
  14964. var onerror = function (request, exception) {
  14965. if (onErrorCallBack && request) {
  14966. onErrorCallBack(request.status + " " + request.statusText, exception);
  14967. }
  14968. };
  14969. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14970. };
  14971. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14972. if (onError === void 0) { onError = null; }
  14973. var loadedFiles = [];
  14974. loadedFiles._internalCount = 0;
  14975. for (var index = 0; index < 6; index++) {
  14976. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14977. }
  14978. };
  14979. // Statics
  14980. Engine.isSupported = function () {
  14981. try {
  14982. var tempcanvas = document.createElement("canvas");
  14983. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14984. return gl != null && !!window.WebGLRenderingContext;
  14985. }
  14986. catch (e) {
  14987. return false;
  14988. }
  14989. };
  14990. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14991. Engine.ExceptionList = [
  14992. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14993. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14994. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14995. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14996. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14997. ];
  14998. Engine.Instances = new Array();
  14999. // Const statics
  15000. Engine._ALPHA_DISABLE = 0;
  15001. Engine._ALPHA_ADD = 1;
  15002. Engine._ALPHA_COMBINE = 2;
  15003. Engine._ALPHA_SUBTRACT = 3;
  15004. Engine._ALPHA_MULTIPLY = 4;
  15005. Engine._ALPHA_MAXIMIZED = 5;
  15006. Engine._ALPHA_ONEONE = 6;
  15007. Engine._ALPHA_PREMULTIPLIED = 7;
  15008. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15009. Engine._ALPHA_INTERPOLATE = 9;
  15010. Engine._ALPHA_SCREENMODE = 10;
  15011. Engine._DELAYLOADSTATE_NONE = 0;
  15012. Engine._DELAYLOADSTATE_LOADED = 1;
  15013. Engine._DELAYLOADSTATE_LOADING = 2;
  15014. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15015. Engine._TEXTUREFORMAT_ALPHA = 0;
  15016. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15017. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15018. Engine._TEXTUREFORMAT_RGB = 4;
  15019. Engine._TEXTUREFORMAT_RGBA = 5;
  15020. Engine._TEXTUREFORMAT_R32F = 6;
  15021. Engine._TEXTUREFORMAT_RG32F = 7;
  15022. Engine._TEXTUREFORMAT_RGB32F = 8;
  15023. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15024. Engine._TEXTURETYPE_FLOAT = 1;
  15025. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15026. // Depht or Stencil test Constants.
  15027. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15028. 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.
  15029. 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.
  15030. 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.
  15031. 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.
  15032. 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.
  15033. 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.
  15034. 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.
  15035. // Stencil Actions Constants.
  15036. Engine._KEEP = 0x1E00;
  15037. Engine._REPLACE = 0x1E01;
  15038. Engine._INCR = 0x1E02;
  15039. Engine._DECR = 0x1E03;
  15040. Engine._INVERT = 0x150A;
  15041. Engine._INCR_WRAP = 0x8507;
  15042. Engine._DECR_WRAP = 0x8508;
  15043. // Texture rescaling mode
  15044. Engine._SCALEMODE_FLOOR = 1;
  15045. Engine._SCALEMODE_NEAREST = 2;
  15046. Engine._SCALEMODE_CEILING = 3;
  15047. // Updatable statics so stick with vars here
  15048. Engine.CollisionsEpsilon = 0.001;
  15049. Engine.CodeRepository = "src/";
  15050. Engine.ShadersRepository = "src/Shaders/";
  15051. return Engine;
  15052. }());
  15053. BABYLON.Engine = Engine;
  15054. })(BABYLON || (BABYLON = {}));
  15055. //# sourceMappingURL=babylon.engine.js.map
  15056. var BABYLON;
  15057. (function (BABYLON) {
  15058. /**
  15059. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15060. */
  15061. var Node = /** @class */ (function () {
  15062. /**
  15063. * Creates a new Node
  15064. * @param {string} name - the name and id to be given to this node
  15065. * @param {BABYLON.Scene} the scene this node will be added to
  15066. */
  15067. function Node(name, scene) {
  15068. if (scene === void 0) { scene = null; }
  15069. /**
  15070. * Gets or sets a string used to store user defined state for the node
  15071. */
  15072. this.state = "";
  15073. /**
  15074. * Gets or sets an object used to store user defined information for the node
  15075. */
  15076. this.metadata = null;
  15077. /**
  15078. * Gets or sets a boolean used to define if the node must be serialized
  15079. */
  15080. this.doNotSerialize = false;
  15081. /** @ignore */
  15082. this._isDisposed = false;
  15083. /**
  15084. * Gets a list of {BABYLON.Animation} associated with the node
  15085. */
  15086. this.animations = new Array();
  15087. this._ranges = {};
  15088. this._isEnabled = true;
  15089. this._isReady = true;
  15090. /** @ignore */
  15091. this._currentRenderId = -1;
  15092. this._parentRenderId = -1;
  15093. /**
  15094. * An event triggered when the mesh is disposed
  15095. * @type {BABYLON.Observable}
  15096. */
  15097. this.onDisposeObservable = new BABYLON.Observable();
  15098. // Behaviors
  15099. this._behaviors = new Array();
  15100. this.name = name;
  15101. this.id = name;
  15102. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15103. this.uniqueId = this._scene.getUniqueId();
  15104. this._initCache();
  15105. }
  15106. /**
  15107. * Gets a boolean indicating if the node has been disposed
  15108. * @returns true if the node was disposed
  15109. */
  15110. Node.prototype.isDisposed = function () {
  15111. return this._isDisposed;
  15112. };
  15113. Object.defineProperty(Node.prototype, "parent", {
  15114. get: function () {
  15115. return this._parentNode;
  15116. },
  15117. /**
  15118. * Gets or sets the parent of the node
  15119. */
  15120. set: function (parent) {
  15121. if (this._parentNode === parent) {
  15122. return;
  15123. }
  15124. // Remove self from list of children of parent
  15125. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15126. var index = this._parentNode._children.indexOf(this);
  15127. if (index !== -1) {
  15128. this._parentNode._children.splice(index, 1);
  15129. }
  15130. }
  15131. // Store new parent
  15132. this._parentNode = parent;
  15133. // Add as child to new parent
  15134. if (this._parentNode) {
  15135. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15136. this._parentNode._children = new Array();
  15137. }
  15138. this._parentNode._children.push(this);
  15139. }
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. /**
  15145. * Gets a string idenfifying the name of the class
  15146. * @returns "Node" string
  15147. */
  15148. Node.prototype.getClassName = function () {
  15149. return "Node";
  15150. };
  15151. Object.defineProperty(Node.prototype, "onDispose", {
  15152. /**
  15153. * Sets a callback that will be raised when the node will be disposed
  15154. */
  15155. set: function (callback) {
  15156. if (this._onDisposeObserver) {
  15157. this.onDisposeObservable.remove(this._onDisposeObserver);
  15158. }
  15159. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. /**
  15165. * Gets the scene of the node
  15166. * @returns a {BABYLON.Scene}
  15167. */
  15168. Node.prototype.getScene = function () {
  15169. return this._scene;
  15170. };
  15171. /**
  15172. * Gets the engine of the node
  15173. * @returns a {BABYLON.Engine}
  15174. */
  15175. Node.prototype.getEngine = function () {
  15176. return this._scene.getEngine();
  15177. };
  15178. /**
  15179. * Attach a behavior to the node
  15180. * @see http://doc.babylonjs.com/features/behaviour
  15181. * @param behavior defines the behavior to attach
  15182. * @returns the current Node
  15183. */
  15184. Node.prototype.addBehavior = function (behavior) {
  15185. var _this = this;
  15186. var index = this._behaviors.indexOf(behavior);
  15187. if (index !== -1) {
  15188. return this;
  15189. }
  15190. behavior.init();
  15191. if (this._scene.isLoading) {
  15192. // We defer the attach when the scene will be loaded
  15193. var observer = this._scene.onDataLoadedObservable.add(function () {
  15194. behavior.attach(_this);
  15195. setTimeout(function () {
  15196. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15197. _this._scene.onDataLoadedObservable.remove(observer);
  15198. }, 0);
  15199. });
  15200. }
  15201. else {
  15202. behavior.attach(this);
  15203. }
  15204. this._behaviors.push(behavior);
  15205. return this;
  15206. };
  15207. /**
  15208. * Remove an attached behavior
  15209. * @see http://doc.babylonjs.com/features/behaviour
  15210. * @param behavior defines the behavior to attach
  15211. * @returns the current Node
  15212. */
  15213. Node.prototype.removeBehavior = function (behavior) {
  15214. var index = this._behaviors.indexOf(behavior);
  15215. if (index === -1) {
  15216. return this;
  15217. }
  15218. this._behaviors[index].detach();
  15219. this._behaviors.splice(index, 1);
  15220. return this;
  15221. };
  15222. Object.defineProperty(Node.prototype, "behaviors", {
  15223. /**
  15224. * Gets the list of attached behaviors
  15225. * @see http://doc.babylonjs.com/features/behaviour
  15226. */
  15227. get: function () {
  15228. return this._behaviors;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. /**
  15234. * Gets an attached behavior by name
  15235. * @param name defines the name of the behavior to look for
  15236. * @see http://doc.babylonjs.com/features/behaviour
  15237. * @returns null if behavior was not found else the requested behavior
  15238. */
  15239. Node.prototype.getBehaviorByName = function (name) {
  15240. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15241. var behavior = _a[_i];
  15242. if (behavior.name === name) {
  15243. return behavior;
  15244. }
  15245. }
  15246. return null;
  15247. };
  15248. /**
  15249. * Returns the world matrix of the node
  15250. * @returns a matrix containing the node's world matrix
  15251. */
  15252. Node.prototype.getWorldMatrix = function () {
  15253. return BABYLON.Matrix.Identity();
  15254. };
  15255. // override it in derived class if you add new variables to the cache
  15256. // and call the parent class method
  15257. /** @ignore */
  15258. Node.prototype._initCache = function () {
  15259. this._cache = {};
  15260. this._cache.parent = undefined;
  15261. };
  15262. /** @ignore */
  15263. Node.prototype.updateCache = function (force) {
  15264. if (!force && this.isSynchronized())
  15265. return;
  15266. this._cache.parent = this.parent;
  15267. this._updateCache();
  15268. };
  15269. // override it in derived class if you add new variables to the cache
  15270. // and call the parent class method if !ignoreParentClass
  15271. /** @ignore */
  15272. Node.prototype._updateCache = function (ignoreParentClass) {
  15273. };
  15274. // override it in derived class if you add new variables to the cache
  15275. /** @ignore */
  15276. Node.prototype._isSynchronized = function () {
  15277. return true;
  15278. };
  15279. /** @ignore */
  15280. Node.prototype._markSyncedWithParent = function () {
  15281. if (this.parent) {
  15282. this._parentRenderId = this.parent._currentRenderId;
  15283. }
  15284. };
  15285. /** @ignore */
  15286. Node.prototype.isSynchronizedWithParent = function () {
  15287. if (!this.parent) {
  15288. return true;
  15289. }
  15290. if (this._parentRenderId !== this.parent._currentRenderId) {
  15291. return false;
  15292. }
  15293. return this.parent.isSynchronized();
  15294. };
  15295. /** @ignore */
  15296. Node.prototype.isSynchronized = function (updateCache) {
  15297. var check = this.hasNewParent();
  15298. check = check || !this.isSynchronizedWithParent();
  15299. check = check || !this._isSynchronized();
  15300. if (updateCache)
  15301. this.updateCache(true);
  15302. return !check;
  15303. };
  15304. /** @ignore */
  15305. Node.prototype.hasNewParent = function (update) {
  15306. if (this._cache.parent === this.parent)
  15307. return false;
  15308. if (update)
  15309. this._cache.parent = this.parent;
  15310. return true;
  15311. };
  15312. /**
  15313. * Is this node ready to be used/rendered
  15314. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15315. * @return true if the node is ready
  15316. */
  15317. Node.prototype.isReady = function (completeCheck) {
  15318. if (completeCheck === void 0) { completeCheck = false; }
  15319. return this._isReady;
  15320. };
  15321. /**
  15322. * Is this node enabled?
  15323. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  15324. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15325. * @return whether this node (and its parent) is enabled
  15326. * @see setEnabled
  15327. */
  15328. Node.prototype.isEnabled = function (checkAncestors) {
  15329. if (checkAncestors === void 0) { checkAncestors = true; }
  15330. if (checkAncestors === false) {
  15331. return this._isEnabled;
  15332. }
  15333. if (this._isEnabled === false) {
  15334. return false;
  15335. }
  15336. if (this.parent !== undefined && this.parent !== null) {
  15337. return this.parent.isEnabled(checkAncestors);
  15338. }
  15339. return true;
  15340. };
  15341. /**
  15342. * Set the enabled state of this node
  15343. * @param value defines the new enabled state
  15344. * @see isEnabled
  15345. */
  15346. Node.prototype.setEnabled = function (value) {
  15347. this._isEnabled = value;
  15348. };
  15349. /**
  15350. * Is this node a descendant of the given node?
  15351. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15352. * @param ancestor defines the parent node to inspect
  15353. * @see parent
  15354. * @returns a boolean indicating if this node is a descendant of the given node
  15355. */
  15356. Node.prototype.isDescendantOf = function (ancestor) {
  15357. if (this.parent) {
  15358. if (this.parent === ancestor) {
  15359. return true;
  15360. }
  15361. return this.parent.isDescendantOf(ancestor);
  15362. }
  15363. return false;
  15364. };
  15365. /** @ignore */
  15366. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15367. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15368. if (!this._children) {
  15369. return;
  15370. }
  15371. for (var index = 0; index < this._children.length; index++) {
  15372. var item = this._children[index];
  15373. if (!predicate || predicate(item)) {
  15374. results.push(item);
  15375. }
  15376. if (!directDescendantsOnly) {
  15377. item._getDescendants(results, false, predicate);
  15378. }
  15379. }
  15380. };
  15381. /**
  15382. * Will return all nodes that have this node as ascendant
  15383. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15384. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15385. * @return all children nodes of all types
  15386. */
  15387. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15388. var results = new Array();
  15389. this._getDescendants(results, directDescendantsOnly, predicate);
  15390. return results;
  15391. };
  15392. /**
  15393. * Get all child-meshes of this node
  15394. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15395. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15396. * @returns an array of {BABYLON.AbstractMesh}
  15397. */
  15398. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15399. var results = [];
  15400. this._getDescendants(results, directDescendantsOnly, function (node) {
  15401. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15402. });
  15403. return results;
  15404. };
  15405. /**
  15406. * Get all child-transformNodes of this node
  15407. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15408. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15409. * @returns an array of {BABYLON.TransformNode}
  15410. */
  15411. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15412. var results = [];
  15413. this._getDescendants(results, directDescendantsOnly, function (node) {
  15414. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15415. });
  15416. return results;
  15417. };
  15418. /**
  15419. * Get all direct children of this node
  15420. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15421. * @returns an array of {BABYLON.Node}
  15422. */
  15423. Node.prototype.getChildren = function (predicate) {
  15424. return this.getDescendants(true, predicate);
  15425. };
  15426. /** @ignore */
  15427. Node.prototype._setReady = function (state) {
  15428. if (state === this._isReady) {
  15429. return;
  15430. }
  15431. if (!state) {
  15432. this._isReady = false;
  15433. return;
  15434. }
  15435. this._isReady = true;
  15436. if (this.onReady) {
  15437. this.onReady(this);
  15438. }
  15439. };
  15440. /**
  15441. * Get an animation by name
  15442. * @param name defines the name of the animation to look for
  15443. * @returns null if not found else the requested animation
  15444. */
  15445. Node.prototype.getAnimationByName = function (name) {
  15446. for (var i = 0; i < this.animations.length; i++) {
  15447. var animation = this.animations[i];
  15448. if (animation.name === name) {
  15449. return animation;
  15450. }
  15451. }
  15452. return null;
  15453. };
  15454. /**
  15455. * Creates an animation range for this node
  15456. * @param name defines the name of the range
  15457. * @param from defines the starting key
  15458. * @param to defines the end key
  15459. */
  15460. Node.prototype.createAnimationRange = function (name, from, to) {
  15461. // check name not already in use
  15462. if (!this._ranges[name]) {
  15463. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15464. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15465. if (this.animations[i]) {
  15466. this.animations[i].createRange(name, from, to);
  15467. }
  15468. }
  15469. }
  15470. };
  15471. /**
  15472. * Delete a specific animation range
  15473. * @param name defines the name of the range to delete
  15474. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15475. */
  15476. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15477. if (deleteFrames === void 0) { deleteFrames = true; }
  15478. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15479. if (this.animations[i]) {
  15480. this.animations[i].deleteRange(name, deleteFrames);
  15481. }
  15482. }
  15483. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15484. };
  15485. /**
  15486. * Get an animation range by name
  15487. * @param name defines the name of the animation range to look for
  15488. * @returns null if not found else the requested animation range
  15489. */
  15490. Node.prototype.getAnimationRange = function (name) {
  15491. return this._ranges[name];
  15492. };
  15493. /**
  15494. * Will start the animation sequence
  15495. * @param name defines the range frames for animation sequence
  15496. * @param loop defines if the animation should loop (false by default)
  15497. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15498. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15499. * @returns the object created for this animation. If range does not exist, it will return null
  15500. */
  15501. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15502. var range = this.getAnimationRange(name);
  15503. if (!range) {
  15504. return null;
  15505. }
  15506. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15507. };
  15508. /**
  15509. * Serialize animation ranges into a JSON compatible object
  15510. * @returns serialization object
  15511. */
  15512. Node.prototype.serializeAnimationRanges = function () {
  15513. var serializationRanges = [];
  15514. for (var name in this._ranges) {
  15515. var localRange = this._ranges[name];
  15516. if (!localRange) {
  15517. continue;
  15518. }
  15519. var range = {};
  15520. range.name = name;
  15521. range.from = localRange.from;
  15522. range.to = localRange.to;
  15523. serializationRanges.push(range);
  15524. }
  15525. return serializationRanges;
  15526. };
  15527. /**
  15528. * Computes the world matrix of the node
  15529. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15530. * @returns the world matrix
  15531. */
  15532. Node.prototype.computeWorldMatrix = function (force) {
  15533. return BABYLON.Matrix.Identity();
  15534. };
  15535. /**
  15536. * Releases all associated resources
  15537. */
  15538. Node.prototype.dispose = function () {
  15539. this.parent = null;
  15540. // Callback
  15541. this.onDisposeObservable.notifyObservers(this);
  15542. this.onDisposeObservable.clear();
  15543. // Behaviors
  15544. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15545. var behavior = _a[_i];
  15546. behavior.detach();
  15547. }
  15548. this._behaviors = [];
  15549. this._isDisposed = true;
  15550. };
  15551. /**
  15552. * Parse animation range data from a serialization object and store them into a given node
  15553. * @param node defines where to store the animation ranges
  15554. * @param parsedNode defines the serialization object to read data from
  15555. * @param scene defines the hosting scene
  15556. */
  15557. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15558. if (parsedNode.ranges) {
  15559. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15560. var data = parsedNode.ranges[index];
  15561. node.createAnimationRange(data.name, data.from, data.to);
  15562. }
  15563. }
  15564. };
  15565. __decorate([
  15566. BABYLON.serialize()
  15567. ], Node.prototype, "name", void 0);
  15568. __decorate([
  15569. BABYLON.serialize()
  15570. ], Node.prototype, "id", void 0);
  15571. __decorate([
  15572. BABYLON.serialize()
  15573. ], Node.prototype, "uniqueId", void 0);
  15574. __decorate([
  15575. BABYLON.serialize()
  15576. ], Node.prototype, "state", void 0);
  15577. __decorate([
  15578. BABYLON.serialize()
  15579. ], Node.prototype, "metadata", void 0);
  15580. return Node;
  15581. }());
  15582. BABYLON.Node = Node;
  15583. })(BABYLON || (BABYLON = {}));
  15584. //# sourceMappingURL=babylon.node.js.map
  15585. var BABYLON;
  15586. (function (BABYLON) {
  15587. var BoundingSphere = /** @class */ (function () {
  15588. function BoundingSphere(minimum, maximum) {
  15589. this.minimum = minimum;
  15590. this.maximum = maximum;
  15591. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15592. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15593. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15594. this.radius = distance * 0.5;
  15595. this.centerWorld = BABYLON.Vector3.Zero();
  15596. this._update(BABYLON.Matrix.Identity());
  15597. }
  15598. // Methods
  15599. BoundingSphere.prototype._update = function (world) {
  15600. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15601. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15602. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15603. };
  15604. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15605. for (var i = 0; i < 6; i++) {
  15606. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15607. return false;
  15608. }
  15609. return true;
  15610. };
  15611. BoundingSphere.prototype.intersectsPoint = function (point) {
  15612. var x = this.centerWorld.x - point.x;
  15613. var y = this.centerWorld.y - point.y;
  15614. var z = this.centerWorld.z - point.z;
  15615. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15616. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15617. return false;
  15618. return true;
  15619. };
  15620. // Statics
  15621. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15622. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15623. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15624. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15625. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15626. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15627. return false;
  15628. return true;
  15629. };
  15630. return BoundingSphere;
  15631. }());
  15632. BABYLON.BoundingSphere = BoundingSphere;
  15633. })(BABYLON || (BABYLON = {}));
  15634. //# sourceMappingURL=babylon.boundingSphere.js.map
  15635. var BABYLON;
  15636. (function (BABYLON) {
  15637. var BoundingBox = /** @class */ (function () {
  15638. function BoundingBox(minimum, maximum) {
  15639. this.minimum = minimum;
  15640. this.maximum = maximum;
  15641. this.vectors = new Array();
  15642. this.vectorsWorld = new Array();
  15643. // Bounding vectors
  15644. this.vectors.push(this.minimum.clone());
  15645. this.vectors.push(this.maximum.clone());
  15646. this.vectors.push(this.minimum.clone());
  15647. this.vectors[2].x = this.maximum.x;
  15648. this.vectors.push(this.minimum.clone());
  15649. this.vectors[3].y = this.maximum.y;
  15650. this.vectors.push(this.minimum.clone());
  15651. this.vectors[4].z = this.maximum.z;
  15652. this.vectors.push(this.maximum.clone());
  15653. this.vectors[5].z = this.minimum.z;
  15654. this.vectors.push(this.maximum.clone());
  15655. this.vectors[6].x = this.minimum.x;
  15656. this.vectors.push(this.maximum.clone());
  15657. this.vectors[7].y = this.minimum.y;
  15658. // OBB
  15659. this.center = this.maximum.add(this.minimum).scale(0.5);
  15660. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15661. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15662. // World
  15663. for (var index = 0; index < this.vectors.length; index++) {
  15664. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15665. }
  15666. this.minimumWorld = BABYLON.Vector3.Zero();
  15667. this.maximumWorld = BABYLON.Vector3.Zero();
  15668. this.centerWorld = BABYLON.Vector3.Zero();
  15669. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15670. this._update(BABYLON.Matrix.Identity());
  15671. }
  15672. // Methods
  15673. BoundingBox.prototype.getWorldMatrix = function () {
  15674. return this._worldMatrix;
  15675. };
  15676. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15677. this._worldMatrix.copyFrom(matrix);
  15678. return this;
  15679. };
  15680. BoundingBox.prototype._update = function (world) {
  15681. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15682. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15683. for (var index = 0; index < this.vectors.length; index++) {
  15684. var v = this.vectorsWorld[index];
  15685. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15686. if (v.x < this.minimumWorld.x)
  15687. this.minimumWorld.x = v.x;
  15688. if (v.y < this.minimumWorld.y)
  15689. this.minimumWorld.y = v.y;
  15690. if (v.z < this.minimumWorld.z)
  15691. this.minimumWorld.z = v.z;
  15692. if (v.x > this.maximumWorld.x)
  15693. this.maximumWorld.x = v.x;
  15694. if (v.y > this.maximumWorld.y)
  15695. this.maximumWorld.y = v.y;
  15696. if (v.z > this.maximumWorld.z)
  15697. this.maximumWorld.z = v.z;
  15698. }
  15699. // Extend
  15700. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15701. this.extendSizeWorld.scaleInPlace(0.5);
  15702. // OBB
  15703. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15704. this.centerWorld.scaleInPlace(0.5);
  15705. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15706. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15707. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15708. this._worldMatrix = world;
  15709. };
  15710. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15711. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15712. };
  15713. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15714. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15715. };
  15716. BoundingBox.prototype.intersectsPoint = function (point) {
  15717. var delta = -BABYLON.Epsilon;
  15718. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15719. return false;
  15720. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15721. return false;
  15722. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15723. return false;
  15724. return true;
  15725. };
  15726. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15727. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15728. };
  15729. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15730. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15731. return false;
  15732. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15733. return false;
  15734. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15735. return false;
  15736. return true;
  15737. };
  15738. // Statics
  15739. BoundingBox.Intersects = function (box0, box1) {
  15740. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15741. return false;
  15742. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15743. return false;
  15744. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15745. return false;
  15746. return true;
  15747. };
  15748. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15749. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15750. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15751. return (num <= (sphereRadius * sphereRadius));
  15752. };
  15753. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15754. for (var p = 0; p < 6; p++) {
  15755. for (var i = 0; i < 8; i++) {
  15756. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15757. return false;
  15758. }
  15759. }
  15760. }
  15761. return true;
  15762. };
  15763. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15764. for (var p = 0; p < 6; p++) {
  15765. var inCount = 8;
  15766. for (var i = 0; i < 8; i++) {
  15767. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15768. --inCount;
  15769. }
  15770. else {
  15771. break;
  15772. }
  15773. }
  15774. if (inCount === 0)
  15775. return false;
  15776. }
  15777. return true;
  15778. };
  15779. return BoundingBox;
  15780. }());
  15781. BABYLON.BoundingBox = BoundingBox;
  15782. })(BABYLON || (BABYLON = {}));
  15783. //# sourceMappingURL=babylon.boundingBox.js.map
  15784. var BABYLON;
  15785. (function (BABYLON) {
  15786. var computeBoxExtents = function (axis, box) {
  15787. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15788. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15789. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15790. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15791. var r = r0 + r1 + r2;
  15792. return {
  15793. min: p - r,
  15794. max: p + r
  15795. };
  15796. };
  15797. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15798. var axisOverlap = function (axis, box0, box1) {
  15799. var result0 = computeBoxExtents(axis, box0);
  15800. var result1 = computeBoxExtents(axis, box1);
  15801. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15802. };
  15803. var BoundingInfo = /** @class */ (function () {
  15804. function BoundingInfo(minimum, maximum) {
  15805. this.minimum = minimum;
  15806. this.maximum = maximum;
  15807. this._isLocked = false;
  15808. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15809. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15810. }
  15811. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15812. get: function () {
  15813. return this._isLocked;
  15814. },
  15815. set: function (value) {
  15816. this._isLocked = value;
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. // Methods
  15822. BoundingInfo.prototype.update = function (world) {
  15823. if (this._isLocked) {
  15824. return;
  15825. }
  15826. this.boundingBox._update(world);
  15827. this.boundingSphere._update(world);
  15828. };
  15829. /**
  15830. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15831. * @param center New center of the bounding info
  15832. * @param extend New extend of the bounding info
  15833. */
  15834. BoundingInfo.prototype.centerOn = function (center, extend) {
  15835. this.minimum = center.subtract(extend);
  15836. this.maximum = center.add(extend);
  15837. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15838. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15839. return this;
  15840. };
  15841. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15842. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15843. return false;
  15844. return this.boundingBox.isInFrustum(frustumPlanes);
  15845. };
  15846. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15847. /**
  15848. * Gets the world distance between the min and max points of the bounding box
  15849. */
  15850. get: function () {
  15851. var boundingBox = this.boundingBox;
  15852. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15853. return size.length();
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15859. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15860. };
  15861. BoundingInfo.prototype._checkCollision = function (collider) {
  15862. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15863. };
  15864. BoundingInfo.prototype.intersectsPoint = function (point) {
  15865. if (!this.boundingSphere.centerWorld) {
  15866. return false;
  15867. }
  15868. if (!this.boundingSphere.intersectsPoint(point)) {
  15869. return false;
  15870. }
  15871. if (!this.boundingBox.intersectsPoint(point)) {
  15872. return false;
  15873. }
  15874. return true;
  15875. };
  15876. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15877. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15878. return false;
  15879. }
  15880. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15881. return false;
  15882. }
  15883. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15884. return false;
  15885. }
  15886. if (!precise) {
  15887. return true;
  15888. }
  15889. var box0 = this.boundingBox;
  15890. var box1 = boundingInfo.boundingBox;
  15891. if (!axisOverlap(box0.directions[0], box0, box1))
  15892. return false;
  15893. if (!axisOverlap(box0.directions[1], box0, box1))
  15894. return false;
  15895. if (!axisOverlap(box0.directions[2], box0, box1))
  15896. return false;
  15897. if (!axisOverlap(box1.directions[0], box0, box1))
  15898. return false;
  15899. if (!axisOverlap(box1.directions[1], box0, box1))
  15900. return false;
  15901. if (!axisOverlap(box1.directions[2], box0, box1))
  15902. return false;
  15903. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15904. return false;
  15905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15906. return false;
  15907. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15908. return false;
  15909. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15910. return false;
  15911. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15912. return false;
  15913. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15914. return false;
  15915. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15916. return false;
  15917. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15918. return false;
  15919. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15920. return false;
  15921. return true;
  15922. };
  15923. return BoundingInfo;
  15924. }());
  15925. BABYLON.BoundingInfo = BoundingInfo;
  15926. })(BABYLON || (BABYLON = {}));
  15927. //# sourceMappingURL=babylon.boundingInfo.js.map
  15928. var BABYLON;
  15929. (function (BABYLON) {
  15930. var TransformNode = /** @class */ (function (_super) {
  15931. __extends(TransformNode, _super);
  15932. function TransformNode(name, scene, isPure) {
  15933. if (scene === void 0) { scene = null; }
  15934. if (isPure === void 0) { isPure = true; }
  15935. var _this = _super.call(this, name, scene) || this;
  15936. // Properties
  15937. _this._rotation = BABYLON.Vector3.Zero();
  15938. _this._scaling = BABYLON.Vector3.One();
  15939. _this._isDirty = false;
  15940. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15941. _this.scalingDeterminant = 1;
  15942. _this.infiniteDistance = false;
  15943. _this.position = BABYLON.Vector3.Zero();
  15944. _this._localWorld = BABYLON.Matrix.Zero();
  15945. _this._worldMatrix = BABYLON.Matrix.Zero();
  15946. _this._worldMatrixDeterminant = 0;
  15947. _this._absolutePosition = BABYLON.Vector3.Zero();
  15948. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15949. _this._postMultiplyPivotMatrix = false;
  15950. _this._isWorldMatrixFrozen = false;
  15951. /**
  15952. * An event triggered after the world matrix is updated
  15953. * @type {BABYLON.Observable}
  15954. */
  15955. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15956. _this._nonUniformScaling = false;
  15957. if (isPure) {
  15958. _this.getScene().addTransformNode(_this);
  15959. }
  15960. return _this;
  15961. }
  15962. Object.defineProperty(TransformNode.prototype, "rotation", {
  15963. /**
  15964. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15965. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15966. * Default : (0.0, 0.0, 0.0)
  15967. */
  15968. get: function () {
  15969. return this._rotation;
  15970. },
  15971. set: function (newRotation) {
  15972. this._rotation = newRotation;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(TransformNode.prototype, "scaling", {
  15978. /**
  15979. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15980. * Default : (1.0, 1.0, 1.0)
  15981. */
  15982. get: function () {
  15983. return this._scaling;
  15984. },
  15985. /**
  15986. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15987. * Default : (1.0, 1.0, 1.0)
  15988. */
  15989. set: function (newScaling) {
  15990. this._scaling = newScaling;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15996. /**
  15997. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15998. * It's null by default.
  15999. * 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)
  16000. */
  16001. get: function () {
  16002. return this._rotationQuaternion;
  16003. },
  16004. set: function (quaternion) {
  16005. this._rotationQuaternion = quaternion;
  16006. //reset the rotation vector.
  16007. if (quaternion && this.rotation.length()) {
  16008. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16009. }
  16010. },
  16011. enumerable: true,
  16012. configurable: true
  16013. });
  16014. /**
  16015. * Returns the latest update of the World matrix
  16016. * Returns a Matrix.
  16017. */
  16018. TransformNode.prototype.getWorldMatrix = function () {
  16019. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16020. this.computeWorldMatrix();
  16021. }
  16022. return this._worldMatrix;
  16023. };
  16024. /**
  16025. * Returns the latest update of the World matrix determinant.
  16026. */
  16027. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16028. return this._worldMatrixDeterminant;
  16029. };
  16030. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16031. /**
  16032. * Returns directly the latest state of the mesh World matrix.
  16033. * A Matrix is returned.
  16034. */
  16035. get: function () {
  16036. return this._worldMatrix;
  16037. },
  16038. enumerable: true,
  16039. configurable: true
  16040. });
  16041. /**
  16042. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16043. * Returns the AbstractMesh.
  16044. */
  16045. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16046. this._poseMatrix.copyFrom(matrix);
  16047. return this;
  16048. };
  16049. /**
  16050. * Returns the mesh Pose matrix.
  16051. * Returned object : Matrix
  16052. */
  16053. TransformNode.prototype.getPoseMatrix = function () {
  16054. return this._poseMatrix;
  16055. };
  16056. TransformNode.prototype._isSynchronized = function () {
  16057. if (this._isDirty) {
  16058. return false;
  16059. }
  16060. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16061. return false;
  16062. if (this._cache.pivotMatrixUpdated) {
  16063. return false;
  16064. }
  16065. if (this.infiniteDistance) {
  16066. return false;
  16067. }
  16068. if (!this._cache.position.equals(this.position))
  16069. return false;
  16070. if (this.rotationQuaternion) {
  16071. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16072. return false;
  16073. }
  16074. if (!this._cache.rotation.equals(this.rotation))
  16075. return false;
  16076. if (!this._cache.scaling.equals(this.scaling))
  16077. return false;
  16078. return true;
  16079. };
  16080. TransformNode.prototype._initCache = function () {
  16081. _super.prototype._initCache.call(this);
  16082. this._cache.localMatrixUpdated = false;
  16083. this._cache.position = BABYLON.Vector3.Zero();
  16084. this._cache.scaling = BABYLON.Vector3.Zero();
  16085. this._cache.rotation = BABYLON.Vector3.Zero();
  16086. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16087. this._cache.billboardMode = -1;
  16088. };
  16089. TransformNode.prototype.markAsDirty = function (property) {
  16090. if (property === "rotation") {
  16091. this.rotationQuaternion = null;
  16092. }
  16093. this._currentRenderId = Number.MAX_VALUE;
  16094. this._isDirty = true;
  16095. return this;
  16096. };
  16097. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16098. /**
  16099. * Returns the current mesh absolute position.
  16100. * Retuns a Vector3.
  16101. */
  16102. get: function () {
  16103. return this._absolutePosition;
  16104. },
  16105. enumerable: true,
  16106. configurable: true
  16107. });
  16108. /**
  16109. * Sets a new matrix to apply before all other transformation
  16110. * @param matrix defines the transform matrix
  16111. * @returns the current TransformNode
  16112. */
  16113. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16114. return this.setPivotMatrix(matrix, false);
  16115. };
  16116. /**
  16117. * Sets a new pivot matrix to the current node
  16118. * @param matrix defines the new pivot matrix to use
  16119. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16120. * @returns the current TransformNode
  16121. */
  16122. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16123. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16124. this._pivotMatrix = matrix.clone();
  16125. this._cache.pivotMatrixUpdated = true;
  16126. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16127. if (this._postMultiplyPivotMatrix) {
  16128. if (!this._pivotMatrixInverse) {
  16129. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16130. }
  16131. else {
  16132. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16133. }
  16134. }
  16135. return this;
  16136. };
  16137. /**
  16138. * Returns the mesh pivot matrix.
  16139. * Default : Identity.
  16140. * A Matrix is returned.
  16141. */
  16142. TransformNode.prototype.getPivotMatrix = function () {
  16143. return this._pivotMatrix;
  16144. };
  16145. /**
  16146. * Prevents the World matrix to be computed any longer.
  16147. * Returns the AbstractMesh.
  16148. */
  16149. TransformNode.prototype.freezeWorldMatrix = function () {
  16150. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16151. this.computeWorldMatrix(true);
  16152. this._isWorldMatrixFrozen = true;
  16153. return this;
  16154. };
  16155. /**
  16156. * Allows back the World matrix computation.
  16157. * Returns the AbstractMesh.
  16158. */
  16159. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16160. this._isWorldMatrixFrozen = false;
  16161. this.computeWorldMatrix(true);
  16162. return this;
  16163. };
  16164. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16165. /**
  16166. * True if the World matrix has been frozen.
  16167. * Returns a boolean.
  16168. */
  16169. get: function () {
  16170. return this._isWorldMatrixFrozen;
  16171. },
  16172. enumerable: true,
  16173. configurable: true
  16174. });
  16175. /**
  16176. * Retuns the mesh absolute position in the World.
  16177. * Returns a Vector3.
  16178. */
  16179. TransformNode.prototype.getAbsolutePosition = function () {
  16180. this.computeWorldMatrix();
  16181. return this._absolutePosition;
  16182. };
  16183. /**
  16184. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16185. * Returns the AbstractMesh.
  16186. */
  16187. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16188. if (!absolutePosition) {
  16189. return this;
  16190. }
  16191. var absolutePositionX;
  16192. var absolutePositionY;
  16193. var absolutePositionZ;
  16194. if (absolutePosition.x === undefined) {
  16195. if (arguments.length < 3) {
  16196. return this;
  16197. }
  16198. absolutePositionX = arguments[0];
  16199. absolutePositionY = arguments[1];
  16200. absolutePositionZ = arguments[2];
  16201. }
  16202. else {
  16203. absolutePositionX = absolutePosition.x;
  16204. absolutePositionY = absolutePosition.y;
  16205. absolutePositionZ = absolutePosition.z;
  16206. }
  16207. if (this.parent) {
  16208. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16209. invertParentWorldMatrix.invert();
  16210. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16211. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16212. }
  16213. else {
  16214. this.position.x = absolutePositionX;
  16215. this.position.y = absolutePositionY;
  16216. this.position.z = absolutePositionZ;
  16217. }
  16218. return this;
  16219. };
  16220. /**
  16221. * Sets the mesh position in its local space.
  16222. * Returns the AbstractMesh.
  16223. */
  16224. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16225. this.computeWorldMatrix();
  16226. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16227. return this;
  16228. };
  16229. /**
  16230. * Returns the mesh position in the local space from the current World matrix values.
  16231. * Returns a new Vector3.
  16232. */
  16233. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16234. this.computeWorldMatrix();
  16235. var invLocalWorldMatrix = this._localWorld.clone();
  16236. invLocalWorldMatrix.invert();
  16237. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16238. };
  16239. /**
  16240. * Translates the mesh along the passed Vector3 in its local space.
  16241. * Returns the AbstractMesh.
  16242. */
  16243. TransformNode.prototype.locallyTranslate = function (vector3) {
  16244. this.computeWorldMatrix(true);
  16245. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16246. return this;
  16247. };
  16248. /**
  16249. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16250. * @param targetPoint the position (must be in same space as current mesh) to look at
  16251. * @param yawCor optional yaw (y-axis) correction in radians
  16252. * @param pitchCor optional pitch (x-axis) correction in radians
  16253. * @param rollCor optional roll (z-axis) correction in radians
  16254. * @param space the choosen space of the target
  16255. * @returns the TransformNode.
  16256. */
  16257. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16258. if (yawCor === void 0) { yawCor = 0; }
  16259. if (pitchCor === void 0) { pitchCor = 0; }
  16260. if (rollCor === void 0) { rollCor = 0; }
  16261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16262. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16263. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16264. targetPoint.subtractToRef(pos, dv);
  16265. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16266. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16267. var pitch = Math.atan2(dv.y, len);
  16268. if (this.rotationQuaternion) {
  16269. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16270. }
  16271. else {
  16272. this.rotation.x = pitch + pitchCor;
  16273. this.rotation.y = yaw + yawCor;
  16274. this.rotation.z = rollCor;
  16275. }
  16276. return this;
  16277. };
  16278. /**
  16279. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16280. * This Vector3 is expressed in the World space.
  16281. */
  16282. TransformNode.prototype.getDirection = function (localAxis) {
  16283. var result = BABYLON.Vector3.Zero();
  16284. this.getDirectionToRef(localAxis, result);
  16285. return result;
  16286. };
  16287. /**
  16288. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16289. * localAxis is expressed in the mesh local space.
  16290. * result is computed in the Wordl space from the mesh World matrix.
  16291. * Returns the AbstractMesh.
  16292. */
  16293. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16294. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16295. return this;
  16296. };
  16297. /**
  16298. * Sets a new pivot point to the current node
  16299. * @param point defines the new pivot point to use
  16300. * @param space defines if the point is in world or local space (local by default)
  16301. * @returns the current TransformNode
  16302. */
  16303. TransformNode.prototype.setPivotPoint = function (point, space) {
  16304. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16305. if (this.getScene().getRenderId() == 0) {
  16306. this.computeWorldMatrix(true);
  16307. }
  16308. var wm = this.getWorldMatrix();
  16309. if (space == BABYLON.Space.WORLD) {
  16310. var tmat = BABYLON.Tmp.Matrix[0];
  16311. wm.invertToRef(tmat);
  16312. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16313. }
  16314. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16315. };
  16316. /**
  16317. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16318. */
  16319. TransformNode.prototype.getPivotPoint = function () {
  16320. var point = BABYLON.Vector3.Zero();
  16321. this.getPivotPointToRef(point);
  16322. return point;
  16323. };
  16324. /**
  16325. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16326. * Returns the AbstractMesh.
  16327. */
  16328. TransformNode.prototype.getPivotPointToRef = function (result) {
  16329. result.x = -this._pivotMatrix.m[12];
  16330. result.y = -this._pivotMatrix.m[13];
  16331. result.z = -this._pivotMatrix.m[14];
  16332. return this;
  16333. };
  16334. /**
  16335. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16336. */
  16337. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16338. var point = BABYLON.Vector3.Zero();
  16339. this.getAbsolutePivotPointToRef(point);
  16340. return point;
  16341. };
  16342. /**
  16343. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16344. * Returns the AbstractMesh.
  16345. */
  16346. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16347. result.x = this._pivotMatrix.m[12];
  16348. result.y = this._pivotMatrix.m[13];
  16349. result.z = this._pivotMatrix.m[14];
  16350. this.getPivotPointToRef(result);
  16351. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16352. return this;
  16353. };
  16354. /**
  16355. * Defines the passed node as the parent of the current node.
  16356. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16357. * Returns the TransformNode.
  16358. */
  16359. TransformNode.prototype.setParent = function (node) {
  16360. if (node === null) {
  16361. var rotation = BABYLON.Tmp.Quaternion[0];
  16362. var position = BABYLON.Tmp.Vector3[0];
  16363. var scale = BABYLON.Tmp.Vector3[1];
  16364. if (this.parent && this.parent.computeWorldMatrix) {
  16365. this.parent.computeWorldMatrix(true);
  16366. }
  16367. this.computeWorldMatrix(true);
  16368. this.getWorldMatrix().decompose(scale, rotation, position);
  16369. if (this.rotationQuaternion) {
  16370. this.rotationQuaternion.copyFrom(rotation);
  16371. }
  16372. else {
  16373. rotation.toEulerAnglesToRef(this.rotation);
  16374. }
  16375. this.scaling.x = scale.x;
  16376. this.scaling.y = scale.y;
  16377. this.scaling.z = scale.z;
  16378. this.position.x = position.x;
  16379. this.position.y = position.y;
  16380. this.position.z = position.z;
  16381. }
  16382. else {
  16383. var rotation = BABYLON.Tmp.Quaternion[0];
  16384. var position = BABYLON.Tmp.Vector3[0];
  16385. var scale = BABYLON.Tmp.Vector3[1];
  16386. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16387. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16388. this.computeWorldMatrix(true);
  16389. node.computeWorldMatrix(true);
  16390. node.getWorldMatrix().invertToRef(invParentMatrix);
  16391. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16392. diffMatrix.decompose(scale, rotation, position);
  16393. if (this.rotationQuaternion) {
  16394. this.rotationQuaternion.copyFrom(rotation);
  16395. }
  16396. else {
  16397. rotation.toEulerAnglesToRef(this.rotation);
  16398. }
  16399. this.position.x = position.x;
  16400. this.position.y = position.y;
  16401. this.position.z = position.z;
  16402. this.scaling.x = scale.x;
  16403. this.scaling.y = scale.y;
  16404. this.scaling.z = scale.z;
  16405. }
  16406. this.parent = node;
  16407. return this;
  16408. };
  16409. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16410. get: function () {
  16411. return this._nonUniformScaling;
  16412. },
  16413. enumerable: true,
  16414. configurable: true
  16415. });
  16416. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16417. if (this._nonUniformScaling === value) {
  16418. return false;
  16419. }
  16420. this._nonUniformScaling = true;
  16421. return true;
  16422. };
  16423. /**
  16424. * Attach the current TransformNode to another TransformNode associated with a bone
  16425. * @param bone Bone affecting the TransformNode
  16426. * @param affectedTransformNode TransformNode associated with the bone
  16427. */
  16428. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16429. this._transformToBoneReferal = affectedTransformNode;
  16430. this.parent = bone;
  16431. if (bone.getWorldMatrix().determinant() < 0) {
  16432. this.scalingDeterminant *= -1;
  16433. }
  16434. return this;
  16435. };
  16436. TransformNode.prototype.detachFromBone = function () {
  16437. if (!this.parent) {
  16438. return this;
  16439. }
  16440. if (this.parent.getWorldMatrix().determinant() < 0) {
  16441. this.scalingDeterminant *= -1;
  16442. }
  16443. this._transformToBoneReferal = null;
  16444. this.parent = null;
  16445. return this;
  16446. };
  16447. /**
  16448. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16449. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16450. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16451. * The passed axis is also normalized.
  16452. * Returns the AbstractMesh.
  16453. */
  16454. TransformNode.prototype.rotate = function (axis, amount, space) {
  16455. axis.normalize();
  16456. if (!this.rotationQuaternion) {
  16457. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16458. this.rotation = BABYLON.Vector3.Zero();
  16459. }
  16460. var rotationQuaternion;
  16461. if (!space || space === BABYLON.Space.LOCAL) {
  16462. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16463. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16464. }
  16465. else {
  16466. if (this.parent) {
  16467. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16468. invertParentWorldMatrix.invert();
  16469. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16470. }
  16471. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16472. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16473. }
  16474. return this;
  16475. };
  16476. /**
  16477. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16478. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16479. * The passed axis is also normalized.
  16480. * Returns the AbstractMesh.
  16481. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16482. */
  16483. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16484. axis.normalize();
  16485. if (!this.rotationQuaternion) {
  16486. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16487. this.rotation.copyFromFloats(0, 0, 0);
  16488. }
  16489. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16490. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16491. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16492. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16493. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16494. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16495. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16496. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16497. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16498. return this;
  16499. };
  16500. /**
  16501. * Translates the mesh along the axis vector for the passed distance in the given space.
  16502. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16503. * Returns the AbstractMesh.
  16504. */
  16505. TransformNode.prototype.translate = function (axis, distance, space) {
  16506. var displacementVector = axis.scale(distance);
  16507. if (!space || space === BABYLON.Space.LOCAL) {
  16508. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16509. this.setPositionWithLocalVector(tempV3);
  16510. }
  16511. else {
  16512. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16513. }
  16514. return this;
  16515. };
  16516. /**
  16517. * Adds a rotation step to the mesh current rotation.
  16518. * x, y, z are Euler angles expressed in radians.
  16519. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16520. * This means this rotation is made in the mesh local space only.
  16521. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16522. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16523. * ```javascript
  16524. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16525. * ```
  16526. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16527. * 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.
  16528. * Returns the AbstractMesh.
  16529. */
  16530. TransformNode.prototype.addRotation = function (x, y, z) {
  16531. var rotationQuaternion;
  16532. if (this.rotationQuaternion) {
  16533. rotationQuaternion = this.rotationQuaternion;
  16534. }
  16535. else {
  16536. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16537. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16538. }
  16539. var accumulation = BABYLON.Tmp.Quaternion[0];
  16540. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16541. rotationQuaternion.multiplyInPlace(accumulation);
  16542. if (!this.rotationQuaternion) {
  16543. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16544. }
  16545. return this;
  16546. };
  16547. /**
  16548. * Computes the mesh World matrix and returns it.
  16549. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16550. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16551. * If the parameter `force`is set to `true`, the actual computation is done.
  16552. * Returns the mesh World Matrix.
  16553. */
  16554. TransformNode.prototype.computeWorldMatrix = function (force) {
  16555. if (this._isWorldMatrixFrozen) {
  16556. return this._worldMatrix;
  16557. }
  16558. if (!force && this.isSynchronized(true)) {
  16559. return this._worldMatrix;
  16560. }
  16561. this._cache.position.copyFrom(this.position);
  16562. this._cache.scaling.copyFrom(this.scaling);
  16563. this._cache.pivotMatrixUpdated = false;
  16564. this._cache.billboardMode = this.billboardMode;
  16565. this._currentRenderId = this.getScene().getRenderId();
  16566. this._isDirty = false;
  16567. // Scaling
  16568. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16569. // Rotation
  16570. //rotate, if quaternion is set and rotation was used
  16571. if (this.rotationQuaternion) {
  16572. var len = this.rotation.length();
  16573. if (len) {
  16574. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16575. this.rotation.copyFromFloats(0, 0, 0);
  16576. }
  16577. }
  16578. if (this.rotationQuaternion) {
  16579. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16580. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16581. }
  16582. else {
  16583. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16584. this._cache.rotation.copyFrom(this.rotation);
  16585. }
  16586. // Translation
  16587. var camera = this.getScene().activeCamera;
  16588. if (this.infiniteDistance && !this.parent && camera) {
  16589. var cameraWorldMatrix = camera.getWorldMatrix();
  16590. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16591. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16592. }
  16593. else {
  16594. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16595. }
  16596. // Composing transformations
  16597. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16598. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16599. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16600. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16601. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16602. // Need to decompose each rotation here
  16603. var currentPosition = BABYLON.Tmp.Vector3[3];
  16604. if (this.parent && this.parent.getWorldMatrix) {
  16605. if (this._transformToBoneReferal) {
  16606. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16607. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16608. }
  16609. else {
  16610. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16611. }
  16612. }
  16613. else {
  16614. currentPosition.copyFrom(this.position);
  16615. }
  16616. currentPosition.subtractInPlace(camera.globalPosition);
  16617. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16618. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16619. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16620. }
  16621. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16622. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16623. }
  16624. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16625. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16626. }
  16627. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16628. }
  16629. else {
  16630. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16631. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16632. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16633. }
  16634. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16635. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16636. }
  16637. // Local world
  16638. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16639. // Parent
  16640. if (this.parent && this.parent.getWorldMatrix) {
  16641. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16642. if (this._transformToBoneReferal) {
  16643. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16644. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16645. }
  16646. else {
  16647. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16648. }
  16649. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16650. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16651. this._worldMatrix.copyFrom(this._localWorld);
  16652. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16653. }
  16654. else {
  16655. if (this._transformToBoneReferal) {
  16656. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16657. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16658. }
  16659. else {
  16660. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16661. }
  16662. }
  16663. this._markSyncedWithParent();
  16664. }
  16665. else {
  16666. this._worldMatrix.copyFrom(this._localWorld);
  16667. }
  16668. // Post multiply inverse of pivotMatrix
  16669. if (this._postMultiplyPivotMatrix) {
  16670. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16671. }
  16672. // Normal matrix
  16673. if (this.scaling.isNonUniform) {
  16674. this._updateNonUniformScalingState(true);
  16675. }
  16676. else if (this.parent && this.parent._nonUniformScaling) {
  16677. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16678. }
  16679. else {
  16680. this._updateNonUniformScalingState(false);
  16681. }
  16682. this._afterComputeWorldMatrix();
  16683. // Absolute position
  16684. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16685. // Callbacks
  16686. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16687. if (!this._poseMatrix) {
  16688. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16689. }
  16690. // Cache the determinant
  16691. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16692. return this._worldMatrix;
  16693. };
  16694. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16695. };
  16696. /**
  16697. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16698. * @param func: callback function to add
  16699. *
  16700. * Returns the TransformNode.
  16701. */
  16702. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16703. this.onAfterWorldMatrixUpdateObservable.add(func);
  16704. return this;
  16705. };
  16706. /**
  16707. * Removes a registered callback function.
  16708. * Returns the TransformNode.
  16709. */
  16710. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16711. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16712. return this;
  16713. };
  16714. /**
  16715. * Clone the current transform node
  16716. * Returns the new transform node
  16717. * @param name Name of the new clone
  16718. * @param newParent New parent for the clone
  16719. * @param doNotCloneChildren Do not clone children hierarchy
  16720. */
  16721. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16722. var _this = this;
  16723. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16724. result.name = name;
  16725. result.id = name;
  16726. if (newParent) {
  16727. result.parent = newParent;
  16728. }
  16729. if (!doNotCloneChildren) {
  16730. // Children
  16731. var directDescendants = this.getDescendants(true);
  16732. for (var index = 0; index < directDescendants.length; index++) {
  16733. var child = directDescendants[index];
  16734. if (child.clone) {
  16735. child.clone(name + "." + child.name, result);
  16736. }
  16737. }
  16738. }
  16739. return result;
  16740. };
  16741. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16742. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16743. serializationObject.type = this.getClassName();
  16744. // Parent
  16745. if (this.parent) {
  16746. serializationObject.parentId = this.parent.id;
  16747. }
  16748. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16749. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16750. }
  16751. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16752. serializationObject.isEnabled = this.isEnabled();
  16753. // Parent
  16754. if (this.parent) {
  16755. serializationObject.parentId = this.parent.id;
  16756. }
  16757. return serializationObject;
  16758. };
  16759. // Statics
  16760. /**
  16761. * Returns a new TransformNode object parsed from the source provided.
  16762. * The parameter `parsedMesh` is the source.
  16763. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16764. */
  16765. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16766. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16767. if (BABYLON.Tags) {
  16768. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16769. }
  16770. if (parsedTransformNode.localMatrix) {
  16771. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16772. }
  16773. else if (parsedTransformNode.pivotMatrix) {
  16774. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16775. }
  16776. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16777. // Parent
  16778. if (parsedTransformNode.parentId) {
  16779. transformNode._waitingParentId = parsedTransformNode.parentId;
  16780. }
  16781. return transformNode;
  16782. };
  16783. /**
  16784. * Disposes the TransformNode.
  16785. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16786. * Returns nothing.
  16787. */
  16788. TransformNode.prototype.dispose = function (doNotRecurse) {
  16789. // Animations
  16790. this.getScene().stopAnimation(this);
  16791. // Remove from scene
  16792. this.getScene().removeTransformNode(this);
  16793. if (!doNotRecurse) {
  16794. // Children
  16795. var objects = this.getDescendants(true);
  16796. for (var index = 0; index < objects.length; index++) {
  16797. objects[index].dispose();
  16798. }
  16799. }
  16800. else {
  16801. var childMeshes = this.getChildMeshes(true);
  16802. for (index = 0; index < childMeshes.length; index++) {
  16803. var child = childMeshes[index];
  16804. child.parent = null;
  16805. child.computeWorldMatrix(true);
  16806. }
  16807. }
  16808. this.onAfterWorldMatrixUpdateObservable.clear();
  16809. _super.prototype.dispose.call(this);
  16810. };
  16811. // Statics
  16812. TransformNode.BILLBOARDMODE_NONE = 0;
  16813. TransformNode.BILLBOARDMODE_X = 1;
  16814. TransformNode.BILLBOARDMODE_Y = 2;
  16815. TransformNode.BILLBOARDMODE_Z = 4;
  16816. TransformNode.BILLBOARDMODE_ALL = 7;
  16817. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16818. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16819. __decorate([
  16820. BABYLON.serializeAsVector3()
  16821. ], TransformNode.prototype, "_rotation", void 0);
  16822. __decorate([
  16823. BABYLON.serializeAsQuaternion()
  16824. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16825. __decorate([
  16826. BABYLON.serializeAsVector3()
  16827. ], TransformNode.prototype, "_scaling", void 0);
  16828. __decorate([
  16829. BABYLON.serialize()
  16830. ], TransformNode.prototype, "billboardMode", void 0);
  16831. __decorate([
  16832. BABYLON.serialize()
  16833. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16834. __decorate([
  16835. BABYLON.serialize()
  16836. ], TransformNode.prototype, "infiniteDistance", void 0);
  16837. __decorate([
  16838. BABYLON.serializeAsVector3()
  16839. ], TransformNode.prototype, "position", void 0);
  16840. return TransformNode;
  16841. }(BABYLON.Node));
  16842. BABYLON.TransformNode = TransformNode;
  16843. })(BABYLON || (BABYLON = {}));
  16844. //# sourceMappingURL=babylon.transformNode.js.map
  16845. var BABYLON;
  16846. (function (BABYLON) {
  16847. var AbstractMesh = /** @class */ (function (_super) {
  16848. __extends(AbstractMesh, _super);
  16849. // Constructor
  16850. function AbstractMesh(name, scene) {
  16851. if (scene === void 0) { scene = null; }
  16852. var _this = _super.call(this, name, scene, false) || this;
  16853. _this._facetNb = 0; // facet number
  16854. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16855. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16856. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16857. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16858. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16859. _this._subDiv = {
  16860. max: 1,
  16861. X: 1,
  16862. Y: 1,
  16863. Z: 1
  16864. };
  16865. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16866. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16867. // Events
  16868. /**
  16869. * An event triggered when this mesh collides with another one
  16870. * @type {BABYLON.Observable}
  16871. */
  16872. _this.onCollideObservable = new BABYLON.Observable();
  16873. /**
  16874. * An event triggered when the collision's position changes
  16875. * @type {BABYLON.Observable}
  16876. */
  16877. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16878. /**
  16879. * An event triggered when material is changed
  16880. * @type {BABYLON.Observable}
  16881. */
  16882. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16883. // Properties
  16884. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16885. /**
  16886. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16887. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16888. * or
  16889. * 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.
  16890. * for more info check WebGl documentations
  16891. */
  16892. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16893. /**
  16894. * 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:
  16895. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16896. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16897. * 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.
  16898. */
  16899. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16900. /**
  16901. * 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.
  16902. * The default value is -1 which means don't break the query and wait till the result.
  16903. */
  16904. _this.occlusionRetryCount = -1;
  16905. _this._occlusionInternalRetryCounter = 0;
  16906. _this._isOccluded = false;
  16907. _this._isOcclusionQueryInProgress = false;
  16908. _this._visibility = 1.0;
  16909. _this.alphaIndex = Number.MAX_VALUE;
  16910. _this.isVisible = true;
  16911. _this.isPickable = true;
  16912. _this.showBoundingBox = false;
  16913. _this.showSubMeshesBoundingBox = false;
  16914. _this.isBlocker = false;
  16915. _this.enablePointerMoveEvents = false;
  16916. _this.renderingGroupId = 0;
  16917. _this._receiveShadows = false;
  16918. _this.renderOutline = false;
  16919. _this.outlineColor = BABYLON.Color3.Red();
  16920. _this.outlineWidth = 0.02;
  16921. _this.renderOverlay = false;
  16922. _this.overlayColor = BABYLON.Color3.Red();
  16923. _this.overlayAlpha = 0.5;
  16924. _this._hasVertexAlpha = false;
  16925. _this._useVertexColors = true;
  16926. _this._computeBonesUsingShaders = true;
  16927. _this._numBoneInfluencers = 4;
  16928. _this._applyFog = true;
  16929. _this.useOctreeForRenderingSelection = true;
  16930. _this.useOctreeForPicking = true;
  16931. _this.useOctreeForCollisions = true;
  16932. _this._layerMask = 0x0FFFFFFF;
  16933. /**
  16934. * True if the mesh must be rendered in any case.
  16935. */
  16936. _this.alwaysSelectAsActiveMesh = false;
  16937. /**
  16938. * This scene's action manager
  16939. * @type {BABYLON.ActionManager}
  16940. */
  16941. _this.actionManager = null;
  16942. // Physics
  16943. _this.physicsImpostor = null;
  16944. // Collisions
  16945. _this._checkCollisions = false;
  16946. _this._collisionMask = -1;
  16947. _this._collisionGroup = -1;
  16948. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16949. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16950. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16951. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16952. // Edges
  16953. _this.edgesWidth = 1;
  16954. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16955. // Cache
  16956. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16957. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16958. _this._renderId = 0;
  16959. _this._intersectionsInProgress = new Array();
  16960. _this._unIndexed = false;
  16961. _this._lightSources = new Array();
  16962. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16963. if (collidedMesh === void 0) { collidedMesh = null; }
  16964. //TODO move this to the collision coordinator!
  16965. if (_this.getScene().workerCollisions)
  16966. newPosition.multiplyInPlace(_this._collider._radius);
  16967. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16968. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16969. _this.position.addInPlace(_this._diffPositionForCollisions);
  16970. }
  16971. if (collidedMesh) {
  16972. _this.onCollideObservable.notifyObservers(collidedMesh);
  16973. }
  16974. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16975. };
  16976. _this.getScene().addMesh(_this);
  16977. _this._resyncLightSources();
  16978. return _this;
  16979. }
  16980. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16981. get: function () {
  16982. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16983. },
  16984. enumerable: true,
  16985. configurable: true
  16986. });
  16987. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16988. get: function () {
  16989. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16995. get: function () {
  16996. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17002. get: function () {
  17003. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17004. },
  17005. enumerable: true,
  17006. configurable: true
  17007. });
  17008. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17009. get: function () {
  17010. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17016. /**
  17017. * Read-only : the number of facets in the mesh
  17018. */
  17019. get: function () {
  17020. return this._facetNb;
  17021. },
  17022. enumerable: true,
  17023. configurable: true
  17024. });
  17025. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17026. /**
  17027. * The number (integer) of subdivisions per axis in the partioning space
  17028. */
  17029. get: function () {
  17030. return this._partitioningSubdivisions;
  17031. },
  17032. set: function (nb) {
  17033. this._partitioningSubdivisions = nb;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17039. /**
  17040. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17041. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17042. */
  17043. get: function () {
  17044. return this._partitioningBBoxRatio;
  17045. },
  17046. set: function (ratio) {
  17047. this._partitioningBBoxRatio = ratio;
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17053. /**
  17054. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17055. * Works only for updatable meshes.
  17056. * Doesn't work with multi-materials.
  17057. */
  17058. get: function () {
  17059. return this._facetDepthSort;
  17060. },
  17061. set: function (sort) {
  17062. this._facetDepthSort = sort;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17068. /**
  17069. * The location (Vector3) where the facet depth sort must be computed from.
  17070. * By default, the active camera position.
  17071. * Used only when facet depth sort is enabled.
  17072. */
  17073. get: function () {
  17074. return this._facetDepthSortFrom;
  17075. },
  17076. set: function (location) {
  17077. this._facetDepthSortFrom = location;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17083. /**
  17084. * Read-only boolean : is the feature facetData enabled ?
  17085. */
  17086. get: function () {
  17087. return this._facetDataEnabled;
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17093. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17094. return false;
  17095. }
  17096. this._markSubMeshesAsMiscDirty();
  17097. return true;
  17098. };
  17099. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17100. set: function (callback) {
  17101. if (this._onCollideObserver) {
  17102. this.onCollideObservable.remove(this._onCollideObserver);
  17103. }
  17104. this._onCollideObserver = this.onCollideObservable.add(callback);
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17110. set: function (callback) {
  17111. if (this._onCollisionPositionChangeObserver) {
  17112. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17113. }
  17114. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17120. /**
  17121. * 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.
  17122. */
  17123. get: function () {
  17124. return this._isOccluded;
  17125. },
  17126. set: function (value) {
  17127. this._isOccluded = value;
  17128. },
  17129. enumerable: true,
  17130. configurable: true
  17131. });
  17132. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17133. /**
  17134. * Flag to check the progress status of the query
  17135. */
  17136. get: function () {
  17137. return this._isOcclusionQueryInProgress;
  17138. },
  17139. enumerable: true,
  17140. configurable: true
  17141. });
  17142. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17143. /**
  17144. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17145. */
  17146. get: function () {
  17147. return this._visibility;
  17148. },
  17149. /**
  17150. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17151. */
  17152. set: function (value) {
  17153. if (this._visibility === value) {
  17154. return;
  17155. }
  17156. this._visibility = value;
  17157. this._markSubMeshesAsMiscDirty();
  17158. },
  17159. enumerable: true,
  17160. configurable: true
  17161. });
  17162. Object.defineProperty(AbstractMesh.prototype, "material", {
  17163. get: function () {
  17164. return this._material;
  17165. },
  17166. set: function (value) {
  17167. if (this._material === value) {
  17168. return;
  17169. }
  17170. this._material = value;
  17171. if (this.onMaterialChangedObservable.hasObservers) {
  17172. this.onMaterialChangedObservable.notifyObservers(this);
  17173. }
  17174. if (!this.subMeshes) {
  17175. return;
  17176. }
  17177. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17178. var subMesh = _a[_i];
  17179. subMesh.setEffect(null);
  17180. }
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17186. get: function () {
  17187. return this._receiveShadows;
  17188. },
  17189. set: function (value) {
  17190. if (this._receiveShadows === value) {
  17191. return;
  17192. }
  17193. this._receiveShadows = value;
  17194. this._markSubMeshesAsLightDirty();
  17195. },
  17196. enumerable: true,
  17197. configurable: true
  17198. });
  17199. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17200. get: function () {
  17201. return this._hasVertexAlpha;
  17202. },
  17203. set: function (value) {
  17204. if (this._hasVertexAlpha === value) {
  17205. return;
  17206. }
  17207. this._hasVertexAlpha = value;
  17208. this._markSubMeshesAsAttributesDirty();
  17209. this._markSubMeshesAsMiscDirty();
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17215. get: function () {
  17216. return this._useVertexColors;
  17217. },
  17218. set: function (value) {
  17219. if (this._useVertexColors === value) {
  17220. return;
  17221. }
  17222. this._useVertexColors = value;
  17223. this._markSubMeshesAsAttributesDirty();
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17229. get: function () {
  17230. return this._computeBonesUsingShaders;
  17231. },
  17232. set: function (value) {
  17233. if (this._computeBonesUsingShaders === value) {
  17234. return;
  17235. }
  17236. this._computeBonesUsingShaders = value;
  17237. this._markSubMeshesAsAttributesDirty();
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17243. get: function () {
  17244. return this._numBoneInfluencers;
  17245. },
  17246. set: function (value) {
  17247. if (this._numBoneInfluencers === value) {
  17248. return;
  17249. }
  17250. this._numBoneInfluencers = value;
  17251. this._markSubMeshesAsAttributesDirty();
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17257. get: function () {
  17258. return this._applyFog;
  17259. },
  17260. set: function (value) {
  17261. if (this._applyFog === value) {
  17262. return;
  17263. }
  17264. this._applyFog = value;
  17265. this._markSubMeshesAsMiscDirty();
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17271. get: function () {
  17272. return this._layerMask;
  17273. },
  17274. set: function (value) {
  17275. if (value === this._layerMask) {
  17276. return;
  17277. }
  17278. this._layerMask = value;
  17279. this._resyncLightSources();
  17280. },
  17281. enumerable: true,
  17282. configurable: true
  17283. });
  17284. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17285. get: function () {
  17286. return this._collisionMask;
  17287. },
  17288. set: function (mask) {
  17289. this._collisionMask = !isNaN(mask) ? mask : -1;
  17290. },
  17291. enumerable: true,
  17292. configurable: true
  17293. });
  17294. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17295. get: function () {
  17296. return this._collisionGroup;
  17297. },
  17298. set: function (mask) {
  17299. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17300. },
  17301. enumerable: true,
  17302. configurable: true
  17303. });
  17304. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17305. get: function () {
  17306. return null;
  17307. },
  17308. enumerable: true,
  17309. configurable: true
  17310. });
  17311. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17312. get: function () {
  17313. return this._skeleton;
  17314. },
  17315. set: function (value) {
  17316. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17317. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17318. }
  17319. if (value && value.needInitialSkinMatrix) {
  17320. value._registerMeshWithPoseMatrix(this);
  17321. }
  17322. this._skeleton = value;
  17323. if (!this._skeleton) {
  17324. this._bonesTransformMatrices = null;
  17325. }
  17326. this._markSubMeshesAsAttributesDirty();
  17327. },
  17328. enumerable: true,
  17329. configurable: true
  17330. });
  17331. /**
  17332. * Returns the string "AbstractMesh"
  17333. */
  17334. AbstractMesh.prototype.getClassName = function () {
  17335. return "AbstractMesh";
  17336. };
  17337. /**
  17338. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17339. */
  17340. AbstractMesh.prototype.toString = function (fullDetails) {
  17341. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17342. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17343. if (this._skeleton) {
  17344. ret += ", skeleton: " + this._skeleton.name;
  17345. }
  17346. if (fullDetails) {
  17347. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17348. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17349. }
  17350. return ret;
  17351. };
  17352. AbstractMesh.prototype._rebuild = function () {
  17353. if (this._occlusionQuery) {
  17354. this._occlusionQuery = null;
  17355. }
  17356. if (this._edgesRenderer) {
  17357. this._edgesRenderer._rebuild();
  17358. }
  17359. if (!this.subMeshes) {
  17360. return;
  17361. }
  17362. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17363. var subMesh = _a[_i];
  17364. subMesh._rebuild();
  17365. }
  17366. };
  17367. AbstractMesh.prototype._resyncLightSources = function () {
  17368. this._lightSources.length = 0;
  17369. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17370. var light = _a[_i];
  17371. if (!light.isEnabled()) {
  17372. continue;
  17373. }
  17374. if (light.canAffectMesh(this)) {
  17375. this._lightSources.push(light);
  17376. }
  17377. }
  17378. this._markSubMeshesAsLightDirty();
  17379. };
  17380. AbstractMesh.prototype._resyncLighSource = function (light) {
  17381. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17382. var index = this._lightSources.indexOf(light);
  17383. if (index === -1) {
  17384. if (!isIn) {
  17385. return;
  17386. }
  17387. this._lightSources.push(light);
  17388. }
  17389. else {
  17390. if (isIn) {
  17391. return;
  17392. }
  17393. this._lightSources.splice(index, 1);
  17394. }
  17395. this._markSubMeshesAsLightDirty();
  17396. };
  17397. AbstractMesh.prototype._removeLightSource = function (light) {
  17398. var index = this._lightSources.indexOf(light);
  17399. if (index === -1) {
  17400. return;
  17401. }
  17402. this._lightSources.splice(index, 1);
  17403. this._markSubMeshesAsLightDirty();
  17404. };
  17405. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17406. if (!this.subMeshes) {
  17407. return;
  17408. }
  17409. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17410. var subMesh = _a[_i];
  17411. if (subMesh._materialDefines) {
  17412. func(subMesh._materialDefines);
  17413. }
  17414. }
  17415. };
  17416. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17417. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17418. };
  17419. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17420. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17421. };
  17422. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17423. if (!this.subMeshes) {
  17424. return;
  17425. }
  17426. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17427. var subMesh = _a[_i];
  17428. var material = subMesh.getMaterial();
  17429. if (material) {
  17430. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17431. }
  17432. }
  17433. };
  17434. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17435. /**
  17436. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17437. * Default : (1.0, 1.0, 1.0)
  17438. */
  17439. get: function () {
  17440. return this._scaling;
  17441. },
  17442. /**
  17443. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17444. * Default : (1.0, 1.0, 1.0)
  17445. */
  17446. set: function (newScaling) {
  17447. this._scaling = newScaling;
  17448. if (this.physicsImpostor) {
  17449. this.physicsImpostor.forceUpdate();
  17450. }
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. // Methods
  17456. /**
  17457. * Disables the mesh edger rendering mode.
  17458. * Returns the AbstractMesh.
  17459. */
  17460. AbstractMesh.prototype.disableEdgesRendering = function () {
  17461. if (this._edgesRenderer) {
  17462. this._edgesRenderer.dispose();
  17463. this._edgesRenderer = null;
  17464. }
  17465. return this;
  17466. };
  17467. /**
  17468. * Enables the edge rendering mode on the mesh.
  17469. * This mode makes the mesh edges visible.
  17470. * Returns the AbstractMesh.
  17471. */
  17472. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17473. if (epsilon === void 0) { epsilon = 0.95; }
  17474. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17475. this.disableEdgesRendering();
  17476. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17477. return this;
  17478. };
  17479. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17480. /**
  17481. * Returns true if the mesh is blocked. Used by the class Mesh.
  17482. * Returns the boolean `false` by default.
  17483. */
  17484. get: function () {
  17485. return false;
  17486. },
  17487. enumerable: true,
  17488. configurable: true
  17489. });
  17490. /**
  17491. * Returns the mesh itself by default, used by the class Mesh.
  17492. * Returned type : AbstractMesh
  17493. */
  17494. AbstractMesh.prototype.getLOD = function (camera) {
  17495. return this;
  17496. };
  17497. /**
  17498. * Returns 0 by default, used by the class Mesh.
  17499. * Returns an integer.
  17500. */
  17501. AbstractMesh.prototype.getTotalVertices = function () {
  17502. return 0;
  17503. };
  17504. /**
  17505. * Returns null by default, used by the class Mesh.
  17506. * Returned type : integer array
  17507. */
  17508. AbstractMesh.prototype.getIndices = function () {
  17509. return null;
  17510. };
  17511. /**
  17512. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17513. * Returned type : float array or Float32Array
  17514. */
  17515. AbstractMesh.prototype.getVerticesData = function (kind) {
  17516. return null;
  17517. };
  17518. /**
  17519. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17520. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17521. * The `data` are either a numeric array either a Float32Array.
  17522. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17523. * 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).
  17524. * Note that a new underlying VertexBuffer object is created each call.
  17525. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17526. *
  17527. * Possible `kind` values :
  17528. * - BABYLON.VertexBuffer.PositionKind
  17529. * - BABYLON.VertexBuffer.UVKind
  17530. * - BABYLON.VertexBuffer.UV2Kind
  17531. * - BABYLON.VertexBuffer.UV3Kind
  17532. * - BABYLON.VertexBuffer.UV4Kind
  17533. * - BABYLON.VertexBuffer.UV5Kind
  17534. * - BABYLON.VertexBuffer.UV6Kind
  17535. * - BABYLON.VertexBuffer.ColorKind
  17536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17540. *
  17541. * Returns the Mesh.
  17542. */
  17543. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17544. return this;
  17545. };
  17546. /**
  17547. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17548. * If the mesh has no geometry, it is simply returned as it is.
  17549. * The `data` are either a numeric array either a Float32Array.
  17550. * No new underlying VertexBuffer object is created.
  17551. * 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.
  17552. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17553. *
  17554. * Possible `kind` values :
  17555. * - BABYLON.VertexBuffer.PositionKind
  17556. * - BABYLON.VertexBuffer.UVKind
  17557. * - BABYLON.VertexBuffer.UV2Kind
  17558. * - BABYLON.VertexBuffer.UV3Kind
  17559. * - BABYLON.VertexBuffer.UV4Kind
  17560. * - BABYLON.VertexBuffer.UV5Kind
  17561. * - BABYLON.VertexBuffer.UV6Kind
  17562. * - BABYLON.VertexBuffer.ColorKind
  17563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17567. *
  17568. * Returns the Mesh.
  17569. */
  17570. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17571. return this;
  17572. };
  17573. /**
  17574. * Sets the mesh indices.
  17575. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17576. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17577. * This method creates a new index buffer each call.
  17578. * Returns the Mesh.
  17579. */
  17580. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17581. return this;
  17582. };
  17583. /** Returns false by default, used by the class Mesh.
  17584. * Returns a boolean
  17585. */
  17586. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17587. return false;
  17588. };
  17589. /**
  17590. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17591. * Returns a BoundingInfo
  17592. */
  17593. AbstractMesh.prototype.getBoundingInfo = function () {
  17594. if (this._masterMesh) {
  17595. return this._masterMesh.getBoundingInfo();
  17596. }
  17597. if (!this._boundingInfo) {
  17598. // this._boundingInfo is being created here
  17599. this._updateBoundingInfo();
  17600. }
  17601. // cannot be null.
  17602. return this._boundingInfo;
  17603. };
  17604. /**
  17605. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17606. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17607. */
  17608. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17609. if (includeDescendants === void 0) { includeDescendants = true; }
  17610. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17611. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17612. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17613. if (maxDimension === 0) {
  17614. return this;
  17615. }
  17616. var scale = 1 / maxDimension;
  17617. this.scaling.scaleInPlace(scale);
  17618. return this;
  17619. };
  17620. /**
  17621. * Sets a mesh new object BoundingInfo.
  17622. * Returns the AbstractMesh.
  17623. */
  17624. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17625. this._boundingInfo = boundingInfo;
  17626. return this;
  17627. };
  17628. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17629. get: function () {
  17630. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. AbstractMesh.prototype._preActivate = function () {
  17636. };
  17637. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17638. };
  17639. AbstractMesh.prototype._activate = function (renderId) {
  17640. this._renderId = renderId;
  17641. };
  17642. /**
  17643. * Returns the latest update of the World matrix
  17644. * Returns a Matrix.
  17645. */
  17646. AbstractMesh.prototype.getWorldMatrix = function () {
  17647. if (this._masterMesh) {
  17648. return this._masterMesh.getWorldMatrix();
  17649. }
  17650. return _super.prototype.getWorldMatrix.call(this);
  17651. };
  17652. /**
  17653. * Returns the latest update of the World matrix determinant.
  17654. */
  17655. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17656. if (this._masterMesh) {
  17657. return this._masterMesh._getWorldMatrixDeterminant();
  17658. }
  17659. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17660. };
  17661. // ================================== Point of View Movement =================================
  17662. /**
  17663. * Perform relative position change from the point of view of behind the front of the mesh.
  17664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17665. * Supports definition of mesh facing forward or backward.
  17666. * @param {number} amountRight
  17667. * @param {number} amountUp
  17668. * @param {number} amountForward
  17669. *
  17670. * Returns the AbstractMesh.
  17671. */
  17672. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17673. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17674. return this;
  17675. };
  17676. /**
  17677. * Calculate relative position change from the point of view of behind the front of the mesh.
  17678. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17679. * Supports definition of mesh facing forward or backward.
  17680. * @param {number} amountRight
  17681. * @param {number} amountUp
  17682. * @param {number} amountForward
  17683. *
  17684. * Returns a new Vector3.
  17685. */
  17686. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17687. var rotMatrix = new BABYLON.Matrix();
  17688. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17689. rotQuaternion.toRotationMatrix(rotMatrix);
  17690. var translationDelta = BABYLON.Vector3.Zero();
  17691. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17693. return translationDelta;
  17694. };
  17695. // ================================== Point of View Rotation =================================
  17696. /**
  17697. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17698. * Supports definition of mesh facing forward or backward.
  17699. * @param {number} flipBack
  17700. * @param {number} twirlClockwise
  17701. * @param {number} tiltRight
  17702. *
  17703. * Returns the AbstractMesh.
  17704. */
  17705. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17706. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17707. return this;
  17708. };
  17709. /**
  17710. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17711. * Supports definition of mesh facing forward or backward.
  17712. * @param {number} flipBack
  17713. * @param {number} twirlClockwise
  17714. * @param {number} tiltRight
  17715. *
  17716. * Returns a new Vector3.
  17717. */
  17718. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17719. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17720. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17721. };
  17722. /**
  17723. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17724. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17725. */
  17726. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17727. if (includeDescendants === void 0) { includeDescendants = true; }
  17728. this.computeWorldMatrix(true);
  17729. var min;
  17730. var max;
  17731. var boundingInfo = this.getBoundingInfo();
  17732. if (!this.subMeshes) {
  17733. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17734. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17735. }
  17736. else {
  17737. min = boundingInfo.boundingBox.minimumWorld;
  17738. max = boundingInfo.boundingBox.maximumWorld;
  17739. }
  17740. if (includeDescendants) {
  17741. var descendants = this.getDescendants(false);
  17742. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17743. var descendant = descendants_1[_i];
  17744. var childMesh = descendant;
  17745. childMesh.computeWorldMatrix(true);
  17746. //make sure we have the needed params to get mix and max
  17747. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17748. continue;
  17749. }
  17750. var childBoundingInfo = childMesh.getBoundingInfo();
  17751. var boundingBox = childBoundingInfo.boundingBox;
  17752. var minBox = boundingBox.minimumWorld;
  17753. var maxBox = boundingBox.maximumWorld;
  17754. BABYLON.Tools.CheckExtends(minBox, min, max);
  17755. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17756. }
  17757. }
  17758. return {
  17759. min: min,
  17760. max: max
  17761. };
  17762. };
  17763. /**
  17764. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17765. * Returns the AbstractMesh.
  17766. */
  17767. AbstractMesh.prototype._updateBoundingInfo = function () {
  17768. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17769. this._boundingInfo.update(this.worldMatrixFromCache);
  17770. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17771. return this;
  17772. };
  17773. /**
  17774. * Update a mesh's children BoundingInfo objects only.
  17775. * Returns the AbstractMesh.
  17776. */
  17777. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17778. if (!this.subMeshes) {
  17779. return this;
  17780. }
  17781. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17782. var subMesh = this.subMeshes[subIndex];
  17783. if (!subMesh.IsGlobal) {
  17784. subMesh.updateBoundingInfo(matrix);
  17785. }
  17786. }
  17787. return this;
  17788. };
  17789. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17790. // Bounding info
  17791. this._updateBoundingInfo();
  17792. };
  17793. /**
  17794. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17795. * A mesh is in the frustum if its bounding box intersects the frustum.
  17796. * Boolean returned.
  17797. */
  17798. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17799. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17800. };
  17801. /**
  17802. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17803. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17804. * Boolean returned.
  17805. */
  17806. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17807. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17808. ;
  17809. };
  17810. /**
  17811. * True if the mesh intersects another mesh or a SolidParticle object.
  17812. * 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)
  17813. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17814. * Returns a boolean.
  17815. */
  17816. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17817. if (precise === void 0) { precise = false; }
  17818. if (!this._boundingInfo || !mesh._boundingInfo) {
  17819. return false;
  17820. }
  17821. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17822. return true;
  17823. }
  17824. if (includeDescendants) {
  17825. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17826. var child = _a[_i];
  17827. if (child.intersectsMesh(mesh, precise, true)) {
  17828. return true;
  17829. }
  17830. }
  17831. }
  17832. return false;
  17833. };
  17834. /**
  17835. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17836. * Returns a boolean.
  17837. */
  17838. AbstractMesh.prototype.intersectsPoint = function (point) {
  17839. if (!this._boundingInfo) {
  17840. return false;
  17841. }
  17842. return this._boundingInfo.intersectsPoint(point);
  17843. };
  17844. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17845. return this.physicsImpostor;
  17846. };
  17847. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17848. if (camera === void 0) { camera = null; }
  17849. if (!camera) {
  17850. camera = this.getScene().activeCamera;
  17851. }
  17852. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17853. };
  17854. /**
  17855. * Returns the distance from the mesh to the active camera.
  17856. * Returns a float.
  17857. */
  17858. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17859. if (camera === void 0) { camera = null; }
  17860. if (!camera) {
  17861. camera = this.getScene().activeCamera;
  17862. }
  17863. return this.absolutePosition.subtract(camera.position).length();
  17864. };
  17865. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17866. if (!this.physicsImpostor) {
  17867. return this;
  17868. }
  17869. this.physicsImpostor.applyImpulse(force, contactPoint);
  17870. return this;
  17871. };
  17872. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17873. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17874. return this;
  17875. }
  17876. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17877. mainPivot: pivot1,
  17878. connectedPivot: pivot2,
  17879. nativeParams: options
  17880. });
  17881. return this;
  17882. };
  17883. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17884. // Collisions
  17885. /**
  17886. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17887. * Default `false`.
  17888. */
  17889. get: function () {
  17890. return this._checkCollisions;
  17891. },
  17892. set: function (collisionEnabled) {
  17893. this._checkCollisions = collisionEnabled;
  17894. if (this.getScene().workerCollisions) {
  17895. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17896. }
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17902. /**
  17903. * Gets Collider object used to compute collisions (not physics)
  17904. */
  17905. get: function () {
  17906. return this._collider;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17912. var globalPosition = this.getAbsolutePosition();
  17913. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17914. if (!this._collider) {
  17915. this._collider = new BABYLON.Collider();
  17916. }
  17917. this._collider._radius = this.ellipsoid;
  17918. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17919. return this;
  17920. };
  17921. // Submeshes octree
  17922. /**
  17923. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17924. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17925. * Returns an Octree of submeshes.
  17926. */
  17927. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17928. if (maxCapacity === void 0) { maxCapacity = 64; }
  17929. if (maxDepth === void 0) { maxDepth = 2; }
  17930. if (!this._submeshesOctree) {
  17931. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17932. }
  17933. this.computeWorldMatrix(true);
  17934. var boundingInfo = this.getBoundingInfo();
  17935. // Update octree
  17936. var bbox = boundingInfo.boundingBox;
  17937. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17938. return this._submeshesOctree;
  17939. };
  17940. // Collisions
  17941. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17942. this._generatePointsArray();
  17943. if (!this._positions) {
  17944. return this;
  17945. }
  17946. // Transformation
  17947. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17948. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17949. subMesh._lastColliderWorldVertices = [];
  17950. subMesh._trianglePlanes = [];
  17951. var start = subMesh.verticesStart;
  17952. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17953. for (var i = start; i < end; i++) {
  17954. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17955. }
  17956. }
  17957. // Collide
  17958. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17959. if (collider.collisionFound) {
  17960. collider.collidedMesh = this;
  17961. }
  17962. return this;
  17963. };
  17964. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17965. var subMeshes;
  17966. var len;
  17967. // Octrees
  17968. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17969. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17970. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17971. len = intersections.length;
  17972. subMeshes = intersections.data;
  17973. }
  17974. else {
  17975. subMeshes = this.subMeshes;
  17976. len = subMeshes.length;
  17977. }
  17978. for (var index = 0; index < len; index++) {
  17979. var subMesh = subMeshes[index];
  17980. // Bounding test
  17981. if (len > 1 && !subMesh._checkCollision(collider))
  17982. continue;
  17983. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17984. }
  17985. return this;
  17986. };
  17987. AbstractMesh.prototype._checkCollision = function (collider) {
  17988. // Bounding box test
  17989. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17990. return this;
  17991. // Transformation matrix
  17992. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17993. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17994. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17995. return this;
  17996. };
  17997. // Picking
  17998. AbstractMesh.prototype._generatePointsArray = function () {
  17999. return false;
  18000. };
  18001. /**
  18002. * Checks if the passed Ray intersects with the mesh.
  18003. * Returns an object PickingInfo.
  18004. */
  18005. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18006. var pickingInfo = new BABYLON.PickingInfo();
  18007. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18008. return pickingInfo;
  18009. }
  18010. if (!this._generatePointsArray()) {
  18011. return pickingInfo;
  18012. }
  18013. var intersectInfo = null;
  18014. // Octrees
  18015. var subMeshes;
  18016. var len;
  18017. if (this._submeshesOctree && this.useOctreeForPicking) {
  18018. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18019. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18020. len = intersections.length;
  18021. subMeshes = intersections.data;
  18022. }
  18023. else {
  18024. subMeshes = this.subMeshes;
  18025. len = subMeshes.length;
  18026. }
  18027. for (var index = 0; index < len; index++) {
  18028. var subMesh = subMeshes[index];
  18029. // Bounding test
  18030. if (len > 1 && !subMesh.canIntersects(ray))
  18031. continue;
  18032. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18033. if (currentIntersectInfo) {
  18034. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18035. intersectInfo = currentIntersectInfo;
  18036. intersectInfo.subMeshId = index;
  18037. if (fastCheck) {
  18038. break;
  18039. }
  18040. }
  18041. }
  18042. }
  18043. if (intersectInfo) {
  18044. // Get picked point
  18045. var world = this.getWorldMatrix();
  18046. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18047. var direction = ray.direction.clone();
  18048. direction = direction.scale(intersectInfo.distance);
  18049. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18050. var pickedPoint = worldOrigin.add(worldDirection);
  18051. // Return result
  18052. pickingInfo.hit = true;
  18053. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18054. pickingInfo.pickedPoint = pickedPoint;
  18055. pickingInfo.pickedMesh = this;
  18056. pickingInfo.bu = intersectInfo.bu || 0;
  18057. pickingInfo.bv = intersectInfo.bv || 0;
  18058. pickingInfo.faceId = intersectInfo.faceId;
  18059. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18060. return pickingInfo;
  18061. }
  18062. return pickingInfo;
  18063. };
  18064. /**
  18065. * Clones the mesh, used by the class Mesh.
  18066. * Just returns `null` for an AbstractMesh.
  18067. */
  18068. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18069. return null;
  18070. };
  18071. /**
  18072. * Disposes all the mesh submeshes.
  18073. * Returns the AbstractMesh.
  18074. */
  18075. AbstractMesh.prototype.releaseSubMeshes = function () {
  18076. if (this.subMeshes) {
  18077. while (this.subMeshes.length) {
  18078. this.subMeshes[0].dispose();
  18079. }
  18080. }
  18081. else {
  18082. this.subMeshes = new Array();
  18083. }
  18084. return this;
  18085. };
  18086. /**
  18087. * Disposes the AbstractMesh.
  18088. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18089. * Returns nothing.
  18090. */
  18091. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18092. var _this = this;
  18093. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18094. var index;
  18095. // Action manager
  18096. if (this.actionManager !== undefined && this.actionManager !== null) {
  18097. this.actionManager.dispose();
  18098. this.actionManager = null;
  18099. }
  18100. // Skeleton
  18101. this.skeleton = null;
  18102. // Physics
  18103. if (this.physicsImpostor) {
  18104. this.physicsImpostor.dispose();
  18105. }
  18106. // Intersections in progress
  18107. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18108. var other = this._intersectionsInProgress[index];
  18109. var pos = other._intersectionsInProgress.indexOf(this);
  18110. other._intersectionsInProgress.splice(pos, 1);
  18111. }
  18112. this._intersectionsInProgress = [];
  18113. // Lights
  18114. var lights = this.getScene().lights;
  18115. lights.forEach(function (light) {
  18116. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18117. if (meshIndex !== -1) {
  18118. light.includedOnlyMeshes.splice(meshIndex, 1);
  18119. }
  18120. meshIndex = light.excludedMeshes.indexOf(_this);
  18121. if (meshIndex !== -1) {
  18122. light.excludedMeshes.splice(meshIndex, 1);
  18123. }
  18124. // Shadow generators
  18125. var generator = light.getShadowGenerator();
  18126. if (generator) {
  18127. var shadowMap = generator.getShadowMap();
  18128. if (shadowMap && shadowMap.renderList) {
  18129. meshIndex = shadowMap.renderList.indexOf(_this);
  18130. if (meshIndex !== -1) {
  18131. shadowMap.renderList.splice(meshIndex, 1);
  18132. }
  18133. }
  18134. }
  18135. });
  18136. // Edges
  18137. if (this._edgesRenderer) {
  18138. this._edgesRenderer.dispose();
  18139. this._edgesRenderer = null;
  18140. }
  18141. // SubMeshes
  18142. if (this.getClassName() !== "InstancedMesh") {
  18143. this.releaseSubMeshes();
  18144. }
  18145. // Octree
  18146. var sceneOctree = this.getScene().selectionOctree;
  18147. if (sceneOctree !== undefined && sceneOctree !== null) {
  18148. var index = sceneOctree.dynamicContent.indexOf(this);
  18149. if (index !== -1) {
  18150. sceneOctree.dynamicContent.splice(index, 1);
  18151. }
  18152. }
  18153. // Query
  18154. var engine = this.getScene().getEngine();
  18155. if (this._occlusionQuery) {
  18156. this._isOcclusionQueryInProgress = false;
  18157. engine.deleteQuery(this._occlusionQuery);
  18158. this._occlusionQuery = null;
  18159. }
  18160. // Engine
  18161. engine.wipeCaches();
  18162. // Remove from scene
  18163. this.getScene().removeMesh(this);
  18164. if (disposeMaterialAndTextures) {
  18165. if (this.material) {
  18166. this.material.dispose(false, true);
  18167. }
  18168. }
  18169. if (!doNotRecurse) {
  18170. // Particles
  18171. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18172. if (this.getScene().particleSystems[index].emitter === this) {
  18173. this.getScene().particleSystems[index].dispose();
  18174. index--;
  18175. }
  18176. }
  18177. }
  18178. // facet data
  18179. if (this._facetDataEnabled) {
  18180. this.disableFacetData();
  18181. }
  18182. this.onAfterWorldMatrixUpdateObservable.clear();
  18183. this.onCollideObservable.clear();
  18184. this.onCollisionPositionChangeObservable.clear();
  18185. _super.prototype.dispose.call(this, doNotRecurse);
  18186. };
  18187. /**
  18188. * Adds the passed mesh as a child to the current mesh.
  18189. * Returns the AbstractMesh.
  18190. */
  18191. AbstractMesh.prototype.addChild = function (mesh) {
  18192. mesh.setParent(this);
  18193. return this;
  18194. };
  18195. /**
  18196. * Removes the passed mesh from the current mesh children list.
  18197. * Returns the AbstractMesh.
  18198. */
  18199. AbstractMesh.prototype.removeChild = function (mesh) {
  18200. mesh.setParent(null);
  18201. return this;
  18202. };
  18203. // Facet data
  18204. /**
  18205. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18206. * Returns the AbstractMesh.
  18207. */
  18208. AbstractMesh.prototype._initFacetData = function () {
  18209. if (!this._facetNormals) {
  18210. this._facetNormals = new Array();
  18211. }
  18212. if (!this._facetPositions) {
  18213. this._facetPositions = new Array();
  18214. }
  18215. if (!this._facetPartitioning) {
  18216. this._facetPartitioning = new Array();
  18217. }
  18218. this._facetNb = (this.getIndices().length / 3) | 0;
  18219. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18220. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18221. for (var f = 0; f < this._facetNb; f++) {
  18222. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18223. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18224. }
  18225. this._facetDataEnabled = true;
  18226. return this;
  18227. };
  18228. /**
  18229. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18230. * This method can be called within the render loop.
  18231. * 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.
  18232. * Returns the AbstractMesh.
  18233. */
  18234. AbstractMesh.prototype.updateFacetData = function () {
  18235. if (!this._facetDataEnabled) {
  18236. this._initFacetData();
  18237. }
  18238. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18239. var indices = this.getIndices();
  18240. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18241. var bInfo = this.getBoundingInfo();
  18242. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18243. // init arrays, matrix and sort function on first call
  18244. this._facetDepthSortEnabled = true;
  18245. if (indices instanceof Uint16Array) {
  18246. this._depthSortedIndices = new Uint16Array(indices);
  18247. }
  18248. else if (indices instanceof Uint32Array) {
  18249. this._depthSortedIndices = new Uint32Array(indices);
  18250. }
  18251. else {
  18252. var needs32bits = false;
  18253. for (var i = 0; i < indices.length; i++) {
  18254. if (indices[i] > 65535) {
  18255. needs32bits = true;
  18256. break;
  18257. }
  18258. }
  18259. if (needs32bits) {
  18260. this._depthSortedIndices = new Uint32Array(indices);
  18261. }
  18262. else {
  18263. this._depthSortedIndices = new Uint16Array(indices);
  18264. }
  18265. }
  18266. this._facetDepthSortFunction = function (f1, f2) {
  18267. return (f2.sqDistance - f1.sqDistance);
  18268. };
  18269. if (!this._facetDepthSortFrom) {
  18270. var camera = this.getScene().activeCamera;
  18271. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18272. }
  18273. this._depthSortedFacets = [];
  18274. for (var f = 0; f < this._facetNb; f++) {
  18275. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18276. this._depthSortedFacets.push(depthSortedFacet);
  18277. }
  18278. this._invertedMatrix = BABYLON.Matrix.Identity();
  18279. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18280. }
  18281. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18282. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18283. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18284. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18285. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18286. this._subDiv.max = this._partitioningSubdivisions;
  18287. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18288. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18289. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18290. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18291. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18292. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18293. // set the parameters for ComputeNormals()
  18294. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18295. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18296. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18297. this._facetParameters.bInfo = bInfo;
  18298. this._facetParameters.bbSize = this._bbSize;
  18299. this._facetParameters.subDiv = this._subDiv;
  18300. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18301. this._facetParameters.depthSort = this._facetDepthSort;
  18302. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18303. this.computeWorldMatrix(true);
  18304. this._worldMatrix.invertToRef(this._invertedMatrix);
  18305. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18306. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18307. }
  18308. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18309. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18310. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18311. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18312. var l = (this._depthSortedIndices.length / 3) | 0;
  18313. for (var f = 0; f < l; f++) {
  18314. var sind = this._depthSortedFacets[f].ind;
  18315. this._depthSortedIndices[f * 3] = indices[sind];
  18316. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18317. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18318. }
  18319. this.updateIndices(this._depthSortedIndices);
  18320. }
  18321. return this;
  18322. };
  18323. /**
  18324. * Returns the facetLocalNormals array.
  18325. * The normals are expressed in the mesh local space.
  18326. */
  18327. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18328. if (!this._facetNormals) {
  18329. this.updateFacetData();
  18330. }
  18331. return this._facetNormals;
  18332. };
  18333. /**
  18334. * Returns the facetLocalPositions array.
  18335. * The facet positions are expressed in the mesh local space.
  18336. */
  18337. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18338. if (!this._facetPositions) {
  18339. this.updateFacetData();
  18340. }
  18341. return this._facetPositions;
  18342. };
  18343. /**
  18344. * Returns the facetLocalPartioning array.
  18345. */
  18346. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18347. if (!this._facetPartitioning) {
  18348. this.updateFacetData();
  18349. }
  18350. return this._facetPartitioning;
  18351. };
  18352. /**
  18353. * Returns the i-th facet position in the world system.
  18354. * This method allocates a new Vector3 per call.
  18355. */
  18356. AbstractMesh.prototype.getFacetPosition = function (i) {
  18357. var pos = BABYLON.Vector3.Zero();
  18358. this.getFacetPositionToRef(i, pos);
  18359. return pos;
  18360. };
  18361. /**
  18362. * Sets the reference Vector3 with the i-th facet position in the world system.
  18363. * Returns the AbstractMesh.
  18364. */
  18365. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18366. var localPos = (this.getFacetLocalPositions())[i];
  18367. var world = this.getWorldMatrix();
  18368. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18369. return this;
  18370. };
  18371. /**
  18372. * Returns the i-th facet normal in the world system.
  18373. * This method allocates a new Vector3 per call.
  18374. */
  18375. AbstractMesh.prototype.getFacetNormal = function (i) {
  18376. var norm = BABYLON.Vector3.Zero();
  18377. this.getFacetNormalToRef(i, norm);
  18378. return norm;
  18379. };
  18380. /**
  18381. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18382. * Returns the AbstractMesh.
  18383. */
  18384. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18385. var localNorm = (this.getFacetLocalNormals())[i];
  18386. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18387. return this;
  18388. };
  18389. /**
  18390. * 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).
  18391. */
  18392. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18393. var bInfo = this.getBoundingInfo();
  18394. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18395. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18396. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18397. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18398. return null;
  18399. }
  18400. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18401. };
  18402. /**
  18403. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18404. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18405. * 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.
  18406. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18407. * 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.
  18408. */
  18409. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18410. if (checkFace === void 0) { checkFace = false; }
  18411. if (facing === void 0) { facing = true; }
  18412. var world = this.getWorldMatrix();
  18413. var invMat = BABYLON.Tmp.Matrix[5];
  18414. world.invertToRef(invMat);
  18415. var invVect = BABYLON.Tmp.Vector3[8];
  18416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18417. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18418. if (projected) {
  18419. // tranform the local computed projected vector to world coordinates
  18420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18421. }
  18422. return closest;
  18423. };
  18424. /**
  18425. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18426. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18427. * 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.
  18428. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18429. * 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.
  18430. */
  18431. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18432. if (checkFace === void 0) { checkFace = false; }
  18433. if (facing === void 0) { facing = true; }
  18434. var closest = null;
  18435. var tmpx = 0.0;
  18436. var tmpy = 0.0;
  18437. var tmpz = 0.0;
  18438. var d = 0.0; // tmp dot facet normal * facet position
  18439. var t0 = 0.0;
  18440. var projx = 0.0;
  18441. var projy = 0.0;
  18442. var projz = 0.0;
  18443. // Get all the facets in the same partitioning block than (x, y, z)
  18444. var facetPositions = this.getFacetLocalPositions();
  18445. var facetNormals = this.getFacetLocalNormals();
  18446. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18447. if (!facetsInBlock) {
  18448. return null;
  18449. }
  18450. // Get the closest facet to (x, y, z)
  18451. var shortest = Number.MAX_VALUE; // init distance vars
  18452. var tmpDistance = shortest;
  18453. var fib; // current facet in the block
  18454. var norm; // current facet normal
  18455. var p0; // current facet barycenter position
  18456. // loop on all the facets in the current partitioning block
  18457. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18458. fib = facetsInBlock[idx];
  18459. norm = facetNormals[fib];
  18460. p0 = facetPositions[fib];
  18461. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18462. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18463. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18464. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18465. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18466. projx = x + norm.x * t0;
  18467. projy = y + norm.y * t0;
  18468. projz = z + norm.z * t0;
  18469. tmpx = projx - x;
  18470. tmpy = projy - y;
  18471. tmpz = projz - z;
  18472. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18473. if (tmpDistance < shortest) {
  18474. shortest = tmpDistance;
  18475. closest = fib;
  18476. if (projected) {
  18477. projected.x = projx;
  18478. projected.y = projy;
  18479. projected.z = projz;
  18480. }
  18481. }
  18482. }
  18483. }
  18484. return closest;
  18485. };
  18486. /**
  18487. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18488. */
  18489. AbstractMesh.prototype.getFacetDataParameters = function () {
  18490. return this._facetParameters;
  18491. };
  18492. /**
  18493. * Disables the feature FacetData and frees the related memory.
  18494. * Returns the AbstractMesh.
  18495. */
  18496. AbstractMesh.prototype.disableFacetData = function () {
  18497. if (this._facetDataEnabled) {
  18498. this._facetDataEnabled = false;
  18499. this._facetPositions = new Array();
  18500. this._facetNormals = new Array();
  18501. this._facetPartitioning = new Array();
  18502. this._facetParameters = null;
  18503. this._depthSortedIndices = new Uint32Array(0);
  18504. }
  18505. return this;
  18506. };
  18507. /**
  18508. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18509. * Returns the mesh.
  18510. */
  18511. AbstractMesh.prototype.updateIndices = function (indices) {
  18512. return this;
  18513. };
  18514. /**
  18515. * The mesh Geometry. Actually used by the Mesh object.
  18516. * Returns a blank geometry object.
  18517. */
  18518. /**
  18519. * Creates new normals data for the mesh.
  18520. * @param updatable.
  18521. */
  18522. AbstractMesh.prototype.createNormals = function (updatable) {
  18523. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18524. var indices = this.getIndices();
  18525. var normals;
  18526. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18527. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18528. }
  18529. else {
  18530. normals = [];
  18531. }
  18532. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18533. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18534. };
  18535. /**
  18536. * Align the mesh with a normal.
  18537. * Returns the mesh.
  18538. */
  18539. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18540. if (!upDirection) {
  18541. upDirection = BABYLON.Axis.Y;
  18542. }
  18543. var axisX = BABYLON.Tmp.Vector3[0];
  18544. var axisZ = BABYLON.Tmp.Vector3[1];
  18545. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18546. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18547. if (this.rotationQuaternion) {
  18548. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18549. }
  18550. else {
  18551. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18552. }
  18553. return this;
  18554. };
  18555. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18556. var engine = this.getEngine();
  18557. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18558. this._isOccluded = false;
  18559. return;
  18560. }
  18561. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18562. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18563. if (isOcclusionQueryAvailable) {
  18564. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18565. this._isOcclusionQueryInProgress = false;
  18566. this._occlusionInternalRetryCounter = 0;
  18567. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18568. }
  18569. else {
  18570. this._occlusionInternalRetryCounter++;
  18571. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18572. this._isOcclusionQueryInProgress = false;
  18573. this._occlusionInternalRetryCounter = 0;
  18574. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18575. // if strict continue the last state of the object.
  18576. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18577. }
  18578. else {
  18579. return;
  18580. }
  18581. }
  18582. }
  18583. var scene = this.getScene();
  18584. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18585. if (!this._occlusionQuery) {
  18586. this._occlusionQuery = engine.createQuery();
  18587. }
  18588. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18589. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18590. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18591. this._isOcclusionQueryInProgress = true;
  18592. };
  18593. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18594. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18595. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18596. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18597. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18598. return AbstractMesh;
  18599. }(BABYLON.TransformNode));
  18600. BABYLON.AbstractMesh = AbstractMesh;
  18601. })(BABYLON || (BABYLON = {}));
  18602. //# sourceMappingURL=babylon.abstractMesh.js.map
  18603. var BABYLON;
  18604. (function (BABYLON) {
  18605. /**
  18606. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18607. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18608. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  18609. */
  18610. var Light = /** @class */ (function (_super) {
  18611. __extends(Light, _super);
  18612. /**
  18613. * Creates a Light object in the scene.
  18614. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18615. * @param name The firendly name of the light
  18616. * @param scene The scene the light belongs too
  18617. */
  18618. function Light(name, scene) {
  18619. var _this = _super.call(this, name, scene) || this;
  18620. /**
  18621. * Diffuse gives the basic color to an object.
  18622. */
  18623. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18624. /**
  18625. * Specular produces a highlight color on an object.
  18626. * Note: This is note affecting PBR materials.
  18627. */
  18628. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18629. /**
  18630. * Strength of the light.
  18631. * Note: By default it is define in the framework own unit.
  18632. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18633. */
  18634. _this.intensity = 1.0;
  18635. /**
  18636. * Defines how far from the source the light is impacting in scene units.
  18637. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18638. */
  18639. _this.range = Number.MAX_VALUE;
  18640. /**
  18641. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18642. * of light.
  18643. */
  18644. _this._photometricScale = 1.0;
  18645. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18646. _this._radius = 0.00001;
  18647. /**
  18648. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18649. * exceeding the number allowed of the materials.
  18650. */
  18651. _this.renderPriority = 0;
  18652. /**
  18653. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18654. * the current shadow generator.
  18655. */
  18656. _this.shadowEnabled = true;
  18657. _this._excludeWithLayerMask = 0;
  18658. _this._includeOnlyWithLayerMask = 0;
  18659. _this._lightmapMode = 0;
  18660. /**
  18661. * @ignore Internal use only.
  18662. */
  18663. _this._excludedMeshesIds = new Array();
  18664. /**
  18665. * @ignore Internal use only.
  18666. */
  18667. _this._includedOnlyMeshesIds = new Array();
  18668. _this.getScene().addLight(_this);
  18669. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18670. _this._buildUniformLayout();
  18671. _this.includedOnlyMeshes = new Array();
  18672. _this.excludedMeshes = new Array();
  18673. _this._resyncMeshes();
  18674. return _this;
  18675. }
  18676. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18677. /**
  18678. * If every light affecting the material is in this lightmapMode,
  18679. * material.lightmapTexture adds or multiplies
  18680. * (depends on material.useLightmapAsShadowmap)
  18681. * after every other light calculations.
  18682. */
  18683. get: function () {
  18684. return Light._LIGHTMAP_DEFAULT;
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18690. /**
  18691. * material.lightmapTexture as only diffuse lighting from this light
  18692. * adds only specular lighting from this light
  18693. * adds dynamic shadows
  18694. */
  18695. get: function () {
  18696. return Light._LIGHTMAP_SPECULAR;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18702. /**
  18703. * material.lightmapTexture as only lighting
  18704. * no light calculation from this light
  18705. * only adds dynamic shadows from this light
  18706. */
  18707. get: function () {
  18708. return Light._LIGHTMAP_SHADOWSONLY;
  18709. },
  18710. enumerable: true,
  18711. configurable: true
  18712. });
  18713. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18714. /**
  18715. * Each light type uses the default quantity according to its type:
  18716. * point/spot lights use luminous intensity
  18717. * directional lights use illuminance
  18718. */
  18719. get: function () {
  18720. return Light._INTENSITYMODE_AUTOMATIC;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18726. /**
  18727. * lumen (lm)
  18728. */
  18729. get: function () {
  18730. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18736. /**
  18737. * candela (lm/sr)
  18738. */
  18739. get: function () {
  18740. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18746. /**
  18747. * lux (lm/m^2)
  18748. */
  18749. get: function () {
  18750. return Light._INTENSITYMODE_ILLUMINANCE;
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18756. /**
  18757. * nit (cd/m^2)
  18758. */
  18759. get: function () {
  18760. return Light._INTENSITYMODE_LUMINANCE;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18766. /**
  18767. * Light type const id of the point light.
  18768. */
  18769. get: function () {
  18770. return Light._LIGHTTYPEID_POINTLIGHT;
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18776. /**
  18777. * Light type const id of the directional light.
  18778. */
  18779. get: function () {
  18780. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18781. },
  18782. enumerable: true,
  18783. configurable: true
  18784. });
  18785. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18786. /**
  18787. * Light type const id of the spot light.
  18788. */
  18789. get: function () {
  18790. return Light._LIGHTTYPEID_SPOTLIGHT;
  18791. },
  18792. enumerable: true,
  18793. configurable: true
  18794. });
  18795. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18796. /**
  18797. * Light type const id of the hemispheric light.
  18798. */
  18799. get: function () {
  18800. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18801. },
  18802. enumerable: true,
  18803. configurable: true
  18804. });
  18805. Object.defineProperty(Light.prototype, "intensityMode", {
  18806. /**
  18807. * Gets the photometric scale used to interpret the intensity.
  18808. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18809. */
  18810. get: function () {
  18811. return this._intensityMode;
  18812. },
  18813. /**
  18814. * Sets the photometric scale used to interpret the intensity.
  18815. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18816. */
  18817. set: function (value) {
  18818. this._intensityMode = value;
  18819. this._computePhotometricScale();
  18820. },
  18821. enumerable: true,
  18822. configurable: true
  18823. });
  18824. ;
  18825. ;
  18826. Object.defineProperty(Light.prototype, "radius", {
  18827. /**
  18828. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18829. */
  18830. get: function () {
  18831. return this._radius;
  18832. },
  18833. /**
  18834. * sets the light radius used by PBR Materials to simulate soft area lights.
  18835. */
  18836. set: function (value) {
  18837. this._radius = value;
  18838. this._computePhotometricScale();
  18839. },
  18840. enumerable: true,
  18841. configurable: true
  18842. });
  18843. ;
  18844. ;
  18845. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18846. /**
  18847. * Gets the only meshes impacted by this light.
  18848. */
  18849. get: function () {
  18850. return this._includedOnlyMeshes;
  18851. },
  18852. /**
  18853. * Sets the only meshes impacted by this light.
  18854. */
  18855. set: function (value) {
  18856. this._includedOnlyMeshes = value;
  18857. this._hookArrayForIncludedOnly(value);
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18863. /**
  18864. * Gets the meshes not impacted by this light.
  18865. */
  18866. get: function () {
  18867. return this._excludedMeshes;
  18868. },
  18869. /**
  18870. * Sets the meshes not impacted by this light.
  18871. */
  18872. set: function (value) {
  18873. this._excludedMeshes = value;
  18874. this._hookArrayForExcluded(value);
  18875. },
  18876. enumerable: true,
  18877. configurable: true
  18878. });
  18879. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18880. /**
  18881. * Gets the layer id use to find what meshes are not impacted by the light.
  18882. * Inactive if 0
  18883. */
  18884. get: function () {
  18885. return this._excludeWithLayerMask;
  18886. },
  18887. /**
  18888. * Sets the layer id use to find what meshes are not impacted by the light.
  18889. * Inactive if 0
  18890. */
  18891. set: function (value) {
  18892. this._excludeWithLayerMask = value;
  18893. this._resyncMeshes();
  18894. },
  18895. enumerable: true,
  18896. configurable: true
  18897. });
  18898. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18899. /**
  18900. * Gets the layer id use to find what meshes are impacted by the light.
  18901. * Inactive if 0
  18902. */
  18903. get: function () {
  18904. return this._includeOnlyWithLayerMask;
  18905. },
  18906. /**
  18907. * Sets the layer id use to find what meshes are impacted by the light.
  18908. * Inactive if 0
  18909. */
  18910. set: function (value) {
  18911. this._includeOnlyWithLayerMask = value;
  18912. this._resyncMeshes();
  18913. },
  18914. enumerable: true,
  18915. configurable: true
  18916. });
  18917. Object.defineProperty(Light.prototype, "lightmapMode", {
  18918. /**
  18919. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18920. */
  18921. get: function () {
  18922. return this._lightmapMode;
  18923. },
  18924. /**
  18925. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18926. */
  18927. set: function (value) {
  18928. if (this._lightmapMode === value) {
  18929. return;
  18930. }
  18931. this._lightmapMode = value;
  18932. this._markMeshesAsLightDirty();
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. /**
  18938. * Returns the string "Light".
  18939. * @returns the class name
  18940. */
  18941. Light.prototype.getClassName = function () {
  18942. return "Light";
  18943. };
  18944. /**
  18945. * Converts the light information to a readable string for debug purpose.
  18946. * @param fullDetails Supports for multiple levels of logging within scene loading
  18947. * @returns the human readable light info
  18948. */
  18949. Light.prototype.toString = function (fullDetails) {
  18950. var ret = "Name: " + this.name;
  18951. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18952. if (this.animations) {
  18953. for (var i = 0; i < this.animations.length; i++) {
  18954. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18955. }
  18956. }
  18957. if (fullDetails) {
  18958. }
  18959. return ret;
  18960. };
  18961. /**
  18962. * Set the enabled state of this node.
  18963. * @param value - the new enabled state
  18964. * @see isEnabled
  18965. */
  18966. Light.prototype.setEnabled = function (value) {
  18967. _super.prototype.setEnabled.call(this, value);
  18968. this._resyncMeshes();
  18969. };
  18970. /**
  18971. * Returns the Light associated shadow generator if any.
  18972. * @return the associated shadow generator.
  18973. */
  18974. Light.prototype.getShadowGenerator = function () {
  18975. return this._shadowGenerator;
  18976. };
  18977. /**
  18978. * Returns a Vector3, the absolute light position in the World.
  18979. * @returns the world space position of the light
  18980. */
  18981. Light.prototype.getAbsolutePosition = function () {
  18982. return BABYLON.Vector3.Zero();
  18983. };
  18984. /**
  18985. * Specifies if the light will affect the passed mesh.
  18986. * @param mesh The mesh to test against the light
  18987. * @return true the mesh is affected otherwise, false.
  18988. */
  18989. Light.prototype.canAffectMesh = function (mesh) {
  18990. if (!mesh) {
  18991. return true;
  18992. }
  18993. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18994. return false;
  18995. }
  18996. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18997. return false;
  18998. }
  18999. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19000. return false;
  19001. }
  19002. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19003. return false;
  19004. }
  19005. return true;
  19006. };
  19007. /**
  19008. * Computes and Returns the light World matrix.
  19009. * @returns the world matrix
  19010. */
  19011. Light.prototype.getWorldMatrix = function () {
  19012. this._currentRenderId = this.getScene().getRenderId();
  19013. var worldMatrix = this._getWorldMatrix();
  19014. if (this.parent && this.parent.getWorldMatrix) {
  19015. if (!this._parentedWorldMatrix) {
  19016. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19017. }
  19018. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19019. this._markSyncedWithParent();
  19020. return this._parentedWorldMatrix;
  19021. }
  19022. return worldMatrix;
  19023. };
  19024. /**
  19025. * Sort function to order lights for rendering.
  19026. * @param a First Light object to compare to second.
  19027. * @param b Second Light object to compare first.
  19028. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19029. */
  19030. Light.CompareLightsPriority = function (a, b) {
  19031. //shadow-casting lights have priority over non-shadow-casting lights
  19032. //the renderPrioirty is a secondary sort criterion
  19033. if (a.shadowEnabled !== b.shadowEnabled) {
  19034. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19035. }
  19036. return b.renderPriority - a.renderPriority;
  19037. };
  19038. /**
  19039. * Disposes the light.
  19040. */
  19041. Light.prototype.dispose = function () {
  19042. if (this._shadowGenerator) {
  19043. this._shadowGenerator.dispose();
  19044. this._shadowGenerator = null;
  19045. }
  19046. // Animations
  19047. this.getScene().stopAnimation(this);
  19048. // Remove from meshes
  19049. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19050. var mesh = _a[_i];
  19051. mesh._removeLightSource(this);
  19052. }
  19053. this._uniformBuffer.dispose();
  19054. // Remove from scene
  19055. this.getScene().removeLight(this);
  19056. _super.prototype.dispose.call(this);
  19057. };
  19058. /**
  19059. * Returns the light type ID (integer).
  19060. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19061. */
  19062. Light.prototype.getTypeID = function () {
  19063. return 0;
  19064. };
  19065. /**
  19066. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19067. * @returns the scaled intensity in intensity mode unit
  19068. */
  19069. Light.prototype.getScaledIntensity = function () {
  19070. return this._photometricScale * this.intensity;
  19071. };
  19072. /**
  19073. * Returns a new Light object, named "name", from the current one.
  19074. * @param name The name of the cloned light
  19075. * @returns the new created light
  19076. */
  19077. Light.prototype.clone = function (name) {
  19078. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19079. if (!constructor) {
  19080. return null;
  19081. }
  19082. return BABYLON.SerializationHelper.Clone(constructor, this);
  19083. };
  19084. /**
  19085. * Serializes the current light into a Serialization object.
  19086. * @returns the serialized object.
  19087. */
  19088. Light.prototype.serialize = function () {
  19089. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19090. // Type
  19091. serializationObject.type = this.getTypeID();
  19092. // Parent
  19093. if (this.parent) {
  19094. serializationObject.parentId = this.parent.id;
  19095. }
  19096. // Inclusion / exclusions
  19097. if (this.excludedMeshes.length > 0) {
  19098. serializationObject.excludedMeshesIds = [];
  19099. this.excludedMeshes.forEach(function (mesh) {
  19100. serializationObject.excludedMeshesIds.push(mesh.id);
  19101. });
  19102. }
  19103. if (this.includedOnlyMeshes.length > 0) {
  19104. serializationObject.includedOnlyMeshesIds = [];
  19105. this.includedOnlyMeshes.forEach(function (mesh) {
  19106. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19107. });
  19108. }
  19109. // Animations
  19110. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19111. serializationObject.ranges = this.serializeAnimationRanges();
  19112. return serializationObject;
  19113. };
  19114. /**
  19115. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19116. * This new light is named "name" and added to the passed scene.
  19117. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19118. * @param name The friendly name of the light
  19119. * @param scene The scene the new light will belong to
  19120. * @returns the constructor function
  19121. */
  19122. Light.GetConstructorFromName = function (type, name, scene) {
  19123. switch (type) {
  19124. case 0:
  19125. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19126. case 1:
  19127. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19128. case 2:
  19129. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19130. case 3:
  19131. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19132. }
  19133. return null;
  19134. };
  19135. /**
  19136. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19137. * @param parsedLight The JSON representation of the light
  19138. * @param scene The scene to create the parsed light in
  19139. * @returns the created light after parsing
  19140. */
  19141. Light.Parse = function (parsedLight, scene) {
  19142. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19143. if (!constructor) {
  19144. return null;
  19145. }
  19146. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19147. // Inclusion / exclusions
  19148. if (parsedLight.excludedMeshesIds) {
  19149. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19150. }
  19151. if (parsedLight.includedOnlyMeshesIds) {
  19152. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19153. }
  19154. // Parent
  19155. if (parsedLight.parentId) {
  19156. light._waitingParentId = parsedLight.parentId;
  19157. }
  19158. // Animations
  19159. if (parsedLight.animations) {
  19160. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19161. var parsedAnimation = parsedLight.animations[animationIndex];
  19162. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19163. }
  19164. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19165. }
  19166. if (parsedLight.autoAnimate) {
  19167. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19168. }
  19169. return light;
  19170. };
  19171. Light.prototype._hookArrayForExcluded = function (array) {
  19172. var _this = this;
  19173. var oldPush = array.push;
  19174. array.push = function () {
  19175. var items = [];
  19176. for (var _i = 0; _i < arguments.length; _i++) {
  19177. items[_i] = arguments[_i];
  19178. }
  19179. var result = oldPush.apply(array, items);
  19180. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19181. var item = items_1[_a];
  19182. item._resyncLighSource(_this);
  19183. }
  19184. return result;
  19185. };
  19186. var oldSplice = array.splice;
  19187. array.splice = function (index, deleteCount) {
  19188. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19189. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19190. var item = deleted_1[_i];
  19191. item._resyncLighSource(_this);
  19192. }
  19193. return deleted;
  19194. };
  19195. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19196. var item = array_1[_i];
  19197. item._resyncLighSource(this);
  19198. }
  19199. };
  19200. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19201. var _this = this;
  19202. var oldPush = array.push;
  19203. array.push = function () {
  19204. var items = [];
  19205. for (var _i = 0; _i < arguments.length; _i++) {
  19206. items[_i] = arguments[_i];
  19207. }
  19208. var result = oldPush.apply(array, items);
  19209. _this._resyncMeshes();
  19210. return result;
  19211. };
  19212. var oldSplice = array.splice;
  19213. array.splice = function (index, deleteCount) {
  19214. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19215. _this._resyncMeshes();
  19216. return deleted;
  19217. };
  19218. this._resyncMeshes();
  19219. };
  19220. Light.prototype._resyncMeshes = function () {
  19221. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19222. var mesh = _a[_i];
  19223. mesh._resyncLighSource(this);
  19224. }
  19225. };
  19226. /**
  19227. * Forces the meshes to update their light related information in their rendering used effects
  19228. * @ignore Internal Use Only
  19229. */
  19230. Light.prototype._markMeshesAsLightDirty = function () {
  19231. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19232. var mesh = _a[_i];
  19233. if (mesh._lightSources.indexOf(this) !== -1) {
  19234. mesh._markSubMeshesAsLightDirty();
  19235. }
  19236. }
  19237. };
  19238. /**
  19239. * Recomputes the cached photometric scale if needed.
  19240. */
  19241. Light.prototype._computePhotometricScale = function () {
  19242. this._photometricScale = this._getPhotometricScale();
  19243. this.getScene().resetCachedMaterial();
  19244. };
  19245. /**
  19246. * Returns the Photometric Scale according to the light type and intensity mode.
  19247. */
  19248. Light.prototype._getPhotometricScale = function () {
  19249. var photometricScale = 0.0;
  19250. var lightTypeID = this.getTypeID();
  19251. //get photometric mode
  19252. var photometricMode = this.intensityMode;
  19253. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19254. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19255. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19256. }
  19257. else {
  19258. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19259. }
  19260. }
  19261. //compute photometric scale
  19262. switch (lightTypeID) {
  19263. case Light.LIGHTTYPEID_POINTLIGHT:
  19264. case Light.LIGHTTYPEID_SPOTLIGHT:
  19265. switch (photometricMode) {
  19266. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19267. photometricScale = 1.0 / (4.0 * Math.PI);
  19268. break;
  19269. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19270. photometricScale = 1.0;
  19271. break;
  19272. case Light.INTENSITYMODE_LUMINANCE:
  19273. photometricScale = this.radius * this.radius;
  19274. break;
  19275. }
  19276. break;
  19277. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19278. switch (photometricMode) {
  19279. case Light.INTENSITYMODE_ILLUMINANCE:
  19280. photometricScale = 1.0;
  19281. break;
  19282. case Light.INTENSITYMODE_LUMINANCE:
  19283. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19284. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19285. var apexAngleRadians = this.radius;
  19286. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19287. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19288. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19289. photometricScale = solidAngle;
  19290. break;
  19291. }
  19292. break;
  19293. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19294. // No fall off in hemisperic light.
  19295. photometricScale = 1.0;
  19296. break;
  19297. }
  19298. return photometricScale;
  19299. };
  19300. /**
  19301. * Reorder the light in the scene according to their defined priority.
  19302. * @ignore Internal Use Only
  19303. */
  19304. Light.prototype._reorderLightsInScene = function () {
  19305. var scene = this.getScene();
  19306. if (this._renderPriority != 0) {
  19307. scene.requireLightSorting = true;
  19308. }
  19309. this.getScene().sortLightsByPriority();
  19310. };
  19311. //lightmapMode Consts
  19312. Light._LIGHTMAP_DEFAULT = 0;
  19313. Light._LIGHTMAP_SPECULAR = 1;
  19314. Light._LIGHTMAP_SHADOWSONLY = 2;
  19315. // Intensity Mode Consts
  19316. Light._INTENSITYMODE_AUTOMATIC = 0;
  19317. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19318. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19319. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19320. Light._INTENSITYMODE_LUMINANCE = 4;
  19321. // Light types ids const.
  19322. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19323. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19324. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19325. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19326. __decorate([
  19327. BABYLON.serializeAsColor3()
  19328. ], Light.prototype, "diffuse", void 0);
  19329. __decorate([
  19330. BABYLON.serializeAsColor3()
  19331. ], Light.prototype, "specular", void 0);
  19332. __decorate([
  19333. BABYLON.serialize()
  19334. ], Light.prototype, "intensity", void 0);
  19335. __decorate([
  19336. BABYLON.serialize()
  19337. ], Light.prototype, "range", void 0);
  19338. __decorate([
  19339. BABYLON.serialize()
  19340. ], Light.prototype, "intensityMode", null);
  19341. __decorate([
  19342. BABYLON.serialize()
  19343. ], Light.prototype, "radius", null);
  19344. __decorate([
  19345. BABYLON.serialize()
  19346. ], Light.prototype, "_renderPriority", void 0);
  19347. __decorate([
  19348. BABYLON.expandToProperty("_reorderLightsInScene")
  19349. ], Light.prototype, "renderPriority", void 0);
  19350. __decorate([
  19351. BABYLON.serialize()
  19352. ], Light.prototype, "shadowEnabled", void 0);
  19353. __decorate([
  19354. BABYLON.serialize("excludeWithLayerMask")
  19355. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19356. __decorate([
  19357. BABYLON.serialize("includeOnlyWithLayerMask")
  19358. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19359. __decorate([
  19360. BABYLON.serialize("lightmapMode")
  19361. ], Light.prototype, "_lightmapMode", void 0);
  19362. return Light;
  19363. }(BABYLON.Node));
  19364. BABYLON.Light = Light;
  19365. })(BABYLON || (BABYLON = {}));
  19366. //# sourceMappingURL=babylon.light.js.map
  19367. var BABYLON;
  19368. (function (BABYLON) {
  19369. var Camera = /** @class */ (function (_super) {
  19370. __extends(Camera, _super);
  19371. function Camera(name, position, scene) {
  19372. var _this = _super.call(this, name, scene) || this;
  19373. /**
  19374. * The vector the camera should consider as up.
  19375. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19376. */
  19377. _this.upVector = BABYLON.Vector3.Up();
  19378. _this.orthoLeft = null;
  19379. _this.orthoRight = null;
  19380. _this.orthoBottom = null;
  19381. _this.orthoTop = null;
  19382. /**
  19383. * FOV is set in Radians. (default is 0.8)
  19384. */
  19385. _this.fov = 0.8;
  19386. _this.minZ = 1;
  19387. _this.maxZ = 10000.0;
  19388. _this.inertia = 0.9;
  19389. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19390. _this.isIntermediate = false;
  19391. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19392. /**
  19393. * Restricts the camera to viewing objects with the same layerMask.
  19394. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19395. */
  19396. _this.layerMask = 0x0FFFFFFF;
  19397. /**
  19398. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19399. */
  19400. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19401. // Camera rig members
  19402. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19403. _this._rigCameras = new Array();
  19404. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19405. _this._skipRendering = false;
  19406. _this.customRenderTargets = new Array();
  19407. // Observables
  19408. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19409. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19410. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19411. _this.onRestoreStateObservable = new BABYLON.Observable();
  19412. // Cache
  19413. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19414. _this._projectionMatrix = new BABYLON.Matrix();
  19415. _this._doNotComputeProjectionMatrix = false;
  19416. _this._postProcesses = new Array();
  19417. _this._transformMatrix = BABYLON.Matrix.Zero();
  19418. _this._activeMeshes = new BABYLON.SmartArray(256);
  19419. _this._globalPosition = BABYLON.Vector3.Zero();
  19420. _this._refreshFrustumPlanes = true;
  19421. _this.getScene().addCamera(_this);
  19422. if (!_this.getScene().activeCamera) {
  19423. _this.getScene().activeCamera = _this;
  19424. }
  19425. _this.position = position;
  19426. return _this;
  19427. }
  19428. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19429. get: function () {
  19430. return Camera._PERSPECTIVE_CAMERA;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19436. get: function () {
  19437. return Camera._ORTHOGRAPHIC_CAMERA;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19443. /**
  19444. * This is the default FOV mode for perspective cameras.
  19445. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19446. *
  19447. */
  19448. get: function () {
  19449. return Camera._FOVMODE_VERTICAL_FIXED;
  19450. },
  19451. enumerable: true,
  19452. configurable: true
  19453. });
  19454. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19455. /**
  19456. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19457. *
  19458. */
  19459. get: function () {
  19460. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19466. get: function () {
  19467. return Camera._RIG_MODE_NONE;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19473. get: function () {
  19474. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19480. get: function () {
  19481. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19487. get: function () {
  19488. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19494. get: function () {
  19495. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19501. get: function () {
  19502. return Camera._RIG_MODE_VR;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19508. get: function () {
  19509. return Camera._RIG_MODE_WEBVR;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. /**
  19515. * Store current camera state (fov, position, etc..)
  19516. */
  19517. Camera.prototype.storeState = function () {
  19518. this._stateStored = true;
  19519. this._storedFov = this.fov;
  19520. return this;
  19521. };
  19522. /**
  19523. * Restores the camera state values if it has been stored. You must call storeState() first
  19524. */
  19525. Camera.prototype._restoreStateValues = function () {
  19526. if (!this._stateStored) {
  19527. return false;
  19528. }
  19529. this.fov = this._storedFov;
  19530. return true;
  19531. };
  19532. /**
  19533. * Restored camera state. You must call storeState() first
  19534. */
  19535. Camera.prototype.restoreState = function () {
  19536. if (this._restoreStateValues()) {
  19537. this.onRestoreStateObservable.notifyObservers(this);
  19538. return true;
  19539. }
  19540. return false;
  19541. };
  19542. Camera.prototype.getClassName = function () {
  19543. return "Camera";
  19544. };
  19545. /**
  19546. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19547. */
  19548. Camera.prototype.toString = function (fullDetails) {
  19549. var ret = "Name: " + this.name;
  19550. ret += ", type: " + this.getClassName();
  19551. if (this.animations) {
  19552. for (var i = 0; i < this.animations.length; i++) {
  19553. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19554. }
  19555. }
  19556. if (fullDetails) {
  19557. }
  19558. return ret;
  19559. };
  19560. Object.defineProperty(Camera.prototype, "globalPosition", {
  19561. get: function () {
  19562. return this._globalPosition;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Camera.prototype.getActiveMeshes = function () {
  19568. return this._activeMeshes;
  19569. };
  19570. Camera.prototype.isActiveMesh = function (mesh) {
  19571. return (this._activeMeshes.indexOf(mesh) !== -1);
  19572. };
  19573. //Cache
  19574. Camera.prototype._initCache = function () {
  19575. _super.prototype._initCache.call(this);
  19576. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19577. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19578. this._cache.mode = undefined;
  19579. this._cache.minZ = undefined;
  19580. this._cache.maxZ = undefined;
  19581. this._cache.fov = undefined;
  19582. this._cache.fovMode = undefined;
  19583. this._cache.aspectRatio = undefined;
  19584. this._cache.orthoLeft = undefined;
  19585. this._cache.orthoRight = undefined;
  19586. this._cache.orthoBottom = undefined;
  19587. this._cache.orthoTop = undefined;
  19588. this._cache.renderWidth = undefined;
  19589. this._cache.renderHeight = undefined;
  19590. };
  19591. Camera.prototype._updateCache = function (ignoreParentClass) {
  19592. if (!ignoreParentClass) {
  19593. _super.prototype._updateCache.call(this);
  19594. }
  19595. this._cache.position.copyFrom(this.position);
  19596. this._cache.upVector.copyFrom(this.upVector);
  19597. };
  19598. // Synchronized
  19599. Camera.prototype._isSynchronized = function () {
  19600. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19601. };
  19602. Camera.prototype._isSynchronizedViewMatrix = function () {
  19603. if (!_super.prototype._isSynchronized.call(this))
  19604. return false;
  19605. return this._cache.position.equals(this.position)
  19606. && this._cache.upVector.equals(this.upVector)
  19607. && this.isSynchronizedWithParent();
  19608. };
  19609. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19610. var check = this._cache.mode === this.mode
  19611. && this._cache.minZ === this.minZ
  19612. && this._cache.maxZ === this.maxZ;
  19613. if (!check) {
  19614. return false;
  19615. }
  19616. var engine = this.getEngine();
  19617. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19618. check = this._cache.fov === this.fov
  19619. && this._cache.fovMode === this.fovMode
  19620. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19621. }
  19622. else {
  19623. check = this._cache.orthoLeft === this.orthoLeft
  19624. && this._cache.orthoRight === this.orthoRight
  19625. && this._cache.orthoBottom === this.orthoBottom
  19626. && this._cache.orthoTop === this.orthoTop
  19627. && this._cache.renderWidth === engine.getRenderWidth()
  19628. && this._cache.renderHeight === engine.getRenderHeight();
  19629. }
  19630. return check;
  19631. };
  19632. // Controls
  19633. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19634. };
  19635. Camera.prototype.detachControl = function (element) {
  19636. };
  19637. Camera.prototype.update = function () {
  19638. this._checkInputs();
  19639. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19640. this._updateRigCameras();
  19641. }
  19642. };
  19643. Camera.prototype._checkInputs = function () {
  19644. this.onAfterCheckInputsObservable.notifyObservers(this);
  19645. };
  19646. Object.defineProperty(Camera.prototype, "rigCameras", {
  19647. get: function () {
  19648. return this._rigCameras;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19654. get: function () {
  19655. return this._rigPostProcess;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19661. // invalidate framebuffer
  19662. if (this._postProcesses.length > 0) {
  19663. this._postProcesses[0].markTextureDirty();
  19664. }
  19665. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19666. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19667. var cam = this._rigCameras[i];
  19668. var rigPostProcess = cam._rigPostProcess;
  19669. // for VR rig, there does not have to be a post process
  19670. if (rigPostProcess) {
  19671. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19672. if (isPass) {
  19673. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19674. cam.isIntermediate = this._postProcesses.length === 0;
  19675. }
  19676. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19677. rigPostProcess.markTextureDirty();
  19678. }
  19679. else {
  19680. cam._postProcesses = this._postProcesses.slice(0);
  19681. }
  19682. }
  19683. };
  19684. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19685. if (insertAt === void 0) { insertAt = null; }
  19686. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19687. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19688. return 0;
  19689. }
  19690. if (insertAt == null || insertAt < 0) {
  19691. this._postProcesses.push(postProcess);
  19692. }
  19693. else {
  19694. this._postProcesses.splice(insertAt, 0, postProcess);
  19695. }
  19696. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19697. return this._postProcesses.indexOf(postProcess);
  19698. };
  19699. Camera.prototype.detachPostProcess = function (postProcess) {
  19700. var idx = this._postProcesses.indexOf(postProcess);
  19701. if (idx !== -1) {
  19702. this._postProcesses.splice(idx, 1);
  19703. }
  19704. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19705. };
  19706. Camera.prototype.getWorldMatrix = function () {
  19707. if (!this._worldMatrix) {
  19708. this._worldMatrix = BABYLON.Matrix.Identity();
  19709. }
  19710. var viewMatrix = this.getViewMatrix();
  19711. viewMatrix.invertToRef(this._worldMatrix);
  19712. return this._worldMatrix;
  19713. };
  19714. Camera.prototype._getViewMatrix = function () {
  19715. return BABYLON.Matrix.Identity();
  19716. };
  19717. Camera.prototype.getViewMatrix = function (force) {
  19718. if (!force && this._isSynchronizedViewMatrix()) {
  19719. return this._computedViewMatrix;
  19720. }
  19721. this.updateCache();
  19722. this._computedViewMatrix = this._getViewMatrix();
  19723. this._currentRenderId = this.getScene().getRenderId();
  19724. this._refreshFrustumPlanes = true;
  19725. if (!this.parent || !this.parent.getWorldMatrix) {
  19726. this._globalPosition.copyFrom(this.position);
  19727. }
  19728. else {
  19729. if (!this._worldMatrix) {
  19730. this._worldMatrix = BABYLON.Matrix.Identity();
  19731. }
  19732. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19733. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19734. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19735. this._computedViewMatrix.invert();
  19736. this._markSyncedWithParent();
  19737. }
  19738. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19739. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19740. }
  19741. this.onViewMatrixChangedObservable.notifyObservers(this);
  19742. return this._computedViewMatrix;
  19743. };
  19744. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19745. this._doNotComputeProjectionMatrix = true;
  19746. if (projection !== undefined) {
  19747. this._projectionMatrix = projection;
  19748. }
  19749. };
  19750. ;
  19751. Camera.prototype.unfreezeProjectionMatrix = function () {
  19752. this._doNotComputeProjectionMatrix = false;
  19753. };
  19754. ;
  19755. Camera.prototype.getProjectionMatrix = function (force) {
  19756. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19757. return this._projectionMatrix;
  19758. }
  19759. // Cache
  19760. this._cache.mode = this.mode;
  19761. this._cache.minZ = this.minZ;
  19762. this._cache.maxZ = this.maxZ;
  19763. // Matrix
  19764. this._refreshFrustumPlanes = true;
  19765. var engine = this.getEngine();
  19766. var scene = this.getScene();
  19767. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19768. this._cache.fov = this.fov;
  19769. this._cache.fovMode = this.fovMode;
  19770. this._cache.aspectRatio = engine.getAspectRatio(this);
  19771. if (this.minZ <= 0) {
  19772. this.minZ = 0.1;
  19773. }
  19774. if (scene.useRightHandedSystem) {
  19775. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19776. }
  19777. else {
  19778. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19779. }
  19780. }
  19781. else {
  19782. var halfWidth = engine.getRenderWidth() / 2.0;
  19783. var halfHeight = engine.getRenderHeight() / 2.0;
  19784. if (scene.useRightHandedSystem) {
  19785. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19786. }
  19787. else {
  19788. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19789. }
  19790. this._cache.orthoLeft = this.orthoLeft;
  19791. this._cache.orthoRight = this.orthoRight;
  19792. this._cache.orthoBottom = this.orthoBottom;
  19793. this._cache.orthoTop = this.orthoTop;
  19794. this._cache.renderWidth = engine.getRenderWidth();
  19795. this._cache.renderHeight = engine.getRenderHeight();
  19796. }
  19797. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19798. return this._projectionMatrix;
  19799. };
  19800. Camera.prototype.getTranformationMatrix = function () {
  19801. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19802. return this._transformMatrix;
  19803. };
  19804. Camera.prototype.updateFrustumPlanes = function () {
  19805. if (!this._refreshFrustumPlanes) {
  19806. return;
  19807. }
  19808. this.getTranformationMatrix();
  19809. if (!this._frustumPlanes) {
  19810. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19811. }
  19812. else {
  19813. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19814. }
  19815. this._refreshFrustumPlanes = false;
  19816. };
  19817. Camera.prototype.isInFrustum = function (target) {
  19818. this.updateFrustumPlanes();
  19819. return target.isInFrustum(this._frustumPlanes);
  19820. };
  19821. Camera.prototype.isCompletelyInFrustum = function (target) {
  19822. this.updateFrustumPlanes();
  19823. return target.isCompletelyInFrustum(this._frustumPlanes);
  19824. };
  19825. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19826. if (length === void 0) { length = 100; }
  19827. if (!transform) {
  19828. transform = this.getWorldMatrix();
  19829. }
  19830. if (!origin) {
  19831. origin = this.position;
  19832. }
  19833. var forward = new BABYLON.Vector3(0, 0, 1);
  19834. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19835. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19836. return new BABYLON.Ray(origin, direction, length);
  19837. };
  19838. Camera.prototype.dispose = function () {
  19839. // Observables
  19840. this.onViewMatrixChangedObservable.clear();
  19841. this.onProjectionMatrixChangedObservable.clear();
  19842. this.onAfterCheckInputsObservable.clear();
  19843. this.onRestoreStateObservable.clear();
  19844. // Inputs
  19845. if (this.inputs) {
  19846. this.inputs.clear();
  19847. }
  19848. // Animations
  19849. this.getScene().stopAnimation(this);
  19850. // Remove from scene
  19851. this.getScene().removeCamera(this);
  19852. while (this._rigCameras.length > 0) {
  19853. var camera = this._rigCameras.pop();
  19854. if (camera) {
  19855. camera.dispose();
  19856. }
  19857. }
  19858. // Postprocesses
  19859. if (this._rigPostProcess) {
  19860. this._rigPostProcess.dispose(this);
  19861. this._rigPostProcess = null;
  19862. this._postProcesses = [];
  19863. }
  19864. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19865. this._rigPostProcess = null;
  19866. this._postProcesses = [];
  19867. }
  19868. else {
  19869. var i = this._postProcesses.length;
  19870. while (--i >= 0) {
  19871. this._postProcesses[i].dispose(this);
  19872. }
  19873. }
  19874. // Render targets
  19875. var i = this.customRenderTargets.length;
  19876. while (--i >= 0) {
  19877. this.customRenderTargets[i].dispose();
  19878. }
  19879. this.customRenderTargets = [];
  19880. // Active Meshes
  19881. this._activeMeshes.dispose();
  19882. _super.prototype.dispose.call(this);
  19883. };
  19884. Object.defineProperty(Camera.prototype, "leftCamera", {
  19885. // ---- Camera rigs section ----
  19886. get: function () {
  19887. if (this._rigCameras.length < 1) {
  19888. return null;
  19889. }
  19890. return this._rigCameras[0];
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(Camera.prototype, "rightCamera", {
  19896. get: function () {
  19897. if (this._rigCameras.length < 2) {
  19898. return null;
  19899. }
  19900. return this._rigCameras[1];
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Camera.prototype.getLeftTarget = function () {
  19906. if (this._rigCameras.length < 1) {
  19907. return null;
  19908. }
  19909. return this._rigCameras[0].getTarget();
  19910. };
  19911. Camera.prototype.getRightTarget = function () {
  19912. if (this._rigCameras.length < 2) {
  19913. return null;
  19914. }
  19915. return this._rigCameras[1].getTarget();
  19916. };
  19917. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19918. if (this.cameraRigMode === mode) {
  19919. return;
  19920. }
  19921. while (this._rigCameras.length > 0) {
  19922. var camera = this._rigCameras.pop();
  19923. if (camera) {
  19924. camera.dispose();
  19925. }
  19926. }
  19927. this.cameraRigMode = mode;
  19928. this._cameraRigParams = {};
  19929. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19930. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19931. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19932. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19933. // create the rig cameras, unless none
  19934. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19935. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19936. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19937. if (leftCamera && rightCamera) {
  19938. this._rigCameras.push(leftCamera);
  19939. this._rigCameras.push(rightCamera);
  19940. }
  19941. }
  19942. switch (this.cameraRigMode) {
  19943. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19944. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19945. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19946. break;
  19947. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19948. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19949. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19950. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19951. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19952. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19953. break;
  19954. case Camera.RIG_MODE_VR:
  19955. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19956. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19957. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19958. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19959. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19960. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19961. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19962. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19963. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19964. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19965. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19966. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19967. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19968. if (metrics.compensateDistortion) {
  19969. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19970. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19971. }
  19972. break;
  19973. case Camera.RIG_MODE_WEBVR:
  19974. if (rigParams.vrDisplay) {
  19975. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19976. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19977. //Left eye
  19978. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19979. this._rigCameras[0].setCameraRigParameter("left", true);
  19980. //leaving this for future reference
  19981. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19982. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19983. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19984. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19985. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19986. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19987. this._rigCameras[0].parent = this;
  19988. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19989. //Right eye
  19990. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19991. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19992. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19993. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19994. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19995. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19996. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19997. this._rigCameras[1].parent = this;
  19998. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19999. if (Camera.UseAlternateWebVRRendering) {
  20000. this._rigCameras[1]._skipRendering = true;
  20001. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20002. }
  20003. }
  20004. break;
  20005. }
  20006. this._cascadePostProcessesToRigCams();
  20007. this.update();
  20008. };
  20009. Camera.prototype._getVRProjectionMatrix = function () {
  20010. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20011. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20012. return this._projectionMatrix;
  20013. };
  20014. Camera.prototype._updateCameraRotationMatrix = function () {
  20015. //Here for WebVR
  20016. };
  20017. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20018. //Here for WebVR
  20019. };
  20020. /**
  20021. * This function MUST be overwritten by the different WebVR cameras available.
  20022. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20023. */
  20024. Camera.prototype._getWebVRProjectionMatrix = function () {
  20025. return BABYLON.Matrix.Identity();
  20026. };
  20027. /**
  20028. * This function MUST be overwritten by the different WebVR cameras available.
  20029. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20030. */
  20031. Camera.prototype._getWebVRViewMatrix = function () {
  20032. return BABYLON.Matrix.Identity();
  20033. };
  20034. Camera.prototype.setCameraRigParameter = function (name, value) {
  20035. if (!this._cameraRigParams) {
  20036. this._cameraRigParams = {};
  20037. }
  20038. this._cameraRigParams[name] = value;
  20039. //provisionnally:
  20040. if (name === "interaxialDistance") {
  20041. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20042. }
  20043. };
  20044. /**
  20045. * needs to be overridden by children so sub has required properties to be copied
  20046. */
  20047. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20048. return null;
  20049. };
  20050. /**
  20051. * May need to be overridden by children
  20052. */
  20053. Camera.prototype._updateRigCameras = function () {
  20054. for (var i = 0; i < this._rigCameras.length; i++) {
  20055. this._rigCameras[i].minZ = this.minZ;
  20056. this._rigCameras[i].maxZ = this.maxZ;
  20057. this._rigCameras[i].fov = this.fov;
  20058. }
  20059. // only update viewport when ANAGLYPH
  20060. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20061. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20062. }
  20063. };
  20064. Camera.prototype._setupInputs = function () {
  20065. };
  20066. Camera.prototype.serialize = function () {
  20067. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20068. // Type
  20069. serializationObject.type = this.getClassName();
  20070. // Parent
  20071. if (this.parent) {
  20072. serializationObject.parentId = this.parent.id;
  20073. }
  20074. if (this.inputs) {
  20075. this.inputs.serialize(serializationObject);
  20076. }
  20077. // Animations
  20078. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20079. serializationObject.ranges = this.serializeAnimationRanges();
  20080. return serializationObject;
  20081. };
  20082. Camera.prototype.clone = function (name) {
  20083. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20084. };
  20085. Camera.prototype.getDirection = function (localAxis) {
  20086. var result = BABYLON.Vector3.Zero();
  20087. this.getDirectionToRef(localAxis, result);
  20088. return result;
  20089. };
  20090. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20091. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20092. };
  20093. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20094. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20095. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20096. switch (type) {
  20097. case "ArcRotateCamera":
  20098. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20099. case "DeviceOrientationCamera":
  20100. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20101. case "FollowCamera":
  20102. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20103. case "ArcFollowCamera":
  20104. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20105. case "GamepadCamera":
  20106. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20107. case "TouchCamera":
  20108. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20109. case "VirtualJoysticksCamera":
  20110. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20111. case "WebVRFreeCamera":
  20112. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20113. case "WebVRGamepadCamera":
  20114. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20115. case "VRDeviceOrientationFreeCamera":
  20116. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20117. case "VRDeviceOrientationGamepadCamera":
  20118. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20119. case "AnaglyphArcRotateCamera":
  20120. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20121. case "AnaglyphFreeCamera":
  20122. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20123. case "AnaglyphGamepadCamera":
  20124. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20125. case "AnaglyphUniversalCamera":
  20126. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20127. case "StereoscopicArcRotateCamera":
  20128. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20129. case "StereoscopicFreeCamera":
  20130. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20131. case "StereoscopicGamepadCamera":
  20132. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20133. case "StereoscopicUniversalCamera":
  20134. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20135. case "FreeCamera":// Forcing Universal here
  20136. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20137. default:// Universal Camera is the default value
  20138. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20139. }
  20140. };
  20141. Camera.prototype.computeWorldMatrix = function () {
  20142. return this.getWorldMatrix();
  20143. };
  20144. Camera.Parse = function (parsedCamera, scene) {
  20145. var type = parsedCamera.type;
  20146. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20147. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20148. // Parent
  20149. if (parsedCamera.parentId) {
  20150. camera._waitingParentId = parsedCamera.parentId;
  20151. }
  20152. //If camera has an input manager, let it parse inputs settings
  20153. if (camera.inputs) {
  20154. camera.inputs.parse(parsedCamera);
  20155. camera._setupInputs();
  20156. }
  20157. if (camera.setPosition) {
  20158. camera.position.copyFromFloats(0, 0, 0);
  20159. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20160. }
  20161. // Target
  20162. if (parsedCamera.target) {
  20163. if (camera.setTarget) {
  20164. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20165. }
  20166. }
  20167. // Apply 3d rig, when found
  20168. if (parsedCamera.cameraRigMode) {
  20169. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20170. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20171. }
  20172. // Animations
  20173. if (parsedCamera.animations) {
  20174. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20175. var parsedAnimation = parsedCamera.animations[animationIndex];
  20176. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20177. }
  20178. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20179. }
  20180. if (parsedCamera.autoAnimate) {
  20181. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20182. }
  20183. return camera;
  20184. };
  20185. // Statics
  20186. Camera._PERSPECTIVE_CAMERA = 0;
  20187. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20188. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20189. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20190. Camera._RIG_MODE_NONE = 0;
  20191. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20192. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20193. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20194. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20195. Camera._RIG_MODE_VR = 20;
  20196. Camera._RIG_MODE_WEBVR = 21;
  20197. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20198. Camera.UseAlternateWebVRRendering = false;
  20199. __decorate([
  20200. BABYLON.serializeAsVector3()
  20201. ], Camera.prototype, "position", void 0);
  20202. __decorate([
  20203. BABYLON.serializeAsVector3()
  20204. ], Camera.prototype, "upVector", void 0);
  20205. __decorate([
  20206. BABYLON.serialize()
  20207. ], Camera.prototype, "orthoLeft", void 0);
  20208. __decorate([
  20209. BABYLON.serialize()
  20210. ], Camera.prototype, "orthoRight", void 0);
  20211. __decorate([
  20212. BABYLON.serialize()
  20213. ], Camera.prototype, "orthoBottom", void 0);
  20214. __decorate([
  20215. BABYLON.serialize()
  20216. ], Camera.prototype, "orthoTop", void 0);
  20217. __decorate([
  20218. BABYLON.serialize()
  20219. ], Camera.prototype, "fov", void 0);
  20220. __decorate([
  20221. BABYLON.serialize()
  20222. ], Camera.prototype, "minZ", void 0);
  20223. __decorate([
  20224. BABYLON.serialize()
  20225. ], Camera.prototype, "maxZ", void 0);
  20226. __decorate([
  20227. BABYLON.serialize()
  20228. ], Camera.prototype, "inertia", void 0);
  20229. __decorate([
  20230. BABYLON.serialize()
  20231. ], Camera.prototype, "mode", void 0);
  20232. __decorate([
  20233. BABYLON.serialize()
  20234. ], Camera.prototype, "layerMask", void 0);
  20235. __decorate([
  20236. BABYLON.serialize()
  20237. ], Camera.prototype, "fovMode", void 0);
  20238. __decorate([
  20239. BABYLON.serialize()
  20240. ], Camera.prototype, "cameraRigMode", void 0);
  20241. __decorate([
  20242. BABYLON.serialize()
  20243. ], Camera.prototype, "interaxialDistance", void 0);
  20244. __decorate([
  20245. BABYLON.serialize()
  20246. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20247. return Camera;
  20248. }(BABYLON.Node));
  20249. BABYLON.Camera = Camera;
  20250. })(BABYLON || (BABYLON = {}));
  20251. //# sourceMappingURL=babylon.camera.js.map
  20252. var BABYLON;
  20253. (function (BABYLON) {
  20254. var RenderingManager = /** @class */ (function () {
  20255. function RenderingManager(scene) {
  20256. this._renderingGroups = new Array();
  20257. this._autoClearDepthStencil = {};
  20258. this._customOpaqueSortCompareFn = {};
  20259. this._customAlphaTestSortCompareFn = {};
  20260. this._customTransparentSortCompareFn = {};
  20261. this._renderinGroupInfo = null;
  20262. this._scene = scene;
  20263. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20264. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20265. }
  20266. }
  20267. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20268. if (depth === void 0) { depth = true; }
  20269. if (stencil === void 0) { stencil = true; }
  20270. if (this._depthStencilBufferAlreadyCleaned) {
  20271. return;
  20272. }
  20273. this._scene.getEngine().clear(null, false, depth, stencil);
  20274. this._depthStencilBufferAlreadyCleaned = true;
  20275. };
  20276. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20277. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20278. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20279. var info = null;
  20280. if (observable) {
  20281. if (!this._renderinGroupInfo) {
  20282. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20283. }
  20284. info = this._renderinGroupInfo;
  20285. info.scene = this._scene;
  20286. info.camera = this._scene.activeCamera;
  20287. }
  20288. // Dispatch sprites
  20289. if (renderSprites) {
  20290. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20291. var manager = this._scene.spriteManagers[index];
  20292. this.dispatchSprites(manager);
  20293. }
  20294. }
  20295. // Render
  20296. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20297. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20298. var renderingGroup = this._renderingGroups[index];
  20299. if (!renderingGroup && !observable)
  20300. continue;
  20301. var renderingGroupMask = 0;
  20302. // Fire PRECLEAR stage
  20303. if (observable && info) {
  20304. renderingGroupMask = Math.pow(2, index);
  20305. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20306. info.renderingGroupId = index;
  20307. observable.notifyObservers(info, renderingGroupMask);
  20308. }
  20309. // Clear depth/stencil if needed
  20310. if (RenderingManager.AUTOCLEAR) {
  20311. var autoClear = this._autoClearDepthStencil[index];
  20312. if (autoClear && autoClear.autoClear) {
  20313. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20314. }
  20315. }
  20316. if (observable && info) {
  20317. // Fire PREOPAQUE stage
  20318. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20319. observable.notifyObservers(info, renderingGroupMask);
  20320. // Fire PRETRANSPARENT stage
  20321. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20322. observable.notifyObservers(info, renderingGroupMask);
  20323. }
  20324. if (renderingGroup)
  20325. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20326. // Fire POSTTRANSPARENT stage
  20327. if (observable && info) {
  20328. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20329. observable.notifyObservers(info, renderingGroupMask);
  20330. }
  20331. }
  20332. };
  20333. RenderingManager.prototype.reset = function () {
  20334. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20335. var renderingGroup = this._renderingGroups[index];
  20336. if (renderingGroup) {
  20337. renderingGroup.prepare();
  20338. }
  20339. }
  20340. };
  20341. RenderingManager.prototype.dispose = function () {
  20342. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20343. var renderingGroup = this._renderingGroups[index];
  20344. if (renderingGroup) {
  20345. renderingGroup.dispose();
  20346. }
  20347. }
  20348. this._renderingGroups.length = 0;
  20349. };
  20350. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20351. if (this._renderingGroups[renderingGroupId] === undefined) {
  20352. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20353. }
  20354. };
  20355. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20356. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20357. this._prepareRenderingGroup(renderingGroupId);
  20358. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20359. };
  20360. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20361. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20362. this._prepareRenderingGroup(renderingGroupId);
  20363. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20364. };
  20365. /**
  20366. * @param subMesh The submesh to dispatch
  20367. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20368. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20369. */
  20370. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20371. if (mesh === undefined) {
  20372. mesh = subMesh.getMesh();
  20373. }
  20374. var renderingGroupId = mesh.renderingGroupId || 0;
  20375. this._prepareRenderingGroup(renderingGroupId);
  20376. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20377. };
  20378. /**
  20379. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20380. * This allowed control for front to back rendering or reversly depending of the special needs.
  20381. *
  20382. * @param renderingGroupId The rendering group id corresponding to its index
  20383. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20384. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20385. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20386. */
  20387. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20388. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20389. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20390. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20391. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20392. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20393. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20394. if (this._renderingGroups[renderingGroupId]) {
  20395. var group = this._renderingGroups[renderingGroupId];
  20396. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20397. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20398. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20399. }
  20400. };
  20401. /**
  20402. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20403. *
  20404. * @param renderingGroupId The rendering group id corresponding to its index
  20405. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20406. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20407. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20408. */
  20409. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20410. if (depth === void 0) { depth = true; }
  20411. if (stencil === void 0) { stencil = true; }
  20412. this._autoClearDepthStencil[renderingGroupId] = {
  20413. autoClear: autoClearDepthStencil,
  20414. depth: depth,
  20415. stencil: stencil
  20416. };
  20417. };
  20418. /**
  20419. * The max id used for rendering groups (not included)
  20420. */
  20421. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20422. /**
  20423. * The min id used for rendering groups (included)
  20424. */
  20425. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20426. /**
  20427. * Used to globally prevent autoclearing scenes.
  20428. */
  20429. RenderingManager.AUTOCLEAR = true;
  20430. return RenderingManager;
  20431. }());
  20432. BABYLON.RenderingManager = RenderingManager;
  20433. })(BABYLON || (BABYLON = {}));
  20434. //# sourceMappingURL=babylon.renderingManager.js.map
  20435. var BABYLON;
  20436. (function (BABYLON) {
  20437. var RenderingGroup = /** @class */ (function () {
  20438. /**
  20439. * Creates a new rendering group.
  20440. * @param index The rendering group index
  20441. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20442. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20443. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20444. */
  20445. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20446. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20447. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20448. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20449. this.index = index;
  20450. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20451. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20452. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20453. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20454. this._particleSystems = new BABYLON.SmartArray(256);
  20455. this._spriteManagers = new BABYLON.SmartArray(256);
  20456. this._edgesRenderers = new BABYLON.SmartArray(16);
  20457. this._scene = scene;
  20458. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20459. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20460. this.transparentSortCompareFn = transparentSortCompareFn;
  20461. }
  20462. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20463. /**
  20464. * Set the opaque sort comparison function.
  20465. * If null the sub meshes will be render in the order they were created
  20466. */
  20467. set: function (value) {
  20468. this._opaqueSortCompareFn = value;
  20469. if (value) {
  20470. this._renderOpaque = this.renderOpaqueSorted;
  20471. }
  20472. else {
  20473. this._renderOpaque = RenderingGroup.renderUnsorted;
  20474. }
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20480. /**
  20481. * Set the alpha test sort comparison function.
  20482. * If null the sub meshes will be render in the order they were created
  20483. */
  20484. set: function (value) {
  20485. this._alphaTestSortCompareFn = value;
  20486. if (value) {
  20487. this._renderAlphaTest = this.renderAlphaTestSorted;
  20488. }
  20489. else {
  20490. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20491. }
  20492. },
  20493. enumerable: true,
  20494. configurable: true
  20495. });
  20496. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20497. /**
  20498. * Set the transparent sort comparison function.
  20499. * If null the sub meshes will be render in the order they were created
  20500. */
  20501. set: function (value) {
  20502. if (value) {
  20503. this._transparentSortCompareFn = value;
  20504. }
  20505. else {
  20506. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20507. }
  20508. this._renderTransparent = this.renderTransparentSorted;
  20509. },
  20510. enumerable: true,
  20511. configurable: true
  20512. });
  20513. /**
  20514. * Render all the sub meshes contained in the group.
  20515. * @param customRenderFunction Used to override the default render behaviour of the group.
  20516. * @returns true if rendered some submeshes.
  20517. */
  20518. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20519. if (customRenderFunction) {
  20520. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20521. return;
  20522. }
  20523. var engine = this._scene.getEngine();
  20524. // Depth only
  20525. if (this._depthOnlySubMeshes.length !== 0) {
  20526. engine.setColorWrite(false);
  20527. this._renderAlphaTest(this._depthOnlySubMeshes);
  20528. engine.setColorWrite(true);
  20529. }
  20530. // Opaque
  20531. if (this._opaqueSubMeshes.length !== 0) {
  20532. this._renderOpaque(this._opaqueSubMeshes);
  20533. }
  20534. // Alpha test
  20535. if (this._alphaTestSubMeshes.length !== 0) {
  20536. this._renderAlphaTest(this._alphaTestSubMeshes);
  20537. }
  20538. var stencilState = engine.getStencilBuffer();
  20539. engine.setStencilBuffer(false);
  20540. // Sprites
  20541. if (renderSprites) {
  20542. this._renderSprites();
  20543. }
  20544. // Particles
  20545. if (renderParticles) {
  20546. this._renderParticles(activeMeshes);
  20547. }
  20548. if (this.onBeforeTransparentRendering) {
  20549. this.onBeforeTransparentRendering();
  20550. }
  20551. // Transparent
  20552. if (this._transparentSubMeshes.length !== 0) {
  20553. this._renderTransparent(this._transparentSubMeshes);
  20554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20555. }
  20556. // Set back stencil to false in case it changes before the edge renderer.
  20557. engine.setStencilBuffer(false);
  20558. // Edges
  20559. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20560. this._edgesRenderers.data[edgesRendererIndex].render();
  20561. }
  20562. // Restore Stencil state.
  20563. engine.setStencilBuffer(stencilState);
  20564. };
  20565. /**
  20566. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20567. * @param subMeshes The submeshes to render
  20568. */
  20569. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20570. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20571. };
  20572. /**
  20573. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20574. * @param subMeshes The submeshes to render
  20575. */
  20576. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20577. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20578. };
  20579. /**
  20580. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20581. * @param subMeshes The submeshes to render
  20582. */
  20583. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20584. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20585. };
  20586. /**
  20587. * Renders the submeshes in a specified order.
  20588. * @param subMeshes The submeshes to sort before render
  20589. * @param sortCompareFn The comparison function use to sort
  20590. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20591. * @param transparent Specifies to activate blending if true
  20592. */
  20593. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20594. var subIndex = 0;
  20595. var subMesh;
  20596. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20597. for (; subIndex < subMeshes.length; subIndex++) {
  20598. subMesh = subMeshes.data[subIndex];
  20599. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20600. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20601. }
  20602. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20603. if (sortCompareFn) {
  20604. sortedArray.sort(sortCompareFn);
  20605. }
  20606. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20607. subMesh = sortedArray[subIndex];
  20608. if (transparent) {
  20609. var material = subMesh.getMaterial();
  20610. if (material && material.needDepthPrePass) {
  20611. var engine = material.getScene().getEngine();
  20612. engine.setColorWrite(false);
  20613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20614. subMesh.render(false);
  20615. engine.setColorWrite(true);
  20616. }
  20617. }
  20618. subMesh.render(transparent);
  20619. }
  20620. };
  20621. /**
  20622. * Renders the submeshes in the order they were dispatched (no sort applied).
  20623. * @param subMeshes The submeshes to render
  20624. */
  20625. RenderingGroup.renderUnsorted = function (subMeshes) {
  20626. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20627. var submesh = subMeshes.data[subIndex];
  20628. submesh.render(false);
  20629. }
  20630. };
  20631. /**
  20632. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20633. * are rendered back to front if in the same alpha index.
  20634. *
  20635. * @param a The first submesh
  20636. * @param b The second submesh
  20637. * @returns The result of the comparison
  20638. */
  20639. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20640. // Alpha index first
  20641. if (a._alphaIndex > b._alphaIndex) {
  20642. return 1;
  20643. }
  20644. if (a._alphaIndex < b._alphaIndex) {
  20645. return -1;
  20646. }
  20647. // Then distance to camera
  20648. return RenderingGroup.backToFrontSortCompare(a, b);
  20649. };
  20650. /**
  20651. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20652. * are rendered back to front.
  20653. *
  20654. * @param a The first submesh
  20655. * @param b The second submesh
  20656. * @returns The result of the comparison
  20657. */
  20658. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20659. // Then distance to camera
  20660. if (a._distanceToCamera < b._distanceToCamera) {
  20661. return 1;
  20662. }
  20663. if (a._distanceToCamera > b._distanceToCamera) {
  20664. return -1;
  20665. }
  20666. return 0;
  20667. };
  20668. /**
  20669. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20670. * are rendered front to back (prevent overdraw).
  20671. *
  20672. * @param a The first submesh
  20673. * @param b The second submesh
  20674. * @returns The result of the comparison
  20675. */
  20676. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20677. // Then distance to camera
  20678. if (a._distanceToCamera < b._distanceToCamera) {
  20679. return -1;
  20680. }
  20681. if (a._distanceToCamera > b._distanceToCamera) {
  20682. return 1;
  20683. }
  20684. return 0;
  20685. };
  20686. /**
  20687. * Resets the different lists of submeshes to prepare a new frame.
  20688. */
  20689. RenderingGroup.prototype.prepare = function () {
  20690. this._opaqueSubMeshes.reset();
  20691. this._transparentSubMeshes.reset();
  20692. this._alphaTestSubMeshes.reset();
  20693. this._depthOnlySubMeshes.reset();
  20694. this._particleSystems.reset();
  20695. this._spriteManagers.reset();
  20696. this._edgesRenderers.reset();
  20697. };
  20698. RenderingGroup.prototype.dispose = function () {
  20699. this._opaqueSubMeshes.dispose();
  20700. this._transparentSubMeshes.dispose();
  20701. this._alphaTestSubMeshes.dispose();
  20702. this._depthOnlySubMeshes.dispose();
  20703. this._particleSystems.dispose();
  20704. this._spriteManagers.dispose();
  20705. this._edgesRenderers.dispose();
  20706. };
  20707. /**
  20708. * Inserts the submesh in its correct queue depending on its material.
  20709. * @param subMesh The submesh to dispatch
  20710. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20711. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20712. */
  20713. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20714. // Get mesh and materials if not provided
  20715. if (mesh === undefined) {
  20716. mesh = subMesh.getMesh();
  20717. }
  20718. if (material === undefined) {
  20719. material = subMesh.getMaterial();
  20720. }
  20721. if (material === null || material === undefined) {
  20722. return;
  20723. }
  20724. if (material.needAlphaBlendingForMesh(mesh)) {
  20725. this._transparentSubMeshes.push(subMesh);
  20726. }
  20727. else if (material.needAlphaTesting()) {
  20728. if (material.needDepthPrePass) {
  20729. this._depthOnlySubMeshes.push(subMesh);
  20730. }
  20731. this._alphaTestSubMeshes.push(subMesh);
  20732. }
  20733. else {
  20734. if (material.needDepthPrePass) {
  20735. this._depthOnlySubMeshes.push(subMesh);
  20736. }
  20737. this._opaqueSubMeshes.push(subMesh); // Opaque
  20738. }
  20739. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20740. this._edgesRenderers.push(mesh._edgesRenderer);
  20741. }
  20742. };
  20743. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20744. this._spriteManagers.push(spriteManager);
  20745. };
  20746. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20747. this._particleSystems.push(particleSystem);
  20748. };
  20749. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20750. if (this._particleSystems.length === 0) {
  20751. return;
  20752. }
  20753. // Particles
  20754. var activeCamera = this._scene.activeCamera;
  20755. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20756. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20757. var particleSystem = this._particleSystems.data[particleIndex];
  20758. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20759. continue;
  20760. }
  20761. var emitter = particleSystem.emitter;
  20762. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20763. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20764. }
  20765. }
  20766. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20767. };
  20768. RenderingGroup.prototype._renderSprites = function () {
  20769. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20770. return;
  20771. }
  20772. // Sprites
  20773. var activeCamera = this._scene.activeCamera;
  20774. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20775. for (var id = 0; id < this._spriteManagers.length; id++) {
  20776. var spriteManager = this._spriteManagers.data[id];
  20777. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20778. spriteManager.render();
  20779. }
  20780. }
  20781. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20782. };
  20783. return RenderingGroup;
  20784. }());
  20785. BABYLON.RenderingGroup = RenderingGroup;
  20786. })(BABYLON || (BABYLON = {}));
  20787. //# sourceMappingURL=babylon.renderingGroup.js.map
  20788. var BABYLON;
  20789. (function (BABYLON) {
  20790. var ClickInfo = /** @class */ (function () {
  20791. function ClickInfo() {
  20792. this._singleClick = false;
  20793. this._doubleClick = false;
  20794. this._hasSwiped = false;
  20795. this._ignore = false;
  20796. }
  20797. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20798. get: function () {
  20799. return this._singleClick;
  20800. },
  20801. set: function (b) {
  20802. this._singleClick = b;
  20803. },
  20804. enumerable: true,
  20805. configurable: true
  20806. });
  20807. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20808. get: function () {
  20809. return this._doubleClick;
  20810. },
  20811. set: function (b) {
  20812. this._doubleClick = b;
  20813. },
  20814. enumerable: true,
  20815. configurable: true
  20816. });
  20817. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20818. get: function () {
  20819. return this._hasSwiped;
  20820. },
  20821. set: function (b) {
  20822. this._hasSwiped = b;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20828. get: function () {
  20829. return this._ignore;
  20830. },
  20831. set: function (b) {
  20832. this._ignore = b;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. return ClickInfo;
  20838. }());
  20839. /**
  20840. * This class is used by the onRenderingGroupObservable
  20841. */
  20842. var RenderingGroupInfo = /** @class */ (function () {
  20843. function RenderingGroupInfo() {
  20844. }
  20845. /**
  20846. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20847. * This stage will be fired no matter what
  20848. */
  20849. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20850. /**
  20851. * Called before opaque object are rendered.
  20852. * This stage will be fired only if there's 3D Opaque content to render
  20853. */
  20854. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20855. /**
  20856. * Called after the opaque objects are rendered and before the transparent ones
  20857. * This stage will be fired only if there's 3D transparent content to render
  20858. */
  20859. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20860. /**
  20861. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20862. * This stage will be fired no matter what
  20863. */
  20864. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20865. return RenderingGroupInfo;
  20866. }());
  20867. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20868. /**
  20869. * Represents a scene to be rendered by the engine.
  20870. * @see http://doc.babylonjs.com/page.php?p=21911
  20871. */
  20872. var Scene = /** @class */ (function () {
  20873. /**
  20874. * @constructor
  20875. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20876. */
  20877. function Scene(engine) {
  20878. // Members
  20879. this.autoClear = true;
  20880. this.autoClearDepthAndStencil = true;
  20881. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20882. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20883. this.forceWireframe = false;
  20884. this._forcePointsCloud = false;
  20885. this.forceShowBoundingBoxes = false;
  20886. this.animationsEnabled = true;
  20887. this.useConstantAnimationDeltaTime = false;
  20888. this.constantlyUpdateMeshUnderPointer = false;
  20889. this.hoverCursor = "pointer";
  20890. this.defaultCursor = "";
  20891. /**
  20892. * This is used to call preventDefault() on pointer down
  20893. * in order to block unwanted artifacts like system double clicks
  20894. */
  20895. this.preventDefaultOnPointerDown = true;
  20896. // Metadata
  20897. this.metadata = null;
  20898. /**
  20899. * An event triggered when the scene is disposed.
  20900. * @type {BABYLON.Observable}
  20901. */
  20902. this.onDisposeObservable = new BABYLON.Observable();
  20903. /**
  20904. * An event triggered before rendering the scene (right after animations and physics)
  20905. * @type {BABYLON.Observable}
  20906. */
  20907. this.onBeforeRenderObservable = new BABYLON.Observable();
  20908. /**
  20909. * An event triggered after rendering the scene
  20910. * @type {BABYLON.Observable}
  20911. */
  20912. this.onAfterRenderObservable = new BABYLON.Observable();
  20913. /**
  20914. * An event triggered before animating the scene
  20915. * @type {BABYLON.Observable}
  20916. */
  20917. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20918. /**
  20919. * An event triggered after animations processing
  20920. * @type {BABYLON.Observable}
  20921. */
  20922. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20923. /**
  20924. * An event triggered before draw calls are ready to be sent
  20925. * @type {BABYLON.Observable}
  20926. */
  20927. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20928. /**
  20929. * An event triggered after draw calls have been sent
  20930. * @type {BABYLON.Observable}
  20931. */
  20932. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20933. /**
  20934. * An event triggered when physic simulation is about to be run
  20935. * @type {BABYLON.Observable}
  20936. */
  20937. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20938. /**
  20939. * An event triggered when physic simulation has been done
  20940. * @type {BABYLON.Observable}
  20941. */
  20942. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20943. /**
  20944. * An event triggered when the scene is ready
  20945. * @type {BABYLON.Observable}
  20946. */
  20947. this.onReadyObservable = new BABYLON.Observable();
  20948. /**
  20949. * An event triggered before rendering a camera
  20950. * @type {BABYLON.Observable}
  20951. */
  20952. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20953. /**
  20954. * An event triggered after rendering a camera
  20955. * @type {BABYLON.Observable}
  20956. */
  20957. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20958. /**
  20959. * An event triggered when active meshes evaluation is about to start
  20960. * @type {BABYLON.Observable}
  20961. */
  20962. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20963. /**
  20964. * An event triggered when active meshes evaluation is done
  20965. * @type {BABYLON.Observable}
  20966. */
  20967. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20968. /**
  20969. * An event triggered when particles rendering is about to start
  20970. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20971. * @type {BABYLON.Observable}
  20972. */
  20973. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20974. /**
  20975. * An event triggered when particles rendering is done
  20976. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20977. * @type {BABYLON.Observable}
  20978. */
  20979. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20980. /**
  20981. * An event triggered when sprites rendering is about to start
  20982. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20983. * @type {BABYLON.Observable}
  20984. */
  20985. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20986. /**
  20987. * An event triggered when sprites rendering is done
  20988. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20989. * @type {BABYLON.Observable}
  20990. */
  20991. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20992. /**
  20993. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20994. * @type {BABYLON.Observable}
  20995. */
  20996. this.onDataLoadedObservable = new BABYLON.Observable();
  20997. /**
  20998. * An event triggered when a camera is created
  20999. * @type {BABYLON.Observable}
  21000. */
  21001. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21002. /**
  21003. * An event triggered when a camera is removed
  21004. * @type {BABYLON.Observable}
  21005. */
  21006. this.onCameraRemovedObservable = new BABYLON.Observable();
  21007. /**
  21008. * An event triggered when a light is created
  21009. * @type {BABYLON.Observable}
  21010. */
  21011. this.onNewLightAddedObservable = new BABYLON.Observable();
  21012. /**
  21013. * An event triggered when a light is removed
  21014. * @type {BABYLON.Observable}
  21015. */
  21016. this.onLightRemovedObservable = new BABYLON.Observable();
  21017. /**
  21018. * An event triggered when a geometry is created
  21019. * @type {BABYLON.Observable}
  21020. */
  21021. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21022. /**
  21023. * An event triggered when a geometry is removed
  21024. * @type {BABYLON.Observable}
  21025. */
  21026. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21027. /**
  21028. * An event triggered when a transform node is created
  21029. * @type {BABYLON.Observable}
  21030. */
  21031. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21032. /**
  21033. * An event triggered when a transform node is removed
  21034. * @type {BABYLON.Observable}
  21035. */
  21036. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21037. /**
  21038. * An event triggered when a mesh is created
  21039. * @type {BABYLON.Observable}
  21040. */
  21041. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21042. /**
  21043. * An event triggered when a mesh is removed
  21044. * @type {BABYLON.Observable}
  21045. */
  21046. this.onMeshRemovedObservable = new BABYLON.Observable();
  21047. /**
  21048. * An event triggered when render targets are about to be rendered
  21049. * Can happen multiple times per frame.
  21050. * @type {BABYLON.Observable}
  21051. */
  21052. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21053. /**
  21054. * An event triggered when render targets were rendered.
  21055. * Can happen multiple times per frame.
  21056. * @type {BABYLON.Observable}
  21057. */
  21058. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21059. /**
  21060. * An event triggered before calculating deterministic simulation step
  21061. * @type {BABYLON.Observable}
  21062. */
  21063. this.onBeforeStepObservable = new BABYLON.Observable();
  21064. /**
  21065. * An event triggered after calculating deterministic simulation step
  21066. * @type {BABYLON.Observable}
  21067. */
  21068. this.onAfterStepObservable = new BABYLON.Observable();
  21069. /**
  21070. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21071. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21072. * 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)
  21073. */
  21074. this.onRenderingGroupObservable = new BABYLON.Observable();
  21075. // Animations
  21076. this.animations = [];
  21077. /**
  21078. * 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).
  21079. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21080. */
  21081. this.onPrePointerObservable = new BABYLON.Observable();
  21082. /**
  21083. * Observable event triggered each time an input event is received from the rendering canvas
  21084. */
  21085. this.onPointerObservable = new BABYLON.Observable();
  21086. this._meshPickProceed = false;
  21087. this._currentPickResult = null;
  21088. this._previousPickResult = null;
  21089. this._totalPointersPressed = 0;
  21090. this._doubleClickOccured = false;
  21091. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21092. this.cameraToUseForPointers = null;
  21093. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21094. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21095. this._startingPointerTime = 0;
  21096. this._previousStartingPointerTime = 0;
  21097. // Deterministic lockstep
  21098. this._timeAccumulator = 0;
  21099. this._currentStepId = 0;
  21100. this._currentInternalStep = 0;
  21101. // Keyboard
  21102. /**
  21103. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21104. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21105. */
  21106. this.onPreKeyboardObservable = new BABYLON.Observable();
  21107. /**
  21108. * Observable event triggered each time an keyboard event is received from the hosting window
  21109. */
  21110. this.onKeyboardObservable = new BABYLON.Observable();
  21111. // Coordinate system
  21112. /**
  21113. * use right-handed coordinate system on this scene.
  21114. * @type {boolean}
  21115. */
  21116. this._useRightHandedSystem = false;
  21117. // Fog
  21118. this._fogEnabled = true;
  21119. this._fogMode = Scene.FOGMODE_NONE;
  21120. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21121. this.fogDensity = 0.1;
  21122. this.fogStart = 0;
  21123. this.fogEnd = 1000.0;
  21124. // Lights
  21125. /**
  21126. * is shadow enabled on this scene.
  21127. * @type {boolean}
  21128. */
  21129. this._shadowsEnabled = true;
  21130. /**
  21131. * is light enabled on this scene.
  21132. * @type {boolean}
  21133. */
  21134. this._lightsEnabled = true;
  21135. /**
  21136. * All of the lights added to this scene.
  21137. * @see BABYLON.Light
  21138. * @type {BABYLON.Light[]}
  21139. */
  21140. this.lights = new Array();
  21141. // Cameras
  21142. /** All of the cameras added to this scene. */
  21143. this.cameras = new Array();
  21144. /** All of the active cameras added to this scene. */
  21145. this.activeCameras = new Array();
  21146. // Meshes
  21147. /**
  21148. * All of the tranform nodes added to this scene.
  21149. * @see BABYLON.TransformNode
  21150. * @type {BABYLON.TransformNode[]}
  21151. */
  21152. this.transformNodes = new Array();
  21153. /**
  21154. * All of the (abstract) meshes added to this scene.
  21155. * @see BABYLON.AbstractMesh
  21156. * @type {BABYLON.AbstractMesh[]}
  21157. */
  21158. this.meshes = new Array();
  21159. /**
  21160. * All of the animation groups added to this scene.
  21161. * @see BABYLON.AnimationGroup
  21162. * @type {BABYLON.AnimationGroup[]}
  21163. */
  21164. this.animationGroups = new Array();
  21165. // Geometries
  21166. this._geometries = new Array();
  21167. this.materials = new Array();
  21168. this.multiMaterials = new Array();
  21169. // Textures
  21170. this._texturesEnabled = true;
  21171. this.textures = new Array();
  21172. // Particles
  21173. this.particlesEnabled = true;
  21174. this.particleSystems = new Array();
  21175. // Sprites
  21176. this.spritesEnabled = true;
  21177. this.spriteManagers = new Array();
  21178. /**
  21179. * The list of layers (background and foreground) of the scene.
  21180. */
  21181. this.layers = new Array();
  21182. /**
  21183. * The list of effect layers (highlights/glow) contained in the scene.
  21184. */
  21185. this.effectLayers = new Array();
  21186. // Skeletons
  21187. this._skeletonsEnabled = true;
  21188. this.skeletons = new Array();
  21189. // Morph targets
  21190. this.morphTargetManagers = new Array();
  21191. // Lens flares
  21192. this.lensFlaresEnabled = true;
  21193. this.lensFlareSystems = new Array();
  21194. // Collisions
  21195. this.collisionsEnabled = true;
  21196. /** Defines the gravity applied to this scene */
  21197. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21198. // Postprocesses
  21199. this.postProcesses = new Array();
  21200. this.postProcessesEnabled = true;
  21201. // Customs render targets
  21202. this.renderTargetsEnabled = true;
  21203. this.dumpNextRenderTargets = false;
  21204. this.customRenderTargets = new Array();
  21205. // Imported meshes
  21206. this.importedMeshesFiles = new Array();
  21207. // Probes
  21208. this.probesEnabled = true;
  21209. this.reflectionProbes = new Array();
  21210. this._actionManagers = new Array();
  21211. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21212. // Procedural textures
  21213. this.proceduralTexturesEnabled = true;
  21214. this._proceduralTextures = new Array();
  21215. this.soundTracks = new Array();
  21216. this._audioEnabled = true;
  21217. this._headphone = false;
  21218. // Performance counters
  21219. this._totalVertices = new BABYLON.PerfCounter();
  21220. this._activeIndices = new BABYLON.PerfCounter();
  21221. this._activeParticles = new BABYLON.PerfCounter();
  21222. this._activeBones = new BABYLON.PerfCounter();
  21223. this._animationTime = 0;
  21224. this.animationTimeScale = 1;
  21225. this._renderId = 0;
  21226. this._executeWhenReadyTimeoutId = -1;
  21227. this._intermediateRendering = false;
  21228. this._viewUpdateFlag = -1;
  21229. this._projectionUpdateFlag = -1;
  21230. this._alternateViewUpdateFlag = -1;
  21231. this._alternateProjectionUpdateFlag = -1;
  21232. this._toBeDisposed = new BABYLON.SmartArray(256);
  21233. this._activeRequests = new Array();
  21234. this._pendingData = new Array();
  21235. this._isDisposed = false;
  21236. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21237. this._activeMeshes = new BABYLON.SmartArray(256);
  21238. this._processedMaterials = new BABYLON.SmartArray(256);
  21239. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21240. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21241. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21242. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21243. this._activeAnimatables = new Array();
  21244. this._transformMatrix = BABYLON.Matrix.Zero();
  21245. this._useAlternateCameraConfiguration = false;
  21246. this._alternateRendering = false;
  21247. this.requireLightSorting = false;
  21248. this._activeMeshesFrozen = false;
  21249. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21250. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21251. this._engine.scenes.push(this);
  21252. this._uid = null;
  21253. this._renderingManager = new BABYLON.RenderingManager(this);
  21254. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21255. if (BABYLON.OutlineRenderer) {
  21256. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21257. }
  21258. if (BABYLON.Tools.IsWindowObjectExist()) {
  21259. this.attachControl();
  21260. }
  21261. //simplification queue
  21262. if (BABYLON.SimplificationQueue) {
  21263. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21264. }
  21265. //collision coordinator initialization. For now legacy per default.
  21266. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21267. // Uniform Buffer
  21268. this._createUbo();
  21269. // Default Image processing definition.
  21270. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21271. }
  21272. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21273. /** The fog is deactivated */
  21274. get: function () {
  21275. return Scene._FOGMODE_NONE;
  21276. },
  21277. enumerable: true,
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21281. /** The fog density is following an exponential function */
  21282. get: function () {
  21283. return Scene._FOGMODE_EXP;
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21289. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21290. get: function () {
  21291. return Scene._FOGMODE_EXP2;
  21292. },
  21293. enumerable: true,
  21294. configurable: true
  21295. });
  21296. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21297. /** The fog density is following a linear function. */
  21298. get: function () {
  21299. return Scene._FOGMODE_LINEAR;
  21300. },
  21301. enumerable: true,
  21302. configurable: true
  21303. });
  21304. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21305. /**
  21306. * Texture used in all pbr material as the reflection texture.
  21307. * As in the majority of the scene they are the same (exception for multi room and so on),
  21308. * this is easier to reference from here than from all the materials.
  21309. */
  21310. get: function () {
  21311. return this._environmentTexture;
  21312. },
  21313. /**
  21314. * Texture used in all pbr material as the reflection texture.
  21315. * As in the majority of the scene they are the same (exception for multi room and so on),
  21316. * this is easier to set here than in all the materials.
  21317. */
  21318. set: function (value) {
  21319. if (this._environmentTexture === value) {
  21320. return;
  21321. }
  21322. this._environmentTexture = value;
  21323. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21324. },
  21325. enumerable: true,
  21326. configurable: true
  21327. });
  21328. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21329. /**
  21330. * Default image processing configuration used either in the rendering
  21331. * Forward main pass or through the imageProcessingPostProcess if present.
  21332. * As in the majority of the scene they are the same (exception for multi camera),
  21333. * this is easier to reference from here than from all the materials and post process.
  21334. *
  21335. * No setter as we it is a shared configuration, you can set the values instead.
  21336. */
  21337. get: function () {
  21338. return this._imageProcessingConfiguration;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21344. get: function () {
  21345. return this._forcePointsCloud;
  21346. },
  21347. set: function (value) {
  21348. if (this._forcePointsCloud === value) {
  21349. return;
  21350. }
  21351. this._forcePointsCloud = value;
  21352. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Scene.prototype, "onDispose", {
  21358. /** A function to be executed when this scene is disposed. */
  21359. set: function (callback) {
  21360. if (this._onDisposeObserver) {
  21361. this.onDisposeObservable.remove(this._onDisposeObserver);
  21362. }
  21363. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21364. },
  21365. enumerable: true,
  21366. configurable: true
  21367. });
  21368. Object.defineProperty(Scene.prototype, "beforeRender", {
  21369. /** A function to be executed before rendering this scene */
  21370. set: function (callback) {
  21371. if (this._onBeforeRenderObserver) {
  21372. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21373. }
  21374. if (callback) {
  21375. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21376. }
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(Scene.prototype, "afterRender", {
  21382. /** A function to be executed after rendering this scene */
  21383. set: function (callback) {
  21384. if (this._onAfterRenderObserver) {
  21385. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21386. }
  21387. if (callback) {
  21388. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21389. }
  21390. },
  21391. enumerable: true,
  21392. configurable: true
  21393. });
  21394. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21395. set: function (callback) {
  21396. if (this._onBeforeCameraRenderObserver) {
  21397. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21398. }
  21399. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21405. set: function (callback) {
  21406. if (this._onAfterCameraRenderObserver) {
  21407. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21408. }
  21409. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21410. },
  21411. enumerable: true,
  21412. configurable: true
  21413. });
  21414. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21415. get: function () {
  21416. if (!this._gamepadManager) {
  21417. this._gamepadManager = new BABYLON.GamepadManager(this);
  21418. }
  21419. return this._gamepadManager;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21425. get: function () {
  21426. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21432. get: function () {
  21433. return this._useRightHandedSystem;
  21434. },
  21435. set: function (value) {
  21436. if (this._useRightHandedSystem === value) {
  21437. return;
  21438. }
  21439. this._useRightHandedSystem = value;
  21440. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21441. },
  21442. enumerable: true,
  21443. configurable: true
  21444. });
  21445. Scene.prototype.setStepId = function (newStepId) {
  21446. this._currentStepId = newStepId;
  21447. };
  21448. ;
  21449. Scene.prototype.getStepId = function () {
  21450. return this._currentStepId;
  21451. };
  21452. ;
  21453. Scene.prototype.getInternalStep = function () {
  21454. return this._currentInternalStep;
  21455. };
  21456. ;
  21457. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21458. get: function () {
  21459. return this._fogEnabled;
  21460. },
  21461. /**
  21462. * is fog enabled on this scene.
  21463. */
  21464. set: function (value) {
  21465. if (this._fogEnabled === value) {
  21466. return;
  21467. }
  21468. this._fogEnabled = value;
  21469. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(Scene.prototype, "fogMode", {
  21475. get: function () {
  21476. return this._fogMode;
  21477. },
  21478. set: function (value) {
  21479. if (this._fogMode === value) {
  21480. return;
  21481. }
  21482. this._fogMode = value;
  21483. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21489. get: function () {
  21490. return this._shadowsEnabled;
  21491. },
  21492. set: function (value) {
  21493. if (this._shadowsEnabled === value) {
  21494. return;
  21495. }
  21496. this._shadowsEnabled = value;
  21497. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21503. get: function () {
  21504. return this._lightsEnabled;
  21505. },
  21506. set: function (value) {
  21507. if (this._lightsEnabled === value) {
  21508. return;
  21509. }
  21510. this._lightsEnabled = value;
  21511. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21517. /** The default material used on meshes when no material is affected */
  21518. get: function () {
  21519. if (!this._defaultMaterial) {
  21520. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21521. }
  21522. return this._defaultMaterial;
  21523. },
  21524. /** The default material used on meshes when no material is affected */
  21525. set: function (value) {
  21526. this._defaultMaterial = value;
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21532. get: function () {
  21533. return this._texturesEnabled;
  21534. },
  21535. set: function (value) {
  21536. if (this._texturesEnabled === value) {
  21537. return;
  21538. }
  21539. this._texturesEnabled = value;
  21540. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21546. get: function () {
  21547. return this._skeletonsEnabled;
  21548. },
  21549. set: function (value) {
  21550. if (this._skeletonsEnabled === value) {
  21551. return;
  21552. }
  21553. this._skeletonsEnabled = value;
  21554. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21560. get: function () {
  21561. if (!this._postProcessRenderPipelineManager) {
  21562. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21563. }
  21564. return this._postProcessRenderPipelineManager;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21570. get: function () {
  21571. if (!this._mainSoundTrack) {
  21572. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21573. }
  21574. return this._mainSoundTrack;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21580. get: function () {
  21581. return this._alternateRendering;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21587. get: function () {
  21588. return this._frustumPlanes;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21594. /**
  21595. * Gets the current geometry buffer associated to the scene.
  21596. */
  21597. get: function () {
  21598. return this._geometryBufferRenderer;
  21599. },
  21600. /**
  21601. * Sets the current geometry buffer for the scene.
  21602. */
  21603. set: function (geometryBufferRenderer) {
  21604. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21605. this._geometryBufferRenderer = geometryBufferRenderer;
  21606. }
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. Object.defineProperty(Scene.prototype, "debugLayer", {
  21612. // Properties
  21613. get: function () {
  21614. if (!this._debugLayer) {
  21615. this._debugLayer = new BABYLON.DebugLayer(this);
  21616. }
  21617. return this._debugLayer;
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21623. get: function () {
  21624. return this._workerCollisions;
  21625. },
  21626. set: function (enabled) {
  21627. if (!BABYLON.CollisionCoordinatorLegacy) {
  21628. return;
  21629. }
  21630. enabled = (enabled && !!Worker);
  21631. this._workerCollisions = enabled;
  21632. if (this.collisionCoordinator) {
  21633. this.collisionCoordinator.destroy();
  21634. }
  21635. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21636. this.collisionCoordinator.init(this);
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21642. get: function () {
  21643. return this._selectionOctree;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21649. /**
  21650. * The mesh that is currently under the pointer.
  21651. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21652. */
  21653. get: function () {
  21654. return this._pointerOverMesh;
  21655. },
  21656. enumerable: true,
  21657. configurable: true
  21658. });
  21659. Object.defineProperty(Scene.prototype, "pointerX", {
  21660. /**
  21661. * Current on-screen X position of the pointer
  21662. * @return {number} X position of the pointer
  21663. */
  21664. get: function () {
  21665. return this._pointerX;
  21666. },
  21667. enumerable: true,
  21668. configurable: true
  21669. });
  21670. Object.defineProperty(Scene.prototype, "pointerY", {
  21671. /**
  21672. * Current on-screen Y position of the pointer
  21673. * @return {number} Y position of the pointer
  21674. */
  21675. get: function () {
  21676. return this._pointerY;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Scene.prototype.getCachedMaterial = function () {
  21682. return this._cachedMaterial;
  21683. };
  21684. Scene.prototype.getCachedEffect = function () {
  21685. return this._cachedEffect;
  21686. };
  21687. Scene.prototype.getCachedVisibility = function () {
  21688. return this._cachedVisibility;
  21689. };
  21690. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21691. if (visibility === void 0) { visibility = 1; }
  21692. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21693. };
  21694. Scene.prototype.getBoundingBoxRenderer = function () {
  21695. if (!this._boundingBoxRenderer) {
  21696. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21697. }
  21698. return this._boundingBoxRenderer;
  21699. };
  21700. Scene.prototype.getOutlineRenderer = function () {
  21701. return this._outlineRenderer;
  21702. };
  21703. Scene.prototype.getEngine = function () {
  21704. return this._engine;
  21705. };
  21706. Scene.prototype.getTotalVertices = function () {
  21707. return this._totalVertices.current;
  21708. };
  21709. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21710. get: function () {
  21711. return this._totalVertices;
  21712. },
  21713. enumerable: true,
  21714. configurable: true
  21715. });
  21716. Scene.prototype.getActiveIndices = function () {
  21717. return this._activeIndices.current;
  21718. };
  21719. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21720. get: function () {
  21721. return this._activeIndices;
  21722. },
  21723. enumerable: true,
  21724. configurable: true
  21725. });
  21726. Scene.prototype.getActiveParticles = function () {
  21727. return this._activeParticles.current;
  21728. };
  21729. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21730. get: function () {
  21731. return this._activeParticles;
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. Scene.prototype.getActiveBones = function () {
  21737. return this._activeBones.current;
  21738. };
  21739. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21740. get: function () {
  21741. return this._activeBones;
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. // Stats
  21747. Scene.prototype.getInterFramePerfCounter = function () {
  21748. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21749. return 0;
  21750. };
  21751. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21752. get: function () {
  21753. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21754. return null;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Scene.prototype.getLastFrameDuration = function () {
  21760. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21761. return 0;
  21762. };
  21763. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21764. get: function () {
  21765. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21766. return null;
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21772. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21773. return 0;
  21774. };
  21775. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21776. get: function () {
  21777. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21778. return null;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. Scene.prototype.getActiveMeshes = function () {
  21784. return this._activeMeshes;
  21785. };
  21786. Scene.prototype.getRenderTargetsDuration = function () {
  21787. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21788. return 0;
  21789. };
  21790. Scene.prototype.getRenderDuration = function () {
  21791. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21792. return 0;
  21793. };
  21794. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21795. get: function () {
  21796. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21797. return null;
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Scene.prototype.getParticlesDuration = function () {
  21803. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21804. return 0;
  21805. };
  21806. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21807. get: function () {
  21808. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21809. return null;
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. Scene.prototype.getSpritesDuration = function () {
  21815. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21816. return 0;
  21817. };
  21818. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21819. get: function () {
  21820. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21821. return null;
  21822. },
  21823. enumerable: true,
  21824. configurable: true
  21825. });
  21826. Scene.prototype.getAnimationRatio = function () {
  21827. return this._animationRatio;
  21828. };
  21829. Scene.prototype.getRenderId = function () {
  21830. return this._renderId;
  21831. };
  21832. Scene.prototype.incrementRenderId = function () {
  21833. this._renderId++;
  21834. };
  21835. Scene.prototype._updatePointerPosition = function (evt) {
  21836. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21837. if (!canvasRect) {
  21838. return;
  21839. }
  21840. this._pointerX = evt.clientX - canvasRect.left;
  21841. this._pointerY = evt.clientY - canvasRect.top;
  21842. this._unTranslatedPointerX = this._pointerX;
  21843. this._unTranslatedPointerY = this._pointerY;
  21844. };
  21845. Scene.prototype._createUbo = function () {
  21846. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21847. this._sceneUbo.addUniform("viewProjection", 16);
  21848. this._sceneUbo.addUniform("view", 16);
  21849. };
  21850. Scene.prototype._createAlternateUbo = function () {
  21851. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21852. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21853. this._alternateSceneUbo.addUniform("view", 16);
  21854. };
  21855. // Pointers handling
  21856. /**
  21857. * Use this method to simulate a pointer move on a mesh
  21858. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21859. */
  21860. Scene.prototype.simulatePointerMove = function (pickResult) {
  21861. var evt = new PointerEvent("pointermove");
  21862. return this._processPointerMove(pickResult, evt);
  21863. };
  21864. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21865. var canvas = this._engine.getRenderingCanvas();
  21866. if (!canvas) {
  21867. return this;
  21868. }
  21869. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21870. this.setPointerOverSprite(null);
  21871. this.setPointerOverMesh(pickResult.pickedMesh);
  21872. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21873. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21874. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21875. }
  21876. else {
  21877. canvas.style.cursor = this.hoverCursor;
  21878. }
  21879. }
  21880. else {
  21881. canvas.style.cursor = this.defaultCursor;
  21882. }
  21883. }
  21884. else {
  21885. this.setPointerOverMesh(null);
  21886. // Sprites
  21887. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21888. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21889. this.setPointerOverSprite(pickResult.pickedSprite);
  21890. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21891. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21892. }
  21893. else {
  21894. canvas.style.cursor = this.hoverCursor;
  21895. }
  21896. }
  21897. else {
  21898. this.setPointerOverSprite(null);
  21899. // Restore pointer
  21900. canvas.style.cursor = this.defaultCursor;
  21901. }
  21902. }
  21903. if (pickResult) {
  21904. if (this.onPointerMove) {
  21905. this.onPointerMove(evt, pickResult);
  21906. }
  21907. if (this.onPointerObservable.hasObservers()) {
  21908. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21909. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21910. this.onPointerObservable.notifyObservers(pi, type);
  21911. }
  21912. }
  21913. return this;
  21914. };
  21915. /**
  21916. * Use this method to simulate a pointer down on a mesh
  21917. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21918. */
  21919. Scene.prototype.simulatePointerDown = function (pickResult) {
  21920. var evt = new PointerEvent("pointerdown");
  21921. return this._processPointerDown(pickResult, evt);
  21922. };
  21923. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21924. var _this = this;
  21925. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21926. this._pickedDownMesh = pickResult.pickedMesh;
  21927. var actionManager = pickResult.pickedMesh.actionManager;
  21928. if (actionManager) {
  21929. if (actionManager.hasPickTriggers) {
  21930. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21931. switch (evt.button) {
  21932. case 0:
  21933. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21934. break;
  21935. case 1:
  21936. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21937. break;
  21938. case 2:
  21939. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21940. break;
  21941. }
  21942. }
  21943. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21944. window.setTimeout(function () {
  21945. 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);
  21946. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21947. if (_this._totalPointersPressed !== 0 &&
  21948. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21949. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21950. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21951. _this._startingPointerTime = 0;
  21952. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21953. }
  21954. }
  21955. }, Scene.LongPressDelay);
  21956. }
  21957. }
  21958. }
  21959. if (pickResult) {
  21960. if (this.onPointerDown) {
  21961. this.onPointerDown(evt, pickResult);
  21962. }
  21963. if (this.onPointerObservable.hasObservers()) {
  21964. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21965. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21966. this.onPointerObservable.notifyObservers(pi, type);
  21967. }
  21968. }
  21969. return this;
  21970. };
  21971. /**
  21972. * Use this method to simulate a pointer up on a mesh
  21973. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21974. */
  21975. Scene.prototype.simulatePointerUp = function (pickResult) {
  21976. var evt = new PointerEvent("pointerup");
  21977. var clickInfo = new ClickInfo();
  21978. clickInfo.singleClick = true;
  21979. clickInfo.ignore = true;
  21980. return this._processPointerUp(pickResult, evt, clickInfo);
  21981. };
  21982. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21983. if (pickResult && pickResult && pickResult.pickedMesh) {
  21984. this._pickedUpMesh = pickResult.pickedMesh;
  21985. if (this._pickedDownMesh === this._pickedUpMesh) {
  21986. if (this.onPointerPick) {
  21987. this.onPointerPick(evt, pickResult);
  21988. }
  21989. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21990. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21991. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21992. this.onPointerObservable.notifyObservers(pi, type);
  21993. }
  21994. }
  21995. if (pickResult.pickedMesh.actionManager) {
  21996. if (clickInfo.ignore) {
  21997. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21998. }
  21999. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22000. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22001. }
  22002. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22003. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22004. }
  22005. }
  22006. }
  22007. if (this._pickedDownMesh &&
  22008. this._pickedDownMesh.actionManager &&
  22009. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22010. this._pickedDownMesh !== this._pickedUpMesh) {
  22011. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22012. }
  22013. if (this.onPointerUp) {
  22014. this.onPointerUp(evt, pickResult);
  22015. }
  22016. if (this.onPointerObservable.hasObservers()) {
  22017. if (!clickInfo.ignore) {
  22018. if (!clickInfo.hasSwiped) {
  22019. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22020. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22021. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22022. this.onPointerObservable.notifyObservers(pi, type);
  22023. }
  22024. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22025. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22026. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22027. this.onPointerObservable.notifyObservers(pi, type);
  22028. }
  22029. }
  22030. }
  22031. else {
  22032. var type = BABYLON.PointerEventTypes.POINTERUP;
  22033. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22034. this.onPointerObservable.notifyObservers(pi, type);
  22035. }
  22036. }
  22037. return this;
  22038. };
  22039. /**
  22040. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22041. * @param attachUp defines if you want to attach events to pointerup
  22042. * @param attachDown defines if you want to attach events to pointerdown
  22043. * @param attachMove defines if you want to attach events to pointermove
  22044. */
  22045. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22046. var _this = this;
  22047. if (attachUp === void 0) { attachUp = true; }
  22048. if (attachDown === void 0) { attachDown = true; }
  22049. if (attachMove === void 0) { attachMove = true; }
  22050. this._initActionManager = function (act, clickInfo) {
  22051. if (!_this._meshPickProceed) {
  22052. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22053. _this._currentPickResult = pickResult;
  22054. if (pickResult) {
  22055. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22056. }
  22057. _this._meshPickProceed = true;
  22058. }
  22059. return act;
  22060. };
  22061. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22062. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22063. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22064. btn !== _this._previousButtonPressed) {
  22065. _this._doubleClickOccured = false;
  22066. clickInfo.singleClick = true;
  22067. clickInfo.ignore = false;
  22068. cb(clickInfo, _this._currentPickResult);
  22069. }
  22070. };
  22071. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22072. var clickInfo = new ClickInfo();
  22073. _this._currentPickResult = null;
  22074. var act = null;
  22075. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22076. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22077. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22078. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22079. act = _this._initActionManager(act, clickInfo);
  22080. if (act)
  22081. checkPicking = act.hasPickTriggers;
  22082. }
  22083. if (checkPicking) {
  22084. var btn = evt.button;
  22085. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22086. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22087. if (!clickInfo.hasSwiped) {
  22088. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22089. if (!checkSingleClickImmediately) {
  22090. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22091. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22092. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22093. act = _this._initActionManager(act, clickInfo);
  22094. if (act)
  22095. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22096. }
  22097. }
  22098. if (checkSingleClickImmediately) {
  22099. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22100. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22101. btn !== _this._previousButtonPressed) {
  22102. clickInfo.singleClick = true;
  22103. cb(clickInfo, _this._currentPickResult);
  22104. }
  22105. }
  22106. else {
  22107. // wait that no double click has been raised during the double click delay
  22108. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22109. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22110. }
  22111. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22112. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22113. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22114. act = _this._initActionManager(act, clickInfo);
  22115. if (act)
  22116. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22117. }
  22118. if (checkDoubleClick) {
  22119. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22120. if (btn === _this._previousButtonPressed &&
  22121. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22122. !_this._doubleClickOccured) {
  22123. // pointer has not moved for 2 clicks, it's a double click
  22124. if (!clickInfo.hasSwiped &&
  22125. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22126. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22127. _this._previousStartingPointerTime = 0;
  22128. _this._doubleClickOccured = true;
  22129. clickInfo.doubleClick = true;
  22130. clickInfo.ignore = false;
  22131. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22132. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22133. }
  22134. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22135. cb(clickInfo, _this._currentPickResult);
  22136. }
  22137. else {
  22138. _this._doubleClickOccured = false;
  22139. _this._previousStartingPointerTime = _this._startingPointerTime;
  22140. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22141. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22142. _this._previousButtonPressed = btn;
  22143. if (Scene.ExclusiveDoubleClickMode) {
  22144. if (_this._previousDelayedSimpleClickTimeout) {
  22145. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22146. }
  22147. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22148. cb(clickInfo, _this._previousPickResult);
  22149. }
  22150. else {
  22151. cb(clickInfo, _this._currentPickResult);
  22152. }
  22153. }
  22154. }
  22155. else {
  22156. _this._doubleClickOccured = false;
  22157. _this._previousStartingPointerTime = _this._startingPointerTime;
  22158. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22159. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22160. _this._previousButtonPressed = btn;
  22161. }
  22162. }
  22163. }
  22164. }
  22165. clickInfo.ignore = true;
  22166. cb(clickInfo, _this._currentPickResult);
  22167. };
  22168. this._spritePredicate = function (sprite) {
  22169. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22170. };
  22171. this._onPointerMove = function (evt) {
  22172. _this._updatePointerPosition(evt);
  22173. // PreObservable support
  22174. if (_this.onPrePointerObservable.hasObservers()) {
  22175. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22176. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22177. _this.onPrePointerObservable.notifyObservers(pi, type);
  22178. if (pi.skipOnPointerObservable) {
  22179. return;
  22180. }
  22181. }
  22182. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22183. return;
  22184. }
  22185. if (!_this.pointerMovePredicate) {
  22186. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22187. }
  22188. // Meshes
  22189. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22190. _this._processPointerMove(pickResult, evt);
  22191. };
  22192. this._onPointerDown = function (evt) {
  22193. _this._totalPointersPressed++;
  22194. _this._pickedDownMesh = null;
  22195. _this._meshPickProceed = false;
  22196. _this._updatePointerPosition(evt);
  22197. if (_this.preventDefaultOnPointerDown && canvas) {
  22198. evt.preventDefault();
  22199. canvas.focus();
  22200. }
  22201. // PreObservable support
  22202. if (_this.onPrePointerObservable.hasObservers()) {
  22203. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22204. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22205. _this.onPrePointerObservable.notifyObservers(pi, type);
  22206. if (pi.skipOnPointerObservable) {
  22207. return;
  22208. }
  22209. }
  22210. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22211. return;
  22212. }
  22213. _this._startingPointerPosition.x = _this._pointerX;
  22214. _this._startingPointerPosition.y = _this._pointerY;
  22215. _this._startingPointerTime = new Date().getTime();
  22216. if (!_this.pointerDownPredicate) {
  22217. _this.pointerDownPredicate = function (mesh) {
  22218. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22219. };
  22220. }
  22221. // Meshes
  22222. _this._pickedDownMesh = null;
  22223. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22224. _this._processPointerDown(pickResult, evt);
  22225. // Sprites
  22226. _this._pickedDownSprite = null;
  22227. if (_this.spriteManagers.length > 0) {
  22228. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22229. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22230. if (pickResult.pickedSprite.actionManager) {
  22231. _this._pickedDownSprite = pickResult.pickedSprite;
  22232. switch (evt.button) {
  22233. case 0:
  22234. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22235. break;
  22236. case 1:
  22237. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22238. break;
  22239. case 2:
  22240. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22241. break;
  22242. }
  22243. if (pickResult.pickedSprite.actionManager) {
  22244. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22245. }
  22246. }
  22247. }
  22248. }
  22249. };
  22250. this._onPointerUp = function (evt) {
  22251. if (_this._totalPointersPressed === 0) {
  22252. return; // So we need to test it the pointer down was pressed before.
  22253. }
  22254. _this._totalPointersPressed--;
  22255. _this._pickedUpMesh = null;
  22256. _this._meshPickProceed = false;
  22257. _this._updatePointerPosition(evt);
  22258. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22259. // PreObservable support
  22260. if (_this.onPrePointerObservable.hasObservers()) {
  22261. if (!clickInfo.ignore) {
  22262. if (!clickInfo.hasSwiped) {
  22263. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22264. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22265. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22266. _this.onPrePointerObservable.notifyObservers(pi, type);
  22267. if (pi.skipOnPointerObservable) {
  22268. return;
  22269. }
  22270. }
  22271. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22272. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22273. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22274. _this.onPrePointerObservable.notifyObservers(pi, type);
  22275. if (pi.skipOnPointerObservable) {
  22276. return;
  22277. }
  22278. }
  22279. }
  22280. }
  22281. else {
  22282. var type = BABYLON.PointerEventTypes.POINTERUP;
  22283. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22284. _this.onPrePointerObservable.notifyObservers(pi, type);
  22285. if (pi.skipOnPointerObservable) {
  22286. return;
  22287. }
  22288. }
  22289. }
  22290. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22291. return;
  22292. }
  22293. if (!_this.pointerUpPredicate) {
  22294. _this.pointerUpPredicate = function (mesh) {
  22295. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22296. };
  22297. }
  22298. // Meshes
  22299. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22300. _this._initActionManager(null, clickInfo);
  22301. }
  22302. if (!pickResult) {
  22303. pickResult = _this._currentPickResult;
  22304. }
  22305. _this._processPointerUp(pickResult, evt, clickInfo);
  22306. // Sprites
  22307. if (_this.spriteManagers.length > 0) {
  22308. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22309. if (spritePickResult) {
  22310. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22311. if (spritePickResult.pickedSprite.actionManager) {
  22312. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22313. if (spritePickResult.pickedSprite.actionManager) {
  22314. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22315. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22316. }
  22317. }
  22318. }
  22319. }
  22320. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22321. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22322. }
  22323. }
  22324. }
  22325. _this._previousPickResult = _this._currentPickResult;
  22326. });
  22327. };
  22328. this._onKeyDown = function (evt) {
  22329. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22330. if (_this.onPreKeyboardObservable.hasObservers()) {
  22331. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22332. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22333. if (pi.skipOnPointerObservable) {
  22334. return;
  22335. }
  22336. }
  22337. if (_this.onKeyboardObservable.hasObservers()) {
  22338. var pi = new BABYLON.KeyboardInfo(type, evt);
  22339. _this.onKeyboardObservable.notifyObservers(pi, type);
  22340. }
  22341. if (_this.actionManager) {
  22342. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22343. }
  22344. };
  22345. this._onKeyUp = function (evt) {
  22346. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22347. if (_this.onPreKeyboardObservable.hasObservers()) {
  22348. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22349. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22350. if (pi.skipOnPointerObservable) {
  22351. return;
  22352. }
  22353. }
  22354. if (_this.onKeyboardObservable.hasObservers()) {
  22355. var pi = new BABYLON.KeyboardInfo(type, evt);
  22356. _this.onKeyboardObservable.notifyObservers(pi, type);
  22357. }
  22358. if (_this.actionManager) {
  22359. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22360. }
  22361. };
  22362. var engine = this.getEngine();
  22363. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22364. if (!canvas) {
  22365. return;
  22366. }
  22367. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22368. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22369. });
  22370. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22371. if (!canvas) {
  22372. return;
  22373. }
  22374. canvas.removeEventListener("keydown", _this._onKeyDown);
  22375. canvas.removeEventListener("keyup", _this._onKeyUp);
  22376. });
  22377. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22378. var canvas = this._engine.getRenderingCanvas();
  22379. if (!canvas) {
  22380. return;
  22381. }
  22382. if (attachMove) {
  22383. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22384. // Wheel
  22385. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22386. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22387. }
  22388. if (attachDown) {
  22389. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22390. }
  22391. if (attachUp) {
  22392. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22393. }
  22394. canvas.tabIndex = 1;
  22395. };
  22396. Scene.prototype.detachControl = function () {
  22397. var engine = this.getEngine();
  22398. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22399. var canvas = engine.getRenderingCanvas();
  22400. if (!canvas) {
  22401. return;
  22402. }
  22403. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22404. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22405. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22406. if (this._onCanvasBlurObserver) {
  22407. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22408. }
  22409. if (this._onCanvasFocusObserver) {
  22410. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22411. }
  22412. // Wheel
  22413. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22414. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22415. // Keyboard
  22416. canvas.removeEventListener("keydown", this._onKeyDown);
  22417. canvas.removeEventListener("keyup", this._onKeyUp);
  22418. // Observables
  22419. this.onKeyboardObservable.clear();
  22420. this.onPreKeyboardObservable.clear();
  22421. this.onPointerObservable.clear();
  22422. this.onPrePointerObservable.clear();
  22423. };
  22424. /**
  22425. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22426. * Delay loaded resources are not taking in account
  22427. * @return true if all required resources are ready
  22428. */
  22429. Scene.prototype.isReady = function () {
  22430. if (this._isDisposed) {
  22431. return false;
  22432. }
  22433. if (this._pendingData.length > 0) {
  22434. return false;
  22435. }
  22436. var index;
  22437. var engine = this.getEngine();
  22438. // Geometries
  22439. for (index = 0; index < this._geometries.length; index++) {
  22440. var geometry = this._geometries[index];
  22441. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22442. return false;
  22443. }
  22444. }
  22445. // Meshes
  22446. for (index = 0; index < this.meshes.length; index++) {
  22447. var mesh = this.meshes[index];
  22448. if (!mesh.isEnabled()) {
  22449. continue;
  22450. }
  22451. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22452. continue;
  22453. }
  22454. if (!mesh.isReady(true)) {
  22455. return false;
  22456. }
  22457. // Effect layers
  22458. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22459. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22460. var layer = _a[_i];
  22461. if (!layer.hasMesh(mesh)) {
  22462. continue;
  22463. }
  22464. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22465. var subMesh = _c[_b];
  22466. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22467. return false;
  22468. }
  22469. }
  22470. }
  22471. }
  22472. return true;
  22473. };
  22474. Scene.prototype.resetCachedMaterial = function () {
  22475. this._cachedMaterial = null;
  22476. this._cachedEffect = null;
  22477. this._cachedVisibility = null;
  22478. };
  22479. Scene.prototype.registerBeforeRender = function (func) {
  22480. this.onBeforeRenderObservable.add(func);
  22481. };
  22482. Scene.prototype.unregisterBeforeRender = function (func) {
  22483. this.onBeforeRenderObservable.removeCallback(func);
  22484. };
  22485. Scene.prototype.registerAfterRender = function (func) {
  22486. this.onAfterRenderObservable.add(func);
  22487. };
  22488. Scene.prototype.unregisterAfterRender = function (func) {
  22489. this.onAfterRenderObservable.removeCallback(func);
  22490. };
  22491. Scene.prototype._executeOnceBeforeRender = function (func) {
  22492. var _this = this;
  22493. var execFunc = function () {
  22494. func();
  22495. setTimeout(function () {
  22496. _this.unregisterBeforeRender(execFunc);
  22497. });
  22498. };
  22499. this.registerBeforeRender(execFunc);
  22500. };
  22501. /**
  22502. * The provided function will run before render once and will be disposed afterwards.
  22503. * A timeout delay can be provided so that the function will be executed in N ms.
  22504. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22505. * @param func The function to be executed.
  22506. * @param timeout optional delay in ms
  22507. */
  22508. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22509. var _this = this;
  22510. if (timeout !== undefined) {
  22511. setTimeout(function () {
  22512. _this._executeOnceBeforeRender(func);
  22513. }, timeout);
  22514. }
  22515. else {
  22516. this._executeOnceBeforeRender(func);
  22517. }
  22518. };
  22519. Scene.prototype._addPendingData = function (data) {
  22520. this._pendingData.push(data);
  22521. };
  22522. Scene.prototype._removePendingData = function (data) {
  22523. var wasLoading = this.isLoading;
  22524. var index = this._pendingData.indexOf(data);
  22525. if (index !== -1) {
  22526. this._pendingData.splice(index, 1);
  22527. }
  22528. if (wasLoading && !this.isLoading) {
  22529. this.onDataLoadedObservable.notifyObservers(this);
  22530. }
  22531. };
  22532. Scene.prototype.getWaitingItemsCount = function () {
  22533. return this._pendingData.length;
  22534. };
  22535. Object.defineProperty(Scene.prototype, "isLoading", {
  22536. get: function () {
  22537. return this._pendingData.length > 0;
  22538. },
  22539. enumerable: true,
  22540. configurable: true
  22541. });
  22542. /**
  22543. * Registers a function to be executed when the scene is ready.
  22544. * @param {Function} func - the function to be executed.
  22545. */
  22546. Scene.prototype.executeWhenReady = function (func) {
  22547. var _this = this;
  22548. this.onReadyObservable.add(func);
  22549. if (this._executeWhenReadyTimeoutId !== -1) {
  22550. return;
  22551. }
  22552. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22553. _this._checkIsReady();
  22554. }, 150);
  22555. };
  22556. /**
  22557. * Returns a promise that resolves when the scene is ready.
  22558. * @returns A promise that resolves when the scene is ready.
  22559. */
  22560. Scene.prototype.whenReadyAsync = function () {
  22561. var _this = this;
  22562. return new Promise(function (resolve) {
  22563. _this.executeWhenReady(function () {
  22564. resolve();
  22565. });
  22566. });
  22567. };
  22568. Scene.prototype._checkIsReady = function () {
  22569. var _this = this;
  22570. if (this.isReady()) {
  22571. this.onReadyObservable.notifyObservers(this);
  22572. this.onReadyObservable.clear();
  22573. this._executeWhenReadyTimeoutId = -1;
  22574. return;
  22575. }
  22576. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22577. _this._checkIsReady();
  22578. }, 150);
  22579. };
  22580. // Animations
  22581. /**
  22582. * Will start the animation sequence of a given target
  22583. * @param target - the target
  22584. * @param {number} from - from which frame should animation start
  22585. * @param {number} to - till which frame should animation run.
  22586. * @param {boolean} [loop] - should the animation loop
  22587. * @param {number} [speedRatio] - the speed in which to run the animation
  22588. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22589. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22590. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22591. * See BABYLON.Animatable
  22592. */
  22593. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22594. if (speedRatio === void 0) { speedRatio = 1.0; }
  22595. if (from > to && speedRatio > 0) {
  22596. speedRatio *= -1;
  22597. }
  22598. this.stopAnimation(target);
  22599. if (!animatable) {
  22600. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22601. }
  22602. // Local animations
  22603. if (target.animations) {
  22604. animatable.appendAnimations(target, target.animations);
  22605. }
  22606. // Children animations
  22607. if (target.getAnimatables) {
  22608. var animatables = target.getAnimatables();
  22609. for (var index = 0; index < animatables.length; index++) {
  22610. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22611. }
  22612. }
  22613. animatable.reset();
  22614. return animatable;
  22615. };
  22616. /**
  22617. * Begin a new animation on a given node
  22618. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22619. * @param {BABYLON.Animation[]} defines the list of animations to start
  22620. * @param {number} from defines the initial value
  22621. * @param {number} to defines the final value
  22622. * @param {boolean} loop defines if you want animation to loop (off by default)
  22623. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22624. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22625. * @returns the list of created animatables
  22626. */
  22627. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22628. if (speedRatio === undefined) {
  22629. speedRatio = 1.0;
  22630. }
  22631. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22632. return animatable;
  22633. };
  22634. /**
  22635. * Begin a new animation on a given node and its hierarchy
  22636. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22637. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  22638. * @param {BABYLON.Animation[]} defines the list of animations to start
  22639. * @param {number} from defines the initial value
  22640. * @param {number} to defines the final value
  22641. * @param {boolean} loop defines if you want animation to loop (off by default)
  22642. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22643. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22644. * @returns the list of animatables created for all nodes
  22645. */
  22646. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22647. var children = target.getDescendants(directDescendantsOnly);
  22648. var result = [];
  22649. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22650. var child = children_1[_i];
  22651. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22652. }
  22653. return result;
  22654. };
  22655. Scene.prototype.getAnimatableByTarget = function (target) {
  22656. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22657. if (this._activeAnimatables[index].target === target) {
  22658. return this._activeAnimatables[index];
  22659. }
  22660. }
  22661. return null;
  22662. };
  22663. Object.defineProperty(Scene.prototype, "animatables", {
  22664. get: function () {
  22665. return this._activeAnimatables;
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. /**
  22671. * Will stop the animation of the given target
  22672. * @param target - the target
  22673. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22674. * @see beginAnimation
  22675. */
  22676. Scene.prototype.stopAnimation = function (target, animationName) {
  22677. var animatable = this.getAnimatableByTarget(target);
  22678. if (animatable) {
  22679. animatable.stop(animationName);
  22680. }
  22681. };
  22682. /**
  22683. * Stops and removes all animations that have been applied to the scene
  22684. */
  22685. Scene.prototype.stopAllAnimations = function () {
  22686. if (this._activeAnimatables) {
  22687. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22688. this._activeAnimatables[i].stop();
  22689. }
  22690. this._activeAnimatables = [];
  22691. }
  22692. };
  22693. Scene.prototype._animate = function () {
  22694. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22695. return;
  22696. }
  22697. // Getting time
  22698. var now = BABYLON.Tools.Now;
  22699. if (!this._animationTimeLast) {
  22700. if (this._pendingData.length > 0) {
  22701. return;
  22702. }
  22703. this._animationTimeLast = now;
  22704. }
  22705. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22706. this._animationTime += deltaTime;
  22707. this._animationTimeLast = now;
  22708. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22709. this._activeAnimatables[index]._animate(this._animationTime);
  22710. }
  22711. };
  22712. // Matrix
  22713. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22714. this._useAlternateCameraConfiguration = active;
  22715. };
  22716. Scene.prototype.getViewMatrix = function () {
  22717. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22718. };
  22719. Scene.prototype.getProjectionMatrix = function () {
  22720. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22721. };
  22722. Scene.prototype.getTransformMatrix = function () {
  22723. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22724. };
  22725. Scene.prototype.setTransformMatrix = function (view, projection) {
  22726. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22727. return;
  22728. }
  22729. this._viewUpdateFlag = view.updateFlag;
  22730. this._projectionUpdateFlag = projection.updateFlag;
  22731. this._viewMatrix = view;
  22732. this._projectionMatrix = projection;
  22733. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22734. // Update frustum
  22735. if (!this._frustumPlanes) {
  22736. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22737. }
  22738. else {
  22739. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22740. }
  22741. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22742. var otherCamera = this.activeCamera._alternateCamera;
  22743. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22744. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22745. }
  22746. if (this._sceneUbo.useUbo) {
  22747. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22748. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22749. this._sceneUbo.update();
  22750. }
  22751. };
  22752. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22753. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22754. return;
  22755. }
  22756. this._alternateViewUpdateFlag = view.updateFlag;
  22757. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22758. this._alternateViewMatrix = view;
  22759. this._alternateProjectionMatrix = projection;
  22760. if (!this._alternateTransformMatrix) {
  22761. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22762. }
  22763. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22764. if (!this._alternateSceneUbo) {
  22765. this._createAlternateUbo();
  22766. }
  22767. if (this._alternateSceneUbo.useUbo) {
  22768. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22769. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22770. this._alternateSceneUbo.update();
  22771. }
  22772. };
  22773. Scene.prototype.getSceneUniformBuffer = function () {
  22774. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22775. };
  22776. // Methods
  22777. Scene.prototype.getUniqueId = function () {
  22778. var result = Scene._uniqueIdCounter;
  22779. Scene._uniqueIdCounter++;
  22780. return result;
  22781. };
  22782. Scene.prototype.addMesh = function (newMesh) {
  22783. this.meshes.push(newMesh);
  22784. //notify the collision coordinator
  22785. if (this.collisionCoordinator) {
  22786. this.collisionCoordinator.onMeshAdded(newMesh);
  22787. }
  22788. newMesh._resyncLightSources();
  22789. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22790. };
  22791. Scene.prototype.removeMesh = function (toRemove) {
  22792. var index = this.meshes.indexOf(toRemove);
  22793. if (index !== -1) {
  22794. // Remove from the scene if mesh found
  22795. this.meshes.splice(index, 1);
  22796. }
  22797. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22798. return index;
  22799. };
  22800. Scene.prototype.addTransformNode = function (newTransformNode) {
  22801. this.transformNodes.push(newTransformNode);
  22802. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22803. };
  22804. Scene.prototype.removeTransformNode = function (toRemove) {
  22805. var index = this.transformNodes.indexOf(toRemove);
  22806. if (index !== -1) {
  22807. // Remove from the scene if found
  22808. this.transformNodes.splice(index, 1);
  22809. }
  22810. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22811. return index;
  22812. };
  22813. Scene.prototype.removeSkeleton = function (toRemove) {
  22814. var index = this.skeletons.indexOf(toRemove);
  22815. if (index !== -1) {
  22816. // Remove from the scene if found
  22817. this.skeletons.splice(index, 1);
  22818. }
  22819. return index;
  22820. };
  22821. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22822. var index = this.morphTargetManagers.indexOf(toRemove);
  22823. if (index !== -1) {
  22824. // Remove from the scene if found
  22825. this.morphTargetManagers.splice(index, 1);
  22826. }
  22827. return index;
  22828. };
  22829. Scene.prototype.removeLight = function (toRemove) {
  22830. var index = this.lights.indexOf(toRemove);
  22831. if (index !== -1) {
  22832. // Remove from meshes
  22833. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22834. var mesh = _a[_i];
  22835. mesh._removeLightSource(toRemove);
  22836. }
  22837. // Remove from the scene if mesh found
  22838. this.lights.splice(index, 1);
  22839. this.sortLightsByPriority();
  22840. }
  22841. this.onLightRemovedObservable.notifyObservers(toRemove);
  22842. return index;
  22843. };
  22844. Scene.prototype.removeCamera = function (toRemove) {
  22845. var index = this.cameras.indexOf(toRemove);
  22846. if (index !== -1) {
  22847. // Remove from the scene if mesh found
  22848. this.cameras.splice(index, 1);
  22849. }
  22850. // Remove from activeCameras
  22851. var index2 = this.activeCameras.indexOf(toRemove);
  22852. if (index2 !== -1) {
  22853. // Remove from the scene if mesh found
  22854. this.activeCameras.splice(index2, 1);
  22855. }
  22856. // Reset the activeCamera
  22857. if (this.activeCamera === toRemove) {
  22858. if (this.cameras.length > 0) {
  22859. this.activeCamera = this.cameras[0];
  22860. }
  22861. else {
  22862. this.activeCamera = null;
  22863. }
  22864. }
  22865. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22866. return index;
  22867. };
  22868. Scene.prototype.removeParticleSystem = function (toRemove) {
  22869. var index = this.particleSystems.indexOf(toRemove);
  22870. if (index !== -1) {
  22871. this.particleSystems.splice(index, 1);
  22872. }
  22873. return index;
  22874. };
  22875. ;
  22876. Scene.prototype.removeAnimation = function (toRemove) {
  22877. var index = this.animations.indexOf(toRemove);
  22878. if (index !== -1) {
  22879. this.animations.splice(index, 1);
  22880. }
  22881. return index;
  22882. };
  22883. ;
  22884. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22885. var index = this.multiMaterials.indexOf(toRemove);
  22886. if (index !== -1) {
  22887. this.multiMaterials.splice(index, 1);
  22888. }
  22889. return index;
  22890. };
  22891. ;
  22892. Scene.prototype.removeMaterial = function (toRemove) {
  22893. var index = this.materials.indexOf(toRemove);
  22894. if (index !== -1) {
  22895. this.materials.splice(index, 1);
  22896. }
  22897. return index;
  22898. };
  22899. ;
  22900. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22901. var index = this.lensFlareSystems.indexOf(toRemove);
  22902. if (index !== -1) {
  22903. this.lensFlareSystems.splice(index, 1);
  22904. }
  22905. return index;
  22906. };
  22907. ;
  22908. Scene.prototype.removeActionManager = function (toRemove) {
  22909. var index = this._actionManagers.indexOf(toRemove);
  22910. if (index !== -1) {
  22911. this._actionManagers.splice(index, 1);
  22912. }
  22913. return index;
  22914. };
  22915. ;
  22916. Scene.prototype.addLight = function (newLight) {
  22917. this.lights.push(newLight);
  22918. this.sortLightsByPriority();
  22919. // Add light to all meshes (To support if the light is removed and then readded)
  22920. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22921. var mesh = _a[_i];
  22922. if (mesh._lightSources.indexOf(newLight) === -1) {
  22923. mesh._lightSources.push(newLight);
  22924. mesh._resyncLightSources();
  22925. }
  22926. }
  22927. this.onNewLightAddedObservable.notifyObservers(newLight);
  22928. };
  22929. Scene.prototype.sortLightsByPriority = function () {
  22930. if (this.requireLightSorting) {
  22931. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22932. }
  22933. };
  22934. Scene.prototype.addCamera = function (newCamera) {
  22935. this.cameras.push(newCamera);
  22936. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22937. };
  22938. Scene.prototype.addSkeleton = function (newSkeleton) {
  22939. this.skeletons.push(newSkeleton);
  22940. };
  22941. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22942. this.particleSystems.push(newParticleSystem);
  22943. };
  22944. Scene.prototype.addAnimation = function (newAnimation) {
  22945. this.animations.push(newAnimation);
  22946. };
  22947. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22948. this.multiMaterials.push(newMultiMaterial);
  22949. };
  22950. Scene.prototype.addMaterial = function (newMaterial) {
  22951. this.materials.push(newMaterial);
  22952. };
  22953. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22954. this.morphTargetManagers.push(newMorphTargetManager);
  22955. };
  22956. Scene.prototype.addGeometry = function (newGeometrie) {
  22957. this._geometries.push(newGeometrie);
  22958. };
  22959. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22960. this.lensFlareSystems.push(newLensFlareSystem);
  22961. };
  22962. Scene.prototype.addActionManager = function (newActionManager) {
  22963. this._actionManagers.push(newActionManager);
  22964. };
  22965. /**
  22966. * Switch active camera
  22967. * @param {Camera} newCamera - new active camera
  22968. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22969. */
  22970. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22971. if (attachControl === void 0) { attachControl = true; }
  22972. var canvas = this._engine.getRenderingCanvas();
  22973. if (!canvas) {
  22974. return;
  22975. }
  22976. if (this.activeCamera) {
  22977. this.activeCamera.detachControl(canvas);
  22978. }
  22979. this.activeCamera = newCamera;
  22980. if (attachControl) {
  22981. newCamera.attachControl(canvas);
  22982. }
  22983. };
  22984. /**
  22985. * sets the active camera of the scene using its ID
  22986. * @param {string} id - the camera's ID
  22987. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22988. * @see activeCamera
  22989. */
  22990. Scene.prototype.setActiveCameraByID = function (id) {
  22991. var camera = this.getCameraByID(id);
  22992. if (camera) {
  22993. this.activeCamera = camera;
  22994. return camera;
  22995. }
  22996. return null;
  22997. };
  22998. /**
  22999. * sets the active camera of the scene using its name
  23000. * @param {string} name - the camera's name
  23001. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23002. * @see activeCamera
  23003. */
  23004. Scene.prototype.setActiveCameraByName = function (name) {
  23005. var camera = this.getCameraByName(name);
  23006. if (camera) {
  23007. this.activeCamera = camera;
  23008. return camera;
  23009. }
  23010. return null;
  23011. };
  23012. /**
  23013. * get an animation group using its name
  23014. * @param {string} the material's name
  23015. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23016. */
  23017. Scene.prototype.getAnimationGroupByName = function (name) {
  23018. for (var index = 0; index < this.animationGroups.length; index++) {
  23019. if (this.animationGroups[index].name === name) {
  23020. return this.animationGroups[index];
  23021. }
  23022. }
  23023. return null;
  23024. };
  23025. /**
  23026. * get a material using its id
  23027. * @param {string} the material's ID
  23028. * @return {BABYLON.Material|null} the material or null if none found.
  23029. */
  23030. Scene.prototype.getMaterialByID = function (id) {
  23031. for (var index = 0; index < this.materials.length; index++) {
  23032. if (this.materials[index].id === id) {
  23033. return this.materials[index];
  23034. }
  23035. }
  23036. return null;
  23037. };
  23038. /**
  23039. * get a material using its name
  23040. * @param {string} the material's name
  23041. * @return {BABYLON.Material|null} the material or null if none found.
  23042. */
  23043. Scene.prototype.getMaterialByName = function (name) {
  23044. for (var index = 0; index < this.materials.length; index++) {
  23045. if (this.materials[index].name === name) {
  23046. return this.materials[index];
  23047. }
  23048. }
  23049. return null;
  23050. };
  23051. Scene.prototype.getLensFlareSystemByName = function (name) {
  23052. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23053. if (this.lensFlareSystems[index].name === name) {
  23054. return this.lensFlareSystems[index];
  23055. }
  23056. }
  23057. return null;
  23058. };
  23059. Scene.prototype.getLensFlareSystemByID = function (id) {
  23060. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23061. if (this.lensFlareSystems[index].id === id) {
  23062. return this.lensFlareSystems[index];
  23063. }
  23064. }
  23065. return null;
  23066. };
  23067. Scene.prototype.getCameraByID = function (id) {
  23068. for (var index = 0; index < this.cameras.length; index++) {
  23069. if (this.cameras[index].id === id) {
  23070. return this.cameras[index];
  23071. }
  23072. }
  23073. return null;
  23074. };
  23075. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23076. for (var index = 0; index < this.cameras.length; index++) {
  23077. if (this.cameras[index].uniqueId === uniqueId) {
  23078. return this.cameras[index];
  23079. }
  23080. }
  23081. return null;
  23082. };
  23083. /**
  23084. * get a camera using its name
  23085. * @param {string} the camera's name
  23086. * @return {BABYLON.Camera|null} the camera or null if none found.
  23087. */
  23088. Scene.prototype.getCameraByName = function (name) {
  23089. for (var index = 0; index < this.cameras.length; index++) {
  23090. if (this.cameras[index].name === name) {
  23091. return this.cameras[index];
  23092. }
  23093. }
  23094. return null;
  23095. };
  23096. /**
  23097. * get a bone using its id
  23098. * @param {string} the bone's id
  23099. * @return {BABYLON.Bone|null} the bone or null if not found
  23100. */
  23101. Scene.prototype.getBoneByID = function (id) {
  23102. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23103. var skeleton = this.skeletons[skeletonIndex];
  23104. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23105. if (skeleton.bones[boneIndex].id === id) {
  23106. return skeleton.bones[boneIndex];
  23107. }
  23108. }
  23109. }
  23110. return null;
  23111. };
  23112. /**
  23113. * get a bone using its id
  23114. * @param {string} the bone's name
  23115. * @return {BABYLON.Bone|null} the bone or null if not found
  23116. */
  23117. Scene.prototype.getBoneByName = function (name) {
  23118. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23119. var skeleton = this.skeletons[skeletonIndex];
  23120. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23121. if (skeleton.bones[boneIndex].name === name) {
  23122. return skeleton.bones[boneIndex];
  23123. }
  23124. }
  23125. }
  23126. return null;
  23127. };
  23128. /**
  23129. * get a light node using its name
  23130. * @param {string} the light's name
  23131. * @return {BABYLON.Light|null} the light or null if none found.
  23132. */
  23133. Scene.prototype.getLightByName = function (name) {
  23134. for (var index = 0; index < this.lights.length; index++) {
  23135. if (this.lights[index].name === name) {
  23136. return this.lights[index];
  23137. }
  23138. }
  23139. return null;
  23140. };
  23141. /**
  23142. * get a light node using its ID
  23143. * @param {string} the light's id
  23144. * @return {BABYLON.Light|null} the light or null if none found.
  23145. */
  23146. Scene.prototype.getLightByID = function (id) {
  23147. for (var index = 0; index < this.lights.length; index++) {
  23148. if (this.lights[index].id === id) {
  23149. return this.lights[index];
  23150. }
  23151. }
  23152. return null;
  23153. };
  23154. /**
  23155. * get a light node using its scene-generated unique ID
  23156. * @param {number} the light's unique id
  23157. * @return {BABYLON.Light|null} the light or null if none found.
  23158. */
  23159. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23160. for (var index = 0; index < this.lights.length; index++) {
  23161. if (this.lights[index].uniqueId === uniqueId) {
  23162. return this.lights[index];
  23163. }
  23164. }
  23165. return null;
  23166. };
  23167. /**
  23168. * get a particle system by id
  23169. * @param id {number} the particle system id
  23170. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23171. */
  23172. Scene.prototype.getParticleSystemByID = function (id) {
  23173. for (var index = 0; index < this.particleSystems.length; index++) {
  23174. if (this.particleSystems[index].id === id) {
  23175. return this.particleSystems[index];
  23176. }
  23177. }
  23178. return null;
  23179. };
  23180. /**
  23181. * get a geometry using its ID
  23182. * @param {string} the geometry's id
  23183. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23184. */
  23185. Scene.prototype.getGeometryByID = function (id) {
  23186. for (var index = 0; index < this._geometries.length; index++) {
  23187. if (this._geometries[index].id === id) {
  23188. return this._geometries[index];
  23189. }
  23190. }
  23191. return null;
  23192. };
  23193. /**
  23194. * add a new geometry to this scene.
  23195. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23196. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23197. * @return {boolean} was the geometry added or not
  23198. */
  23199. Scene.prototype.pushGeometry = function (geometry, force) {
  23200. if (!force && this.getGeometryByID(geometry.id)) {
  23201. return false;
  23202. }
  23203. this._geometries.push(geometry);
  23204. //notify the collision coordinator
  23205. if (this.collisionCoordinator) {
  23206. this.collisionCoordinator.onGeometryAdded(geometry);
  23207. }
  23208. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23209. return true;
  23210. };
  23211. /**
  23212. * Removes an existing geometry
  23213. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23214. * @return {boolean} was the geometry removed or not
  23215. */
  23216. Scene.prototype.removeGeometry = function (geometry) {
  23217. var index = this._geometries.indexOf(geometry);
  23218. if (index > -1) {
  23219. this._geometries.splice(index, 1);
  23220. //notify the collision coordinator
  23221. if (this.collisionCoordinator) {
  23222. this.collisionCoordinator.onGeometryDeleted(geometry);
  23223. }
  23224. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23225. return true;
  23226. }
  23227. return false;
  23228. };
  23229. Scene.prototype.getGeometries = function () {
  23230. return this._geometries;
  23231. };
  23232. /**
  23233. * Get the first added mesh found of a given ID
  23234. * @param {string} id - the id to search for
  23235. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23236. */
  23237. Scene.prototype.getMeshByID = function (id) {
  23238. for (var index = 0; index < this.meshes.length; index++) {
  23239. if (this.meshes[index].id === id) {
  23240. return this.meshes[index];
  23241. }
  23242. }
  23243. return null;
  23244. };
  23245. Scene.prototype.getMeshesByID = function (id) {
  23246. return this.meshes.filter(function (m) {
  23247. return m.id === id;
  23248. });
  23249. };
  23250. /**
  23251. * Get the first added transform node found of a given ID
  23252. * @param {string} id - the id to search for
  23253. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23254. */
  23255. Scene.prototype.getTransformNodeByID = function (id) {
  23256. for (var index = 0; index < this.transformNodes.length; index++) {
  23257. if (this.transformNodes[index].id === id) {
  23258. return this.transformNodes[index];
  23259. }
  23260. }
  23261. return null;
  23262. };
  23263. Scene.prototype.getTransformNodesByID = function (id) {
  23264. return this.transformNodes.filter(function (m) {
  23265. return m.id === id;
  23266. });
  23267. };
  23268. /**
  23269. * Get a mesh with its auto-generated unique id
  23270. * @param {number} uniqueId - the unique id to search for
  23271. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23272. */
  23273. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23274. for (var index = 0; index < this.meshes.length; index++) {
  23275. if (this.meshes[index].uniqueId === uniqueId) {
  23276. return this.meshes[index];
  23277. }
  23278. }
  23279. return null;
  23280. };
  23281. /**
  23282. * Get a the last added mesh found of a given ID
  23283. * @param {string} id - the id to search for
  23284. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23285. */
  23286. Scene.prototype.getLastMeshByID = function (id) {
  23287. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23288. if (this.meshes[index].id === id) {
  23289. return this.meshes[index];
  23290. }
  23291. }
  23292. return null;
  23293. };
  23294. /**
  23295. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23296. * @param {string} id - the id to search for
  23297. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23298. */
  23299. Scene.prototype.getLastEntryByID = function (id) {
  23300. var index;
  23301. for (index = this.meshes.length - 1; index >= 0; index--) {
  23302. if (this.meshes[index].id === id) {
  23303. return this.meshes[index];
  23304. }
  23305. }
  23306. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23307. if (this.transformNodes[index].id === id) {
  23308. return this.transformNodes[index];
  23309. }
  23310. }
  23311. for (index = this.cameras.length - 1; index >= 0; index--) {
  23312. if (this.cameras[index].id === id) {
  23313. return this.cameras[index];
  23314. }
  23315. }
  23316. for (index = this.lights.length - 1; index >= 0; index--) {
  23317. if (this.lights[index].id === id) {
  23318. return this.lights[index];
  23319. }
  23320. }
  23321. return null;
  23322. };
  23323. Scene.prototype.getNodeByID = function (id) {
  23324. var mesh = this.getMeshByID(id);
  23325. if (mesh) {
  23326. return mesh;
  23327. }
  23328. var light = this.getLightByID(id);
  23329. if (light) {
  23330. return light;
  23331. }
  23332. var camera = this.getCameraByID(id);
  23333. if (camera) {
  23334. return camera;
  23335. }
  23336. var bone = this.getBoneByID(id);
  23337. return bone;
  23338. };
  23339. Scene.prototype.getNodeByName = function (name) {
  23340. var mesh = this.getMeshByName(name);
  23341. if (mesh) {
  23342. return mesh;
  23343. }
  23344. var light = this.getLightByName(name);
  23345. if (light) {
  23346. return light;
  23347. }
  23348. var camera = this.getCameraByName(name);
  23349. if (camera) {
  23350. return camera;
  23351. }
  23352. var bone = this.getBoneByName(name);
  23353. return bone;
  23354. };
  23355. Scene.prototype.getMeshByName = function (name) {
  23356. for (var index = 0; index < this.meshes.length; index++) {
  23357. if (this.meshes[index].name === name) {
  23358. return this.meshes[index];
  23359. }
  23360. }
  23361. return null;
  23362. };
  23363. Scene.prototype.getTransformNodeByName = function (name) {
  23364. for (var index = 0; index < this.transformNodes.length; index++) {
  23365. if (this.transformNodes[index].name === name) {
  23366. return this.transformNodes[index];
  23367. }
  23368. }
  23369. return null;
  23370. };
  23371. Scene.prototype.getSoundByName = function (name) {
  23372. var index;
  23373. if (BABYLON.AudioEngine) {
  23374. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23375. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23376. return this.mainSoundTrack.soundCollection[index];
  23377. }
  23378. }
  23379. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23380. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23381. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23382. return this.soundTracks[sdIndex].soundCollection[index];
  23383. }
  23384. }
  23385. }
  23386. }
  23387. return null;
  23388. };
  23389. Scene.prototype.getLastSkeletonByID = function (id) {
  23390. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23391. if (this.skeletons[index].id === id) {
  23392. return this.skeletons[index];
  23393. }
  23394. }
  23395. return null;
  23396. };
  23397. Scene.prototype.getSkeletonById = function (id) {
  23398. for (var index = 0; index < this.skeletons.length; index++) {
  23399. if (this.skeletons[index].id === id) {
  23400. return this.skeletons[index];
  23401. }
  23402. }
  23403. return null;
  23404. };
  23405. Scene.prototype.getSkeletonByName = function (name) {
  23406. for (var index = 0; index < this.skeletons.length; index++) {
  23407. if (this.skeletons[index].name === name) {
  23408. return this.skeletons[index];
  23409. }
  23410. }
  23411. return null;
  23412. };
  23413. Scene.prototype.getMorphTargetManagerById = function (id) {
  23414. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23415. if (this.morphTargetManagers[index].uniqueId === id) {
  23416. return this.morphTargetManagers[index];
  23417. }
  23418. }
  23419. return null;
  23420. };
  23421. Scene.prototype.isActiveMesh = function (mesh) {
  23422. return (this._activeMeshes.indexOf(mesh) !== -1);
  23423. };
  23424. /**
  23425. * Return a the first highlight layer of the scene with a given name.
  23426. * @param name The name of the highlight layer to look for.
  23427. * @return The highlight layer if found otherwise null.
  23428. */
  23429. Scene.prototype.getHighlightLayerByName = function (name) {
  23430. for (var index = 0; index < this.effectLayers.length; index++) {
  23431. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23432. return this.effectLayers[index];
  23433. }
  23434. }
  23435. return null;
  23436. };
  23437. /**
  23438. * Return a the first highlight layer of the scene with a given name.
  23439. * @param name The name of the highlight layer to look for.
  23440. * @return The highlight layer if found otherwise null.
  23441. */
  23442. Scene.prototype.getGlowLayerByName = function (name) {
  23443. for (var index = 0; index < this.effectLayers.length; index++) {
  23444. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23445. return this.effectLayers[index];
  23446. }
  23447. }
  23448. return null;
  23449. };
  23450. Object.defineProperty(Scene.prototype, "uid", {
  23451. /**
  23452. * Return a unique id as a string which can serve as an identifier for the scene
  23453. */
  23454. get: function () {
  23455. if (!this._uid) {
  23456. this._uid = BABYLON.Tools.RandomId();
  23457. }
  23458. return this._uid;
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. /**
  23464. * Add an externaly attached data from its key.
  23465. * This method call will fail and return false, if such key already exists.
  23466. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23467. * @param key the unique key that identifies the data
  23468. * @param data the data object to associate to the key for this Engine instance
  23469. * @return true if no such key were already present and the data was added successfully, false otherwise
  23470. */
  23471. Scene.prototype.addExternalData = function (key, data) {
  23472. if (!this._externalData) {
  23473. this._externalData = new BABYLON.StringDictionary();
  23474. }
  23475. return this._externalData.add(key, data);
  23476. };
  23477. /**
  23478. * Get an externaly attached data from its key
  23479. * @param key the unique key that identifies the data
  23480. * @return the associated data, if present (can be null), or undefined if not present
  23481. */
  23482. Scene.prototype.getExternalData = function (key) {
  23483. if (!this._externalData) {
  23484. return null;
  23485. }
  23486. return this._externalData.get(key);
  23487. };
  23488. /**
  23489. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23490. * @param key the unique key that identifies the data
  23491. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23492. * @return the associated data, can be null if the factory returned null.
  23493. */
  23494. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23495. if (!this._externalData) {
  23496. this._externalData = new BABYLON.StringDictionary();
  23497. }
  23498. return this._externalData.getOrAddWithFactory(key, factory);
  23499. };
  23500. /**
  23501. * Remove an externaly attached data from the Engine instance
  23502. * @param key the unique key that identifies the data
  23503. * @return true if the data was successfully removed, false if it doesn't exist
  23504. */
  23505. Scene.prototype.removeExternalData = function (key) {
  23506. return this._externalData.remove(key);
  23507. };
  23508. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23509. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23510. if (mesh.showSubMeshesBoundingBox) {
  23511. var boundingInfo = subMesh.getBoundingInfo();
  23512. if (boundingInfo !== null && boundingInfo !== undefined) {
  23513. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23514. }
  23515. }
  23516. var material = subMesh.getMaterial();
  23517. if (material !== null && material !== undefined) {
  23518. // Render targets
  23519. if (material.getRenderTargetTextures !== undefined) {
  23520. if (this._processedMaterials.indexOf(material) === -1) {
  23521. this._processedMaterials.push(material);
  23522. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23523. }
  23524. }
  23525. // Dispatch
  23526. this._activeIndices.addCount(subMesh.indexCount, false);
  23527. this._renderingManager.dispatch(subMesh, mesh, material);
  23528. }
  23529. }
  23530. };
  23531. Scene.prototype._isInIntermediateRendering = function () {
  23532. return this._intermediateRendering;
  23533. };
  23534. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23535. this._activeMeshCandidateProvider = provider;
  23536. };
  23537. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23538. return this._activeMeshCandidateProvider;
  23539. };
  23540. /**
  23541. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23542. */
  23543. Scene.prototype.freezeActiveMeshes = function () {
  23544. this._evaluateActiveMeshes();
  23545. this._activeMeshesFrozen = true;
  23546. return this;
  23547. };
  23548. /**
  23549. * Use this function to restart evaluating active meshes on every frame
  23550. */
  23551. Scene.prototype.unfreezeActiveMeshes = function () {
  23552. this._activeMeshesFrozen = false;
  23553. return this;
  23554. };
  23555. Scene.prototype._evaluateActiveMeshes = function () {
  23556. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23557. return;
  23558. }
  23559. if (!this.activeCamera) {
  23560. return;
  23561. }
  23562. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23563. this.activeCamera._activeMeshes.reset();
  23564. this._activeMeshes.reset();
  23565. this._renderingManager.reset();
  23566. this._processedMaterials.reset();
  23567. this._activeParticleSystems.reset();
  23568. this._activeSkeletons.reset();
  23569. this._softwareSkinnedMeshes.reset();
  23570. if (this._boundingBoxRenderer) {
  23571. this._boundingBoxRenderer.reset();
  23572. }
  23573. // Meshes
  23574. var meshes;
  23575. var len;
  23576. var checkIsEnabled = true;
  23577. // Determine mesh candidates
  23578. if (this._activeMeshCandidateProvider !== undefined) {
  23579. // Use _activeMeshCandidateProvider
  23580. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23581. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23582. if (meshes !== undefined) {
  23583. len = meshes.length;
  23584. }
  23585. else {
  23586. len = 0;
  23587. }
  23588. }
  23589. else if (this._selectionOctree !== undefined) {
  23590. // Octree
  23591. var selection = this._selectionOctree.select(this._frustumPlanes);
  23592. meshes = selection.data;
  23593. len = selection.length;
  23594. }
  23595. else {
  23596. // Full scene traversal
  23597. len = this.meshes.length;
  23598. meshes = this.meshes;
  23599. }
  23600. // Check each mesh
  23601. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23602. mesh = meshes[meshIndex];
  23603. if (mesh.isBlocked) {
  23604. continue;
  23605. }
  23606. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23607. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23608. continue;
  23609. }
  23610. mesh.computeWorldMatrix();
  23611. // Intersections
  23612. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23613. this._meshesForIntersections.pushNoDuplicate(mesh);
  23614. }
  23615. // Switch to current LOD
  23616. meshLOD = mesh.getLOD(this.activeCamera);
  23617. if (meshLOD === undefined || meshLOD === null) {
  23618. continue;
  23619. }
  23620. mesh._preActivate();
  23621. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23622. this._activeMeshes.push(mesh);
  23623. this.activeCamera._activeMeshes.push(mesh);
  23624. mesh._activate(this._renderId);
  23625. if (meshLOD !== mesh) {
  23626. meshLOD._activate(this._renderId);
  23627. }
  23628. this._activeMesh(mesh, meshLOD);
  23629. }
  23630. }
  23631. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23632. // Particle systems
  23633. if (this.particlesEnabled) {
  23634. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23635. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23636. var particleSystem = this.particleSystems[particleIndex];
  23637. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23638. continue;
  23639. }
  23640. var emitter = particleSystem.emitter;
  23641. if (!emitter.position || emitter.isEnabled()) {
  23642. this._activeParticleSystems.push(particleSystem);
  23643. particleSystem.animate();
  23644. this._renderingManager.dispatchParticles(particleSystem);
  23645. }
  23646. }
  23647. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23648. }
  23649. };
  23650. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23651. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23652. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23653. mesh.skeleton.prepare();
  23654. }
  23655. if (!mesh.computeBonesUsingShaders) {
  23656. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23657. }
  23658. }
  23659. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23660. var boundingInfo = sourceMesh.getBoundingInfo();
  23661. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23662. }
  23663. if (mesh !== undefined && mesh !== null
  23664. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23665. // Submeshes Octrees
  23666. var len;
  23667. var subMeshes;
  23668. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23669. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23670. len = intersections.length;
  23671. subMeshes = intersections.data;
  23672. }
  23673. else {
  23674. subMeshes = mesh.subMeshes;
  23675. len = subMeshes.length;
  23676. }
  23677. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23678. subMesh = subMeshes[subIndex];
  23679. this._evaluateSubMesh(subMesh, mesh);
  23680. }
  23681. }
  23682. };
  23683. Scene.prototype.updateTransformMatrix = function (force) {
  23684. if (!this.activeCamera) {
  23685. return;
  23686. }
  23687. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23688. };
  23689. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23690. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23691. };
  23692. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23693. if (camera && camera._skipRendering) {
  23694. return;
  23695. }
  23696. var engine = this._engine;
  23697. this.activeCamera = camera;
  23698. if (!this.activeCamera)
  23699. throw new Error("Active camera not set");
  23700. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23701. // Viewport
  23702. engine.setViewport(this.activeCamera.viewport);
  23703. // Camera
  23704. this.resetCachedMaterial();
  23705. this._renderId++;
  23706. this.activeCamera.update();
  23707. this.updateTransformMatrix();
  23708. if (camera._alternateCamera) {
  23709. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23710. this._alternateRendering = true;
  23711. }
  23712. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23713. // Meshes
  23714. this._evaluateActiveMeshes();
  23715. // Software skinning
  23716. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23717. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23718. mesh.applySkeleton(mesh.skeleton);
  23719. }
  23720. // Render targets
  23721. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23722. var needsRestoreFrameBuffer = false;
  23723. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23724. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23725. }
  23726. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23727. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23728. }
  23729. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23730. this._intermediateRendering = true;
  23731. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23732. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23733. var renderTarget = this._renderTargets.data[renderIndex];
  23734. if (renderTarget._shouldRender()) {
  23735. this._renderId++;
  23736. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23737. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23738. }
  23739. }
  23740. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23741. this._intermediateRendering = false;
  23742. this._renderId++;
  23743. needsRestoreFrameBuffer = true; // Restore back buffer
  23744. }
  23745. // Render EffecttLayer Texture
  23746. var stencilState = this._engine.getStencilBuffer();
  23747. var renderEffects = false;
  23748. var needStencil = false;
  23749. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23750. this._intermediateRendering = true;
  23751. for (var i = 0; i < this.effectLayers.length; i++) {
  23752. var effectLayer = this.effectLayers[i];
  23753. if (effectLayer.shouldRender() &&
  23754. (!effectLayer.camera ||
  23755. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23756. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23757. renderEffects = true;
  23758. needStencil = needStencil || effectLayer.needStencil();
  23759. var renderTarget = effectLayer._mainTexture;
  23760. if (renderTarget._shouldRender()) {
  23761. this._renderId++;
  23762. renderTarget.render(false, false);
  23763. needsRestoreFrameBuffer = true;
  23764. }
  23765. }
  23766. }
  23767. this._intermediateRendering = false;
  23768. this._renderId++;
  23769. }
  23770. if (needsRestoreFrameBuffer) {
  23771. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23772. }
  23773. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23774. // Prepare Frame
  23775. this.postProcessManager._prepareFrame();
  23776. // Backgrounds
  23777. var layerIndex;
  23778. var layer;
  23779. if (this.layers.length) {
  23780. engine.setDepthBuffer(false);
  23781. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23782. layer = this.layers[layerIndex];
  23783. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23784. layer.render();
  23785. }
  23786. }
  23787. engine.setDepthBuffer(true);
  23788. }
  23789. // Activate effect Layer stencil
  23790. if (needStencil) {
  23791. this._engine.setStencilBuffer(true);
  23792. }
  23793. // Render
  23794. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23795. this._renderingManager.render(null, null, true, true);
  23796. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23797. // Restore effect Layer stencil
  23798. if (needStencil) {
  23799. this._engine.setStencilBuffer(stencilState);
  23800. }
  23801. // Bounding boxes
  23802. if (this._boundingBoxRenderer) {
  23803. this._boundingBoxRenderer.render();
  23804. }
  23805. // Lens flares
  23806. if (this.lensFlaresEnabled) {
  23807. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23808. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23809. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23810. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23811. lensFlareSystem.render();
  23812. }
  23813. }
  23814. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23815. }
  23816. // Foregrounds
  23817. if (this.layers.length) {
  23818. engine.setDepthBuffer(false);
  23819. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23820. layer = this.layers[layerIndex];
  23821. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23822. layer.render();
  23823. }
  23824. }
  23825. engine.setDepthBuffer(true);
  23826. }
  23827. // Effect Layer
  23828. if (renderEffects) {
  23829. engine.setDepthBuffer(false);
  23830. for (var i = 0; i < this.effectLayers.length; i++) {
  23831. if (this.effectLayers[i].shouldRender()) {
  23832. this.effectLayers[i].render();
  23833. }
  23834. }
  23835. engine.setDepthBuffer(true);
  23836. }
  23837. // Finalize frame
  23838. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23839. // Reset some special arrays
  23840. this._renderTargets.reset();
  23841. this._alternateRendering = false;
  23842. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23843. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23844. };
  23845. Scene.prototype._processSubCameras = function (camera) {
  23846. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23847. this._renderForCamera(camera);
  23848. return;
  23849. }
  23850. // Update camera
  23851. if (this.activeCamera) {
  23852. this.activeCamera.update();
  23853. }
  23854. // rig cameras
  23855. for (var index = 0; index < camera._rigCameras.length; index++) {
  23856. this._renderForCamera(camera._rigCameras[index], camera);
  23857. }
  23858. this.activeCamera = camera;
  23859. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23860. };
  23861. Scene.prototype._checkIntersections = function () {
  23862. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23863. var sourceMesh = this._meshesForIntersections.data[index];
  23864. if (!sourceMesh.actionManager) {
  23865. continue;
  23866. }
  23867. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23868. var action = sourceMesh.actionManager.actions[actionIndex];
  23869. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23870. var parameters = action.getTriggerParameter();
  23871. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23872. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23873. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23874. if (areIntersecting && currentIntersectionInProgress === -1) {
  23875. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23876. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23877. sourceMesh._intersectionsInProgress.push(otherMesh);
  23878. }
  23879. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23880. sourceMesh._intersectionsInProgress.push(otherMesh);
  23881. }
  23882. }
  23883. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23884. //They intersected, and now they don't.
  23885. //is this trigger an exit trigger? execute an event.
  23886. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23887. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23888. }
  23889. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23890. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23891. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23892. }
  23893. }
  23894. }
  23895. }
  23896. }
  23897. };
  23898. Scene.prototype.render = function () {
  23899. if (this.isDisposed) {
  23900. return;
  23901. }
  23902. this._activeParticles.fetchNewFrame();
  23903. this._totalVertices.fetchNewFrame();
  23904. this._activeIndices.fetchNewFrame();
  23905. this._activeBones.fetchNewFrame();
  23906. this._meshesForIntersections.reset();
  23907. this.resetCachedMaterial();
  23908. this.onBeforeAnimationsObservable.notifyObservers(this);
  23909. // Actions
  23910. if (this.actionManager) {
  23911. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23912. }
  23913. //Simplification Queue
  23914. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23915. this.simplificationQueue.executeNext();
  23916. }
  23917. if (this._engine.isDeterministicLockStep()) {
  23918. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23919. var defaultFPS = (60.0 / 1000.0);
  23920. var defaultFrameTime = 1000 / 60; // frame time in MS
  23921. if (this._physicsEngine) {
  23922. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23923. }
  23924. var stepsTaken = 0;
  23925. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23926. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23927. internalSteps = Math.min(internalSteps, maxSubSteps);
  23928. do {
  23929. this.onBeforeStepObservable.notifyObservers(this);
  23930. // Animations
  23931. this._animationRatio = defaultFrameTime * defaultFPS;
  23932. this._animate();
  23933. this.onAfterAnimationsObservable.notifyObservers(this);
  23934. // Physics
  23935. if (this._physicsEngine) {
  23936. this.onBeforePhysicsObservable.notifyObservers(this);
  23937. this._physicsEngine._step(defaultFrameTime / 1000);
  23938. this.onAfterPhysicsObservable.notifyObservers(this);
  23939. }
  23940. this.onAfterStepObservable.notifyObservers(this);
  23941. this._currentStepId++;
  23942. stepsTaken++;
  23943. deltaTime -= defaultFrameTime;
  23944. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23945. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23946. }
  23947. else {
  23948. // Animations
  23949. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23950. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23951. this._animate();
  23952. this.onAfterAnimationsObservable.notifyObservers(this);
  23953. // Physics
  23954. if (this._physicsEngine) {
  23955. this.onBeforePhysicsObservable.notifyObservers(this);
  23956. this._physicsEngine._step(deltaTime / 1000.0);
  23957. this.onAfterPhysicsObservable.notifyObservers(this);
  23958. }
  23959. }
  23960. // update gamepad manager
  23961. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23962. this._gamepadManager._checkGamepadsStatus();
  23963. }
  23964. // Before render
  23965. this.onBeforeRenderObservable.notifyObservers(this);
  23966. // Customs render targets
  23967. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23968. var engine = this.getEngine();
  23969. var currentActiveCamera = this.activeCamera;
  23970. if (this.renderTargetsEnabled) {
  23971. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23972. this._intermediateRendering = true;
  23973. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23974. var renderTarget = this.customRenderTargets[customIndex];
  23975. if (renderTarget._shouldRender()) {
  23976. this._renderId++;
  23977. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23978. if (!this.activeCamera)
  23979. throw new Error("Active camera not set");
  23980. // Viewport
  23981. engine.setViewport(this.activeCamera.viewport);
  23982. // Camera
  23983. this.updateTransformMatrix();
  23984. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23985. }
  23986. }
  23987. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23988. this._intermediateRendering = false;
  23989. this._renderId++;
  23990. }
  23991. // Restore back buffer
  23992. if (this.customRenderTargets.length > 0) {
  23993. engine.restoreDefaultFramebuffer();
  23994. }
  23995. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23996. this.activeCamera = currentActiveCamera;
  23997. // Procedural textures
  23998. if (this.proceduralTexturesEnabled) {
  23999. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24000. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24001. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24002. if (proceduralTexture._shouldRender()) {
  24003. proceduralTexture.render();
  24004. }
  24005. }
  24006. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24007. }
  24008. // Clear
  24009. if (this.autoClearDepthAndStencil || this.autoClear) {
  24010. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24011. }
  24012. // Shadows
  24013. if (this.shadowsEnabled) {
  24014. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24015. var light = this.lights[lightIndex];
  24016. var shadowGenerator = light.getShadowGenerator();
  24017. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24018. var shadowMap = (shadowGenerator.getShadowMap());
  24019. if (this.textures.indexOf(shadowMap) !== -1) {
  24020. this._renderTargets.push(shadowMap);
  24021. }
  24022. }
  24023. }
  24024. }
  24025. // Depth renderer
  24026. if (this._depthRenderer) {
  24027. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24028. }
  24029. // Geometry renderer
  24030. if (this._geometryBufferRenderer) {
  24031. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24032. }
  24033. // RenderPipeline
  24034. if (this._postProcessRenderPipelineManager) {
  24035. this._postProcessRenderPipelineManager.update();
  24036. }
  24037. // Multi-cameras?
  24038. if (this.activeCameras.length > 0) {
  24039. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24040. if (cameraIndex > 0) {
  24041. this._engine.clear(null, false, true, true);
  24042. }
  24043. this._processSubCameras(this.activeCameras[cameraIndex]);
  24044. }
  24045. }
  24046. else {
  24047. if (!this.activeCamera) {
  24048. throw new Error("No camera defined");
  24049. }
  24050. this._processSubCameras(this.activeCamera);
  24051. }
  24052. // Intersection checks
  24053. this._checkIntersections();
  24054. // Update the audio listener attached to the camera
  24055. if (BABYLON.AudioEngine) {
  24056. this._updateAudioParameters();
  24057. }
  24058. // After render
  24059. if (this.afterRender) {
  24060. this.afterRender();
  24061. }
  24062. this.onAfterRenderObservable.notifyObservers(this);
  24063. // Cleaning
  24064. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24065. var data = this._toBeDisposed.data[index];
  24066. if (data) {
  24067. data.dispose();
  24068. }
  24069. this._toBeDisposed[index] = null;
  24070. }
  24071. this._toBeDisposed.reset();
  24072. if (this.dumpNextRenderTargets) {
  24073. this.dumpNextRenderTargets = false;
  24074. }
  24075. this._activeBones.addCount(0, true);
  24076. this._activeIndices.addCount(0, true);
  24077. this._activeParticles.addCount(0, true);
  24078. };
  24079. Scene.prototype._updateAudioParameters = function () {
  24080. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24081. return;
  24082. }
  24083. var listeningCamera;
  24084. var audioEngine = BABYLON.Engine.audioEngine;
  24085. if (this.activeCameras.length > 0) {
  24086. listeningCamera = this.activeCameras[0];
  24087. }
  24088. else {
  24089. listeningCamera = this.activeCamera;
  24090. }
  24091. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24092. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24093. // for VR cameras
  24094. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24095. listeningCamera = listeningCamera.rigCameras[0];
  24096. }
  24097. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24098. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24099. cameraDirection.normalize();
  24100. // To avoid some errors on GearVR
  24101. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24102. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24103. }
  24104. var i;
  24105. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24106. var sound = this.mainSoundTrack.soundCollection[i];
  24107. if (sound.useCustomAttenuation) {
  24108. sound.updateDistanceFromListener();
  24109. }
  24110. }
  24111. for (i = 0; i < this.soundTracks.length; i++) {
  24112. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24113. sound = this.soundTracks[i].soundCollection[j];
  24114. if (sound.useCustomAttenuation) {
  24115. sound.updateDistanceFromListener();
  24116. }
  24117. }
  24118. }
  24119. }
  24120. };
  24121. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24122. // Audio
  24123. get: function () {
  24124. return this._audioEnabled;
  24125. },
  24126. set: function (value) {
  24127. this._audioEnabled = value;
  24128. if (BABYLON.AudioEngine) {
  24129. if (this._audioEnabled) {
  24130. this._enableAudio();
  24131. }
  24132. else {
  24133. this._disableAudio();
  24134. }
  24135. }
  24136. },
  24137. enumerable: true,
  24138. configurable: true
  24139. });
  24140. Scene.prototype._disableAudio = function () {
  24141. var i;
  24142. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24143. this.mainSoundTrack.soundCollection[i].pause();
  24144. }
  24145. for (i = 0; i < this.soundTracks.length; i++) {
  24146. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24147. this.soundTracks[i].soundCollection[j].pause();
  24148. }
  24149. }
  24150. };
  24151. Scene.prototype._enableAudio = function () {
  24152. var i;
  24153. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24154. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24155. this.mainSoundTrack.soundCollection[i].play();
  24156. }
  24157. }
  24158. for (i = 0; i < this.soundTracks.length; i++) {
  24159. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24160. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24161. this.soundTracks[i].soundCollection[j].play();
  24162. }
  24163. }
  24164. }
  24165. };
  24166. Object.defineProperty(Scene.prototype, "headphone", {
  24167. get: function () {
  24168. return this._headphone;
  24169. },
  24170. set: function (value) {
  24171. this._headphone = value;
  24172. if (BABYLON.AudioEngine) {
  24173. if (this._headphone) {
  24174. this._switchAudioModeForHeadphones();
  24175. }
  24176. else {
  24177. this._switchAudioModeForNormalSpeakers();
  24178. }
  24179. }
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. Scene.prototype._switchAudioModeForHeadphones = function () {
  24185. this.mainSoundTrack.switchPanningModelToHRTF();
  24186. for (var i = 0; i < this.soundTracks.length; i++) {
  24187. this.soundTracks[i].switchPanningModelToHRTF();
  24188. }
  24189. };
  24190. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24191. this.mainSoundTrack.switchPanningModelToEqualPower();
  24192. for (var i = 0; i < this.soundTracks.length; i++) {
  24193. this.soundTracks[i].switchPanningModelToEqualPower();
  24194. }
  24195. };
  24196. Scene.prototype.enableDepthRenderer = function () {
  24197. if (this._depthRenderer) {
  24198. return this._depthRenderer;
  24199. }
  24200. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24201. return this._depthRenderer;
  24202. };
  24203. Scene.prototype.disableDepthRenderer = function () {
  24204. if (!this._depthRenderer) {
  24205. return;
  24206. }
  24207. this._depthRenderer.dispose();
  24208. this._depthRenderer = null;
  24209. };
  24210. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24211. if (ratio === void 0) { ratio = 1; }
  24212. if (this._geometryBufferRenderer) {
  24213. return this._geometryBufferRenderer;
  24214. }
  24215. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24216. if (!this._geometryBufferRenderer.isSupported) {
  24217. this._geometryBufferRenderer = null;
  24218. }
  24219. return this._geometryBufferRenderer;
  24220. };
  24221. Scene.prototype.disableGeometryBufferRenderer = function () {
  24222. if (!this._geometryBufferRenderer) {
  24223. return;
  24224. }
  24225. this._geometryBufferRenderer.dispose();
  24226. this._geometryBufferRenderer = null;
  24227. };
  24228. Scene.prototype.freezeMaterials = function () {
  24229. for (var i = 0; i < this.materials.length; i++) {
  24230. this.materials[i].freeze();
  24231. }
  24232. };
  24233. Scene.prototype.unfreezeMaterials = function () {
  24234. for (var i = 0; i < this.materials.length; i++) {
  24235. this.materials[i].unfreeze();
  24236. }
  24237. };
  24238. Scene.prototype.dispose = function () {
  24239. this.beforeRender = null;
  24240. this.afterRender = null;
  24241. this.skeletons = [];
  24242. this.morphTargetManagers = [];
  24243. this.importedMeshesFiles = new Array();
  24244. this.stopAllAnimations();
  24245. this.resetCachedMaterial();
  24246. if (this._depthRenderer) {
  24247. this._depthRenderer.dispose();
  24248. }
  24249. if (this._gamepadManager) {
  24250. this._gamepadManager.dispose();
  24251. this._gamepadManager = null;
  24252. }
  24253. // Smart arrays
  24254. if (this.activeCamera) {
  24255. this.activeCamera._activeMeshes.dispose();
  24256. this.activeCamera = null;
  24257. }
  24258. this._activeMeshes.dispose();
  24259. this._renderingManager.dispose();
  24260. this._processedMaterials.dispose();
  24261. this._activeParticleSystems.dispose();
  24262. this._activeSkeletons.dispose();
  24263. this._softwareSkinnedMeshes.dispose();
  24264. this._renderTargets.dispose();
  24265. if (this._boundingBoxRenderer) {
  24266. this._boundingBoxRenderer.dispose();
  24267. }
  24268. this._meshesForIntersections.dispose();
  24269. this._toBeDisposed.dispose();
  24270. // Abort active requests
  24271. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24272. var request = _a[_i];
  24273. request.abort();
  24274. }
  24275. // Debug layer
  24276. if (this._debugLayer) {
  24277. this._debugLayer.hide();
  24278. }
  24279. // Events
  24280. this.onDisposeObservable.notifyObservers(this);
  24281. this.onDisposeObservable.clear();
  24282. this.onBeforeRenderObservable.clear();
  24283. this.onAfterRenderObservable.clear();
  24284. this.OnBeforeRenderTargetsRenderObservable.clear();
  24285. this.OnAfterRenderTargetsRenderObservable.clear();
  24286. this.onAfterStepObservable.clear();
  24287. this.onBeforeStepObservable.clear();
  24288. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24289. this.onAfterActiveMeshesEvaluationObservable.clear();
  24290. this.onBeforeParticlesRenderingObservable.clear();
  24291. this.onAfterParticlesRenderingObservable.clear();
  24292. this.onBeforeSpritesRenderingObservable.clear();
  24293. this.onAfterSpritesRenderingObservable.clear();
  24294. this.onBeforeDrawPhaseObservable.clear();
  24295. this.onAfterDrawPhaseObservable.clear();
  24296. this.onBeforePhysicsObservable.clear();
  24297. this.onAfterPhysicsObservable.clear();
  24298. this.onBeforeAnimationsObservable.clear();
  24299. this.onAfterAnimationsObservable.clear();
  24300. this.onDataLoadedObservable.clear();
  24301. this.detachControl();
  24302. // Release sounds & sounds tracks
  24303. if (BABYLON.AudioEngine) {
  24304. this.disposeSounds();
  24305. }
  24306. // VR Helper
  24307. if (this.VRHelper) {
  24308. this.VRHelper.dispose();
  24309. }
  24310. // Detach cameras
  24311. var canvas = this._engine.getRenderingCanvas();
  24312. if (canvas) {
  24313. var index;
  24314. for (index = 0; index < this.cameras.length; index++) {
  24315. this.cameras[index].detachControl(canvas);
  24316. }
  24317. }
  24318. // Release animation groups
  24319. while (this.animationGroups.length) {
  24320. this.animationGroups[0].dispose();
  24321. }
  24322. // Release lights
  24323. while (this.lights.length) {
  24324. this.lights[0].dispose();
  24325. }
  24326. // Release meshes
  24327. while (this.meshes.length) {
  24328. this.meshes[0].dispose(true);
  24329. }
  24330. while (this.transformNodes.length) {
  24331. this.removeTransformNode(this.transformNodes[0]);
  24332. }
  24333. // Release cameras
  24334. while (this.cameras.length) {
  24335. this.cameras[0].dispose();
  24336. }
  24337. // Release materials
  24338. if (this.defaultMaterial) {
  24339. this.defaultMaterial.dispose();
  24340. }
  24341. while (this.multiMaterials.length) {
  24342. this.multiMaterials[0].dispose();
  24343. }
  24344. while (this.materials.length) {
  24345. this.materials[0].dispose();
  24346. }
  24347. // Release particles
  24348. while (this.particleSystems.length) {
  24349. this.particleSystems[0].dispose();
  24350. }
  24351. // Release sprites
  24352. while (this.spriteManagers.length) {
  24353. this.spriteManagers[0].dispose();
  24354. }
  24355. // Release postProcesses
  24356. while (this.postProcesses.length) {
  24357. this.postProcesses[0].dispose();
  24358. }
  24359. // Release layers
  24360. while (this.layers.length) {
  24361. this.layers[0].dispose();
  24362. }
  24363. while (this.effectLayers.length) {
  24364. this.effectLayers[0].dispose();
  24365. }
  24366. // Release textures
  24367. while (this.textures.length) {
  24368. this.textures[0].dispose();
  24369. }
  24370. // Release UBO
  24371. this._sceneUbo.dispose();
  24372. if (this._alternateSceneUbo) {
  24373. this._alternateSceneUbo.dispose();
  24374. }
  24375. // Post-processes
  24376. this.postProcessManager.dispose();
  24377. if (this._postProcessRenderPipelineManager) {
  24378. this._postProcessRenderPipelineManager.dispose();
  24379. }
  24380. // Physics
  24381. if (this._physicsEngine) {
  24382. this.disablePhysicsEngine();
  24383. }
  24384. // Remove from engine
  24385. index = this._engine.scenes.indexOf(this);
  24386. if (index > -1) {
  24387. this._engine.scenes.splice(index, 1);
  24388. }
  24389. this._engine.wipeCaches(true);
  24390. this._isDisposed = true;
  24391. };
  24392. Object.defineProperty(Scene.prototype, "isDisposed", {
  24393. get: function () {
  24394. return this._isDisposed;
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. // Release sounds & sounds tracks
  24400. Scene.prototype.disposeSounds = function () {
  24401. if (!this._mainSoundTrack) {
  24402. return;
  24403. }
  24404. this.mainSoundTrack.dispose();
  24405. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24406. this.soundTracks[scIndex].dispose();
  24407. }
  24408. };
  24409. // Octrees
  24410. Scene.prototype.getWorldExtends = function () {
  24411. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24412. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24413. for (var index = 0; index < this.meshes.length; index++) {
  24414. var mesh = this.meshes[index];
  24415. mesh.computeWorldMatrix(true);
  24416. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24417. continue;
  24418. }
  24419. var boundingInfo = mesh.getBoundingInfo();
  24420. var minBox = boundingInfo.boundingBox.minimumWorld;
  24421. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24422. BABYLON.Tools.CheckExtends(minBox, min, max);
  24423. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24424. }
  24425. return {
  24426. min: min,
  24427. max: max
  24428. };
  24429. };
  24430. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24431. if (maxCapacity === void 0) { maxCapacity = 64; }
  24432. if (maxDepth === void 0) { maxDepth = 2; }
  24433. if (!this._selectionOctree) {
  24434. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24435. }
  24436. var worldExtends = this.getWorldExtends();
  24437. // Update octree
  24438. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24439. return this._selectionOctree;
  24440. };
  24441. // Picking
  24442. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24443. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24444. var result = BABYLON.Ray.Zero();
  24445. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24446. return result;
  24447. };
  24448. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24449. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24450. var engine = this._engine;
  24451. if (!camera) {
  24452. if (!this.activeCamera)
  24453. throw new Error("Active camera not set");
  24454. camera = this.activeCamera;
  24455. }
  24456. var cameraViewport = camera.viewport;
  24457. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24458. // Moving coordinates to local viewport world
  24459. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24460. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24461. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24462. return this;
  24463. };
  24464. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24465. var result = BABYLON.Ray.Zero();
  24466. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24467. return result;
  24468. };
  24469. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24470. if (!BABYLON.PickingInfo) {
  24471. return this;
  24472. }
  24473. var engine = this._engine;
  24474. if (!camera) {
  24475. if (!this.activeCamera)
  24476. throw new Error("Active camera not set");
  24477. camera = this.activeCamera;
  24478. }
  24479. var cameraViewport = camera.viewport;
  24480. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24481. var identity = BABYLON.Matrix.Identity();
  24482. // Moving coordinates to local viewport world
  24483. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24484. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24485. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24486. return this;
  24487. };
  24488. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24489. if (!BABYLON.PickingInfo) {
  24490. return null;
  24491. }
  24492. var pickingInfo = null;
  24493. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24494. var mesh = this.meshes[meshIndex];
  24495. if (predicate) {
  24496. if (!predicate(mesh)) {
  24497. continue;
  24498. }
  24499. }
  24500. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24501. continue;
  24502. }
  24503. var world = mesh.getWorldMatrix();
  24504. var ray = rayFunction(world);
  24505. var result = mesh.intersects(ray, fastCheck);
  24506. if (!result || !result.hit)
  24507. continue;
  24508. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24509. continue;
  24510. pickingInfo = result;
  24511. if (fastCheck) {
  24512. break;
  24513. }
  24514. }
  24515. return pickingInfo || new BABYLON.PickingInfo();
  24516. };
  24517. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24518. if (!BABYLON.PickingInfo) {
  24519. return null;
  24520. }
  24521. var pickingInfos = new Array();
  24522. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24523. var mesh = this.meshes[meshIndex];
  24524. if (predicate) {
  24525. if (!predicate(mesh)) {
  24526. continue;
  24527. }
  24528. }
  24529. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24530. continue;
  24531. }
  24532. var world = mesh.getWorldMatrix();
  24533. var ray = rayFunction(world);
  24534. var result = mesh.intersects(ray, false);
  24535. if (!result || !result.hit)
  24536. continue;
  24537. pickingInfos.push(result);
  24538. }
  24539. return pickingInfos;
  24540. };
  24541. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24542. if (!BABYLON.PickingInfo) {
  24543. return null;
  24544. }
  24545. var pickingInfo = null;
  24546. if (!camera) {
  24547. if (!this.activeCamera) {
  24548. return null;
  24549. }
  24550. camera = this.activeCamera;
  24551. }
  24552. if (this.spriteManagers.length > 0) {
  24553. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24554. var spriteManager = this.spriteManagers[spriteIndex];
  24555. if (!spriteManager.isPickable) {
  24556. continue;
  24557. }
  24558. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24559. if (!result || !result.hit)
  24560. continue;
  24561. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24562. continue;
  24563. pickingInfo = result;
  24564. if (fastCheck) {
  24565. break;
  24566. }
  24567. }
  24568. }
  24569. return pickingInfo || new BABYLON.PickingInfo();
  24570. };
  24571. /** Launch a ray to try to pick a mesh in the scene
  24572. * @param x position on screen
  24573. * @param y position on screen
  24574. * @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
  24575. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24576. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24577. */
  24578. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24579. var _this = this;
  24580. if (!BABYLON.PickingInfo) {
  24581. return null;
  24582. }
  24583. return this._internalPick(function (world) {
  24584. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24585. return _this._tempPickingRay;
  24586. }, predicate, fastCheck);
  24587. };
  24588. /** Launch a ray to try to pick a sprite in the scene
  24589. * @param x position on screen
  24590. * @param y position on screen
  24591. * @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
  24592. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24593. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24594. */
  24595. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24596. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24597. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24598. };
  24599. /** Use the given ray to pick a mesh in the scene
  24600. * @param ray The ray to use to pick meshes
  24601. * @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
  24602. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24603. */
  24604. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24605. var _this = this;
  24606. return this._internalPick(function (world) {
  24607. if (!_this._pickWithRayInverseMatrix) {
  24608. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24609. }
  24610. world.invertToRef(_this._pickWithRayInverseMatrix);
  24611. if (!_this._cachedRayForTransform) {
  24612. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24613. }
  24614. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24615. return _this._cachedRayForTransform;
  24616. }, predicate, fastCheck);
  24617. };
  24618. /**
  24619. * Launch a ray to try to pick a mesh in the scene
  24620. * @param x X position on screen
  24621. * @param y Y position on screen
  24622. * @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
  24623. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24624. */
  24625. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24626. var _this = this;
  24627. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24628. };
  24629. /**
  24630. * Launch a ray to try to pick a mesh in the scene
  24631. * @param ray Ray to use
  24632. * @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
  24633. */
  24634. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24635. var _this = this;
  24636. return this._internalMultiPick(function (world) {
  24637. if (!_this._pickWithRayInverseMatrix) {
  24638. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24639. }
  24640. world.invertToRef(_this._pickWithRayInverseMatrix);
  24641. if (!_this._cachedRayForTransform) {
  24642. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24643. }
  24644. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24645. return _this._cachedRayForTransform;
  24646. }, predicate);
  24647. };
  24648. Scene.prototype.setPointerOverMesh = function (mesh) {
  24649. if (this._pointerOverMesh === mesh) {
  24650. return;
  24651. }
  24652. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24653. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24654. }
  24655. this._pointerOverMesh = mesh;
  24656. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24657. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24658. }
  24659. };
  24660. Scene.prototype.getPointerOverMesh = function () {
  24661. return this._pointerOverMesh;
  24662. };
  24663. Scene.prototype.setPointerOverSprite = function (sprite) {
  24664. if (this._pointerOverSprite === sprite) {
  24665. return;
  24666. }
  24667. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24668. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24669. }
  24670. this._pointerOverSprite = sprite;
  24671. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24672. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24673. }
  24674. };
  24675. Scene.prototype.getPointerOverSprite = function () {
  24676. return this._pointerOverSprite;
  24677. };
  24678. // Physics
  24679. Scene.prototype.getPhysicsEngine = function () {
  24680. return this._physicsEngine;
  24681. };
  24682. /**
  24683. * Enables physics to the current scene
  24684. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24685. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24686. * @return {boolean} was the physics engine initialized
  24687. */
  24688. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24689. if (gravity === void 0) { gravity = null; }
  24690. if (this._physicsEngine) {
  24691. return true;
  24692. }
  24693. try {
  24694. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24695. return true;
  24696. }
  24697. catch (e) {
  24698. BABYLON.Tools.Error(e.message);
  24699. return false;
  24700. }
  24701. };
  24702. Scene.prototype.disablePhysicsEngine = function () {
  24703. if (!this._physicsEngine) {
  24704. return;
  24705. }
  24706. this._physicsEngine.dispose();
  24707. this._physicsEngine = null;
  24708. };
  24709. Scene.prototype.isPhysicsEnabled = function () {
  24710. return this._physicsEngine !== undefined;
  24711. };
  24712. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24713. var mesh = compound.parts[0].mesh;
  24714. if (mesh.physicsImpostor) {
  24715. mesh.physicsImpostor.dispose();
  24716. mesh.physicsImpostor = null;
  24717. }
  24718. };
  24719. // Misc.
  24720. Scene.prototype._rebuildGeometries = function () {
  24721. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24722. var geometry = _a[_i];
  24723. geometry._rebuild();
  24724. }
  24725. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24726. var mesh = _c[_b];
  24727. mesh._rebuild();
  24728. }
  24729. if (this.postProcessManager) {
  24730. this.postProcessManager._rebuild();
  24731. }
  24732. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24733. var layer = _e[_d];
  24734. layer._rebuild();
  24735. }
  24736. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24737. var effectLayer = _g[_f];
  24738. effectLayer._rebuild();
  24739. }
  24740. if (this._boundingBoxRenderer) {
  24741. this._boundingBoxRenderer._rebuild();
  24742. }
  24743. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24744. var system = _j[_h];
  24745. system.rebuild();
  24746. }
  24747. if (this._postProcessRenderPipelineManager) {
  24748. this._postProcessRenderPipelineManager._rebuild();
  24749. }
  24750. };
  24751. Scene.prototype._rebuildTextures = function () {
  24752. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24753. var texture = _a[_i];
  24754. texture._rebuild();
  24755. }
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24757. };
  24758. /**
  24759. * Creates a default light for the scene.
  24760. * @param replace Whether to replace the existing lights in the scene.
  24761. */
  24762. Scene.prototype.createDefaultLight = function (replace) {
  24763. if (replace === void 0) { replace = false; }
  24764. // Dispose existing light in replace mode.
  24765. if (replace) {
  24766. if (this.lights) {
  24767. for (var i = 0; i < this.lights.length; i++) {
  24768. this.lights[i].dispose();
  24769. }
  24770. }
  24771. }
  24772. // Light
  24773. if (this.lights.length === 0) {
  24774. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24775. }
  24776. };
  24777. /**
  24778. * Creates a default camera for the scene.
  24779. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24780. * @param replace Whether to replace the existing active camera in the scene.
  24781. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24782. */
  24783. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24784. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24785. if (replace === void 0) { replace = false; }
  24786. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24787. // Dispose existing camera in replace mode.
  24788. if (replace) {
  24789. if (this.activeCamera) {
  24790. this.activeCamera.dispose();
  24791. this.activeCamera = null;
  24792. }
  24793. }
  24794. // Camera
  24795. if (!this.activeCamera) {
  24796. var worldExtends = this.getWorldExtends();
  24797. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24798. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24799. var camera;
  24800. var radius = worldSize.length() * 1.5;
  24801. // empty scene scenario!
  24802. if (!isFinite(radius)) {
  24803. radius = 1;
  24804. worldCenter.copyFromFloats(0, 0, 0);
  24805. }
  24806. if (createArcRotateCamera) {
  24807. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24808. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24809. arcRotateCamera.wheelPrecision = 100 / radius;
  24810. camera = arcRotateCamera;
  24811. }
  24812. else {
  24813. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24814. freeCamera.setTarget(worldCenter);
  24815. camera = freeCamera;
  24816. }
  24817. camera.minZ = radius * 0.01;
  24818. camera.maxZ = radius * 1000;
  24819. camera.speed = radius * 0.2;
  24820. this.activeCamera = camera;
  24821. var canvas = this.getEngine().getRenderingCanvas();
  24822. if (attachCameraControls && canvas) {
  24823. camera.attachControl(canvas);
  24824. }
  24825. }
  24826. };
  24827. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24828. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24829. if (replace === void 0) { replace = false; }
  24830. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24831. this.createDefaultLight(replace);
  24832. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24833. };
  24834. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24835. if (pbr === void 0) { pbr = false; }
  24836. if (scale === void 0) { scale = 1000; }
  24837. if (blur === void 0) { blur = 0; }
  24838. if (environmentTexture) {
  24839. this.environmentTexture = environmentTexture;
  24840. }
  24841. if (!this.environmentTexture) {
  24842. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24843. return null;
  24844. }
  24845. // Skybox
  24846. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24847. if (pbr) {
  24848. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24849. hdrSkyboxMaterial.backFaceCulling = false;
  24850. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24851. if (hdrSkyboxMaterial.reflectionTexture) {
  24852. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24853. }
  24854. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24855. hdrSkyboxMaterial.disableLighting = true;
  24856. hdrSkyboxMaterial.twoSidedLighting = true;
  24857. hdrSkybox.infiniteDistance = true;
  24858. hdrSkybox.material = hdrSkyboxMaterial;
  24859. }
  24860. else {
  24861. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24862. skyboxMaterial.backFaceCulling = false;
  24863. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24864. if (skyboxMaterial.reflectionTexture) {
  24865. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24866. }
  24867. skyboxMaterial.disableLighting = true;
  24868. hdrSkybox.infiniteDistance = true;
  24869. hdrSkybox.material = skyboxMaterial;
  24870. }
  24871. return hdrSkybox;
  24872. };
  24873. Scene.prototype.createDefaultEnvironment = function (options) {
  24874. if (BABYLON.EnvironmentHelper) {
  24875. return new BABYLON.EnvironmentHelper(options, this);
  24876. }
  24877. return null;
  24878. };
  24879. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24880. if (webVROptions === void 0) { webVROptions = {}; }
  24881. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24882. };
  24883. // Tags
  24884. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24885. if (tagsQuery === undefined) {
  24886. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24887. return list;
  24888. }
  24889. var listByTags = [];
  24890. forEach = forEach || (function (item) { return; });
  24891. for (var i in list) {
  24892. var item = list[i];
  24893. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24894. listByTags.push(item);
  24895. forEach(item);
  24896. }
  24897. }
  24898. return listByTags;
  24899. };
  24900. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24901. return this._getByTags(this.meshes, tagsQuery, forEach);
  24902. };
  24903. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24904. return this._getByTags(this.cameras, tagsQuery, forEach);
  24905. };
  24906. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24907. return this._getByTags(this.lights, tagsQuery, forEach);
  24908. };
  24909. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24910. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24911. };
  24912. /**
  24913. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24914. * This allowed control for front to back rendering or reversly depending of the special needs.
  24915. *
  24916. * @param renderingGroupId The rendering group id corresponding to its index
  24917. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24918. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24919. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24920. */
  24921. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24922. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24923. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24924. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24925. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24926. };
  24927. /**
  24928. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24929. *
  24930. * @param renderingGroupId The rendering group id corresponding to its index
  24931. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24932. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24933. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24934. */
  24935. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24936. if (depth === void 0) { depth = true; }
  24937. if (stencil === void 0) { stencil = true; }
  24938. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24939. };
  24940. /**
  24941. * Will flag all materials as dirty to trigger new shader compilation
  24942. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24943. */
  24944. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24945. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24946. var material = _a[_i];
  24947. if (predicate && !predicate(material)) {
  24948. continue;
  24949. }
  24950. material.markAsDirty(flag);
  24951. }
  24952. };
  24953. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24954. var _this = this;
  24955. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24956. this._activeRequests.push(request);
  24957. request.onCompleteObservable.add(function (request) {
  24958. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24959. });
  24960. return request;
  24961. };
  24962. /** @ignore */
  24963. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24964. var _this = this;
  24965. return new Promise(function (resolve, reject) {
  24966. _this._loadFile(url, function (data) {
  24967. resolve(data);
  24968. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24969. reject(exception);
  24970. });
  24971. });
  24972. };
  24973. // Statics
  24974. Scene._FOGMODE_NONE = 0;
  24975. Scene._FOGMODE_EXP = 1;
  24976. Scene._FOGMODE_EXP2 = 2;
  24977. Scene._FOGMODE_LINEAR = 3;
  24978. Scene._uniqueIdCounter = 0;
  24979. Scene.MinDeltaTime = 1.0;
  24980. Scene.MaxDeltaTime = 1000.0;
  24981. /** The distance in pixel that you have to move to prevent some events */
  24982. Scene.DragMovementThreshold = 10; // in pixels
  24983. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24984. Scene.LongPressDelay = 500; // in milliseconds
  24985. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24986. Scene.DoubleClickDelay = 300; // in milliseconds
  24987. /** If you need to check double click without raising a single click at first click, enable this flag */
  24988. Scene.ExclusiveDoubleClickMode = false;
  24989. return Scene;
  24990. }());
  24991. BABYLON.Scene = Scene;
  24992. })(BABYLON || (BABYLON = {}));
  24993. //# sourceMappingURL=babylon.scene.js.map
  24994. var BABYLON;
  24995. (function (BABYLON) {
  24996. /**
  24997. * Set of assets to keep when moving a scene into an asset container.
  24998. */
  24999. var KeepAssets = /** @class */ (function () {
  25000. function KeepAssets() {
  25001. /**
  25002. * Cameras to keep.
  25003. */
  25004. this.cameras = new Array();
  25005. /**
  25006. * Lights to keep.
  25007. */
  25008. this.lights = new Array();
  25009. /**
  25010. * Meshes to keep.
  25011. */
  25012. this.meshes = new Array();
  25013. /**
  25014. * Skeletons to keep.
  25015. */
  25016. this.skeletons = new Array();
  25017. /**
  25018. * ParticleSystems to keep.
  25019. */
  25020. this.particleSystems = new Array();
  25021. /**
  25022. * Animations to keep.
  25023. */
  25024. this.animations = new Array();
  25025. /**
  25026. * MultiMaterials to keep.
  25027. */
  25028. this.multiMaterials = new Array();
  25029. /**
  25030. * Materials to keep.
  25031. */
  25032. this.materials = new Array();
  25033. /**
  25034. * MorphTargetManagers to keep.
  25035. */
  25036. this.morphTargetManagers = new Array();
  25037. /**
  25038. * Geometries to keep.
  25039. */
  25040. this.geometries = new Array();
  25041. /**
  25042. * TransformNodes to keep.
  25043. */
  25044. this.transformNodes = new Array();
  25045. /**
  25046. * LensFlareSystems to keep.
  25047. */
  25048. this.lensFlareSystems = new Array();
  25049. /**
  25050. * ShadowGenerators to keep.
  25051. */
  25052. this.shadowGenerators = new Array();
  25053. /**
  25054. * ActionManagers to keep.
  25055. */
  25056. this.actionManagers = new Array();
  25057. /**
  25058. * Sounds to keep.
  25059. */
  25060. this.sounds = new Array();
  25061. }
  25062. return KeepAssets;
  25063. }());
  25064. BABYLON.KeepAssets = KeepAssets;
  25065. /**
  25066. * Container with a set of assets that can be added or removed from a scene.
  25067. */
  25068. var AssetContainer = /** @class */ (function () {
  25069. /**
  25070. * Instantiates an AssetContainer.
  25071. * @param scene The scene the AssetContainer belongs to.
  25072. */
  25073. function AssetContainer(scene) {
  25074. // Objects
  25075. /**
  25076. * Cameras populated in the container.
  25077. */
  25078. this.cameras = new Array();
  25079. /**
  25080. * Lights populated in the container.
  25081. */
  25082. this.lights = new Array();
  25083. /**
  25084. * Meshes populated in the container.
  25085. */
  25086. this.meshes = new Array();
  25087. /**
  25088. * Skeletons populated in the container.
  25089. */
  25090. this.skeletons = new Array();
  25091. /**
  25092. * ParticleSystems populated in the container.
  25093. */
  25094. this.particleSystems = new Array();
  25095. /**
  25096. * Animations populated in the container.
  25097. */
  25098. this.animations = new Array();
  25099. /**
  25100. * MultiMaterials populated in the container.
  25101. */
  25102. this.multiMaterials = new Array();
  25103. /**
  25104. * Materials populated in the container.
  25105. */
  25106. this.materials = new Array();
  25107. /**
  25108. * MorphTargetManagers populated in the container.
  25109. */
  25110. this.morphTargetManagers = new Array();
  25111. /**
  25112. * Geometries populated in the container.
  25113. */
  25114. this.geometries = new Array();
  25115. /**
  25116. * TransformNodes populated in the container.
  25117. */
  25118. this.transformNodes = new Array();
  25119. /**
  25120. * LensFlareSystems populated in the container.
  25121. */
  25122. this.lensFlareSystems = new Array();
  25123. /**
  25124. * ShadowGenerators populated in the container.
  25125. */
  25126. this.shadowGenerators = new Array();
  25127. /**
  25128. * ActionManagers populated in the container.
  25129. */
  25130. this.actionManagers = new Array();
  25131. /**
  25132. * Sounds populated in the container.
  25133. */
  25134. this.sounds = new Array();
  25135. this.scene = scene;
  25136. }
  25137. /**
  25138. * Adds all the assets from the container to the scene.
  25139. */
  25140. AssetContainer.prototype.addAllToScene = function () {
  25141. var _this = this;
  25142. this.cameras.forEach(function (o) {
  25143. _this.scene.addCamera(o);
  25144. });
  25145. this.lights.forEach(function (o) {
  25146. _this.scene.addLight(o);
  25147. });
  25148. this.meshes.forEach(function (o) {
  25149. _this.scene.addMesh(o);
  25150. });
  25151. this.skeletons.forEach(function (o) {
  25152. _this.scene.addSkeleton(o);
  25153. });
  25154. this.particleSystems.forEach(function (o) {
  25155. _this.scene.addParticleSystem(o);
  25156. });
  25157. this.animations.forEach(function (o) {
  25158. _this.scene.addAnimation(o);
  25159. });
  25160. this.multiMaterials.forEach(function (o) {
  25161. _this.scene.addMultiMaterial(o);
  25162. });
  25163. this.materials.forEach(function (o) {
  25164. _this.scene.addMaterial(o);
  25165. });
  25166. this.morphTargetManagers.forEach(function (o) {
  25167. _this.scene.addMorphTargetManager(o);
  25168. });
  25169. this.geometries.forEach(function (o) {
  25170. _this.scene.addGeometry(o);
  25171. });
  25172. this.transformNodes.forEach(function (o) {
  25173. _this.scene.addTransformNode(o);
  25174. });
  25175. this.lensFlareSystems.forEach(function (o) {
  25176. _this.scene.addLensFlareSystem(o);
  25177. });
  25178. this.actionManagers.forEach(function (o) {
  25179. _this.scene.addActionManager(o);
  25180. });
  25181. this.sounds.forEach(function (o) {
  25182. o.play();
  25183. o.autoplay = true;
  25184. _this.scene.mainSoundTrack.AddSound(o);
  25185. });
  25186. };
  25187. /**
  25188. * Removes all the assets in the container from the scene
  25189. */
  25190. AssetContainer.prototype.removeAllFromScene = function () {
  25191. var _this = this;
  25192. this.cameras.forEach(function (o) {
  25193. _this.scene.removeCamera(o);
  25194. });
  25195. this.lights.forEach(function (o) {
  25196. _this.scene.removeLight(o);
  25197. });
  25198. this.meshes.forEach(function (o) {
  25199. _this.scene.removeMesh(o);
  25200. });
  25201. this.skeletons.forEach(function (o) {
  25202. _this.scene.removeSkeleton(o);
  25203. });
  25204. this.particleSystems.forEach(function (o) {
  25205. _this.scene.removeParticleSystem(o);
  25206. });
  25207. this.animations.forEach(function (o) {
  25208. _this.scene.removeAnimation(o);
  25209. });
  25210. this.multiMaterials.forEach(function (o) {
  25211. _this.scene.removeMultiMaterial(o);
  25212. });
  25213. this.materials.forEach(function (o) {
  25214. _this.scene.removeMaterial(o);
  25215. });
  25216. this.morphTargetManagers.forEach(function (o) {
  25217. _this.scene.removeMorphTargetManager(o);
  25218. });
  25219. this.geometries.forEach(function (o) {
  25220. _this.scene.removeGeometry(o);
  25221. });
  25222. this.transformNodes.forEach(function (o) {
  25223. _this.scene.removeTransformNode(o);
  25224. });
  25225. this.lensFlareSystems.forEach(function (o) {
  25226. _this.scene.removeLensFlareSystem(o);
  25227. });
  25228. this.actionManagers.forEach(function (o) {
  25229. _this.scene.removeActionManager(o);
  25230. });
  25231. this.sounds.forEach(function (o) {
  25232. o.stop();
  25233. o.autoplay = false;
  25234. _this.scene.mainSoundTrack.RemoveSound(o);
  25235. });
  25236. };
  25237. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25238. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25239. var asset = sourceAssets_1[_i];
  25240. var move = true;
  25241. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25242. var keepAsset = keepAssets_1[_a];
  25243. if (asset === keepAsset) {
  25244. move = false;
  25245. break;
  25246. }
  25247. }
  25248. if (move) {
  25249. targetAssets.push(asset);
  25250. }
  25251. }
  25252. };
  25253. /**
  25254. * Removes all the assets contained in the scene and adds them to the container.
  25255. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25256. */
  25257. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25258. if (keepAssets === undefined) {
  25259. keepAssets = new KeepAssets();
  25260. }
  25261. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25262. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25263. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25264. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25265. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25266. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25267. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25268. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25269. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25270. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25271. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25272. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25273. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25274. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25275. this.removeAllFromScene();
  25276. };
  25277. return AssetContainer;
  25278. }());
  25279. BABYLON.AssetContainer = AssetContainer;
  25280. })(BABYLON || (BABYLON = {}));
  25281. //# sourceMappingURL=babylon.assetContainer.js.map
  25282. var BABYLON;
  25283. (function (BABYLON) {
  25284. var Buffer = /** @class */ (function () {
  25285. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25286. if (instanced === void 0) { instanced = false; }
  25287. if (engine instanceof BABYLON.Mesh) {
  25288. this._engine = engine.getScene().getEngine();
  25289. }
  25290. else {
  25291. this._engine = engine;
  25292. }
  25293. this._updatable = updatable;
  25294. this._instanced = instanced;
  25295. this._data = data;
  25296. this._strideSize = stride;
  25297. if (!postponeInternalCreation) {
  25298. this.create();
  25299. }
  25300. }
  25301. /**
  25302. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25303. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25304. * @param offset defines offset in the buffer (0 by default)
  25305. * @param size defines the size in floats of attributes (position is 3 for instance)
  25306. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25307. * @param instanced defines if the vertex buffer contains indexed data
  25308. * @returns the new vertex buffer
  25309. */
  25310. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25311. // a lot of these parameters are ignored as they are overriden by the buffer
  25312. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25313. };
  25314. // Properties
  25315. Buffer.prototype.isUpdatable = function () {
  25316. return this._updatable;
  25317. };
  25318. Buffer.prototype.getData = function () {
  25319. return this._data;
  25320. };
  25321. Buffer.prototype.getBuffer = function () {
  25322. return this._buffer;
  25323. };
  25324. Buffer.prototype.getStrideSize = function () {
  25325. return this._strideSize;
  25326. };
  25327. // public getIsInstanced(): boolean {
  25328. // return this._instanced;
  25329. // }
  25330. // public get instanceDivisor(): number {
  25331. // return this._instanceDivisor;
  25332. // }
  25333. // public set instanceDivisor(value: number) {
  25334. // this._instanceDivisor = value;
  25335. // if (value == 0) {
  25336. // this._instanced = false;
  25337. // } else {
  25338. // this._instanced = true;
  25339. // }
  25340. // }
  25341. // Methods
  25342. Buffer.prototype.create = function (data) {
  25343. if (data === void 0) { data = null; }
  25344. if (!data && this._buffer) {
  25345. return; // nothing to do
  25346. }
  25347. data = data || this._data;
  25348. if (!data) {
  25349. return;
  25350. }
  25351. if (!this._buffer) {
  25352. if (this._updatable) {
  25353. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25354. this._data = data;
  25355. }
  25356. else {
  25357. this._buffer = this._engine.createVertexBuffer(data);
  25358. }
  25359. }
  25360. else if (this._updatable) {
  25361. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25362. this._data = data;
  25363. }
  25364. };
  25365. Buffer.prototype._rebuild = function () {
  25366. this._buffer = null;
  25367. this.create(this._data);
  25368. };
  25369. Buffer.prototype.update = function (data) {
  25370. this.create(data);
  25371. };
  25372. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25373. if (!this._buffer) {
  25374. return;
  25375. }
  25376. if (this._updatable) {
  25377. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25378. this._data = null;
  25379. }
  25380. };
  25381. Buffer.prototype.dispose = function () {
  25382. if (!this._buffer) {
  25383. return;
  25384. }
  25385. if (this._engine._releaseBuffer(this._buffer)) {
  25386. this._buffer = null;
  25387. }
  25388. };
  25389. return Buffer;
  25390. }());
  25391. BABYLON.Buffer = Buffer;
  25392. })(BABYLON || (BABYLON = {}));
  25393. //# sourceMappingURL=babylon.buffer.js.map
  25394. var BABYLON;
  25395. (function (BABYLON) {
  25396. var VertexBuffer = /** @class */ (function () {
  25397. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25398. if (data instanceof BABYLON.Buffer) {
  25399. if (!stride) {
  25400. stride = data.getStrideSize();
  25401. }
  25402. this._buffer = data;
  25403. this._ownsBuffer = false;
  25404. }
  25405. else {
  25406. if (!stride) {
  25407. stride = VertexBuffer.DeduceStride(kind);
  25408. }
  25409. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25410. this._ownsBuffer = true;
  25411. }
  25412. this._stride = stride;
  25413. this._instanced = instanced !== undefined ? instanced : false;
  25414. this._instanceDivisor = instanced ? 1 : 0;
  25415. this._offset = offset ? offset : 0;
  25416. this._size = size ? size : stride;
  25417. this._kind = kind;
  25418. }
  25419. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25420. /**
  25421. * Gets or sets the instance divisor when in instanced mode
  25422. */
  25423. get: function () {
  25424. return this._instanceDivisor;
  25425. },
  25426. set: function (value) {
  25427. this._instanceDivisor = value;
  25428. if (value == 0) {
  25429. this._instanced = false;
  25430. }
  25431. else {
  25432. this._instanced = true;
  25433. }
  25434. },
  25435. enumerable: true,
  25436. configurable: true
  25437. });
  25438. VertexBuffer.prototype._rebuild = function () {
  25439. if (!this._buffer) {
  25440. return;
  25441. }
  25442. this._buffer._rebuild();
  25443. };
  25444. /**
  25445. * Returns the kind of the VertexBuffer (string).
  25446. */
  25447. VertexBuffer.prototype.getKind = function () {
  25448. return this._kind;
  25449. };
  25450. // Properties
  25451. /**
  25452. * Boolean : is the VertexBuffer updatable ?
  25453. */
  25454. VertexBuffer.prototype.isUpdatable = function () {
  25455. return this._buffer.isUpdatable();
  25456. };
  25457. /**
  25458. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25459. */
  25460. VertexBuffer.prototype.getData = function () {
  25461. return this._buffer.getData();
  25462. };
  25463. /**
  25464. * Returns the WebGLBuffer associated to the VertexBuffer.
  25465. */
  25466. VertexBuffer.prototype.getBuffer = function () {
  25467. return this._buffer.getBuffer();
  25468. };
  25469. /**
  25470. * Returns the stride of the VertexBuffer (integer).
  25471. */
  25472. VertexBuffer.prototype.getStrideSize = function () {
  25473. return this._stride;
  25474. };
  25475. /**
  25476. * Returns the offset (integer).
  25477. */
  25478. VertexBuffer.prototype.getOffset = function () {
  25479. return this._offset;
  25480. };
  25481. /**
  25482. * Returns the VertexBuffer total size (integer).
  25483. */
  25484. VertexBuffer.prototype.getSize = function () {
  25485. return this._size;
  25486. };
  25487. /**
  25488. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25489. */
  25490. VertexBuffer.prototype.getIsInstanced = function () {
  25491. return this._instanced;
  25492. };
  25493. /**
  25494. * Returns the instancing divisor, zero for non-instanced (integer).
  25495. */
  25496. VertexBuffer.prototype.getInstanceDivisor = function () {
  25497. return this._instanceDivisor;
  25498. };
  25499. // Methods
  25500. /**
  25501. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25502. * Returns the created WebGLBuffer.
  25503. */
  25504. VertexBuffer.prototype.create = function (data) {
  25505. return this._buffer.create(data);
  25506. };
  25507. /**
  25508. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25509. * This function will create a new buffer if the current one is not updatable
  25510. * Returns the updated WebGLBuffer.
  25511. */
  25512. VertexBuffer.prototype.update = function (data) {
  25513. return this._buffer.update(data);
  25514. };
  25515. /**
  25516. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25517. * Returns the directly updated WebGLBuffer.
  25518. */
  25519. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25520. return this._buffer.updateDirectly(data, offset);
  25521. };
  25522. /**
  25523. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25524. */
  25525. VertexBuffer.prototype.dispose = function () {
  25526. if (this._ownsBuffer) {
  25527. this._buffer.dispose();
  25528. }
  25529. };
  25530. Object.defineProperty(VertexBuffer, "PositionKind", {
  25531. get: function () {
  25532. return VertexBuffer._PositionKind;
  25533. },
  25534. enumerable: true,
  25535. configurable: true
  25536. });
  25537. Object.defineProperty(VertexBuffer, "NormalKind", {
  25538. get: function () {
  25539. return VertexBuffer._NormalKind;
  25540. },
  25541. enumerable: true,
  25542. configurable: true
  25543. });
  25544. Object.defineProperty(VertexBuffer, "TangentKind", {
  25545. get: function () {
  25546. return VertexBuffer._TangentKind;
  25547. },
  25548. enumerable: true,
  25549. configurable: true
  25550. });
  25551. Object.defineProperty(VertexBuffer, "UVKind", {
  25552. get: function () {
  25553. return VertexBuffer._UVKind;
  25554. },
  25555. enumerable: true,
  25556. configurable: true
  25557. });
  25558. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25559. get: function () {
  25560. return VertexBuffer._UV2Kind;
  25561. },
  25562. enumerable: true,
  25563. configurable: true
  25564. });
  25565. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25566. get: function () {
  25567. return VertexBuffer._UV3Kind;
  25568. },
  25569. enumerable: true,
  25570. configurable: true
  25571. });
  25572. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25573. get: function () {
  25574. return VertexBuffer._UV4Kind;
  25575. },
  25576. enumerable: true,
  25577. configurable: true
  25578. });
  25579. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25580. get: function () {
  25581. return VertexBuffer._UV5Kind;
  25582. },
  25583. enumerable: true,
  25584. configurable: true
  25585. });
  25586. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25587. get: function () {
  25588. return VertexBuffer._UV6Kind;
  25589. },
  25590. enumerable: true,
  25591. configurable: true
  25592. });
  25593. Object.defineProperty(VertexBuffer, "ColorKind", {
  25594. get: function () {
  25595. return VertexBuffer._ColorKind;
  25596. },
  25597. enumerable: true,
  25598. configurable: true
  25599. });
  25600. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25601. get: function () {
  25602. return VertexBuffer._MatricesIndicesKind;
  25603. },
  25604. enumerable: true,
  25605. configurable: true
  25606. });
  25607. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25608. get: function () {
  25609. return VertexBuffer._MatricesWeightsKind;
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25615. get: function () {
  25616. return VertexBuffer._MatricesIndicesExtraKind;
  25617. },
  25618. enumerable: true,
  25619. configurable: true
  25620. });
  25621. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25622. get: function () {
  25623. return VertexBuffer._MatricesWeightsExtraKind;
  25624. },
  25625. enumerable: true,
  25626. configurable: true
  25627. });
  25628. /**
  25629. * Deduces the stride given a kind.
  25630. * @param kind The kind string to deduce
  25631. * @returns The deduced stride
  25632. */
  25633. VertexBuffer.DeduceStride = function (kind) {
  25634. switch (kind) {
  25635. case VertexBuffer.PositionKind:
  25636. return 3;
  25637. case VertexBuffer.NormalKind:
  25638. return 3;
  25639. case VertexBuffer.UVKind:
  25640. case VertexBuffer.UV2Kind:
  25641. case VertexBuffer.UV3Kind:
  25642. case VertexBuffer.UV4Kind:
  25643. case VertexBuffer.UV5Kind:
  25644. case VertexBuffer.UV6Kind:
  25645. return 2;
  25646. case VertexBuffer.TangentKind:
  25647. case VertexBuffer.ColorKind:
  25648. return 4;
  25649. case VertexBuffer.MatricesIndicesKind:
  25650. case VertexBuffer.MatricesIndicesExtraKind:
  25651. return 4;
  25652. case VertexBuffer.MatricesWeightsKind:
  25653. case VertexBuffer.MatricesWeightsExtraKind:
  25654. return 4;
  25655. default:
  25656. throw new Error("Invalid kind '" + kind + "'");
  25657. }
  25658. };
  25659. // Enums
  25660. VertexBuffer._PositionKind = "position";
  25661. VertexBuffer._NormalKind = "normal";
  25662. VertexBuffer._TangentKind = "tangent";
  25663. VertexBuffer._UVKind = "uv";
  25664. VertexBuffer._UV2Kind = "uv2";
  25665. VertexBuffer._UV3Kind = "uv3";
  25666. VertexBuffer._UV4Kind = "uv4";
  25667. VertexBuffer._UV5Kind = "uv5";
  25668. VertexBuffer._UV6Kind = "uv6";
  25669. VertexBuffer._ColorKind = "color";
  25670. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25671. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25672. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25673. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25674. return VertexBuffer;
  25675. }());
  25676. BABYLON.VertexBuffer = VertexBuffer;
  25677. })(BABYLON || (BABYLON = {}));
  25678. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25679. var BABYLON;
  25680. (function (BABYLON) {
  25681. /**
  25682. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25683. */
  25684. var DummyInternalTextureTracker = /** @class */ (function () {
  25685. function DummyInternalTextureTracker() {
  25686. /**
  25687. * Gets or set the previous tracker in the list
  25688. */
  25689. this.previous = null;
  25690. /**
  25691. * Gets or set the next tracker in the list
  25692. */
  25693. this.next = null;
  25694. }
  25695. return DummyInternalTextureTracker;
  25696. }());
  25697. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25698. })(BABYLON || (BABYLON = {}));
  25699. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25700. var BABYLON;
  25701. (function (BABYLON) {
  25702. /**
  25703. * Class used to store data associated with WebGL texture data for the engine
  25704. * This class should not be used directly
  25705. */
  25706. var InternalTexture = /** @class */ (function () {
  25707. /**
  25708. * Creates a new InternalTexture
  25709. * @param engine defines the engine to use
  25710. * @param dataSource defines the type of data that will be used
  25711. */
  25712. function InternalTexture(engine, dataSource) {
  25713. /**
  25714. * Observable called when the texture is loaded
  25715. */
  25716. this.onLoadedObservable = new BABYLON.Observable();
  25717. /**
  25718. * Gets or set the previous tracker in the list
  25719. */
  25720. this.previous = null;
  25721. /**
  25722. * Gets or set the next tracker in the list
  25723. */
  25724. this.next = null;
  25725. // Private
  25726. /** @ignore */
  25727. this._initialSlot = -1;
  25728. /** @ignore */
  25729. this._designatedSlot = -1;
  25730. /** @ignore */
  25731. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25732. /** @ignore */
  25733. this._references = 1;
  25734. this._engine = engine;
  25735. this._dataSource = dataSource;
  25736. this._webGLTexture = engine._createTexture();
  25737. }
  25738. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25739. /**
  25740. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25741. */
  25742. get: function () {
  25743. return this._dataSource;
  25744. },
  25745. enumerable: true,
  25746. configurable: true
  25747. });
  25748. /**
  25749. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25750. */
  25751. InternalTexture.prototype.incrementReferences = function () {
  25752. this._references++;
  25753. };
  25754. /**
  25755. * Change the size of the texture (not the size of the content)
  25756. * @param width defines the new width
  25757. * @param height defines the new height
  25758. * @param depth defines the new depth (1 by default)
  25759. */
  25760. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25761. if (depth === void 0) { depth = 1; }
  25762. this.width = width;
  25763. this.height = height;
  25764. this.depth = depth;
  25765. this.baseWidth = width;
  25766. this.baseHeight = height;
  25767. this.baseDepth = depth;
  25768. this._size = width * height * depth;
  25769. };
  25770. /** @ignore */
  25771. InternalTexture.prototype._rebuild = function () {
  25772. var _this = this;
  25773. var proxy;
  25774. this.isReady = false;
  25775. this._cachedCoordinatesMode = null;
  25776. this._cachedWrapU = null;
  25777. this._cachedWrapV = null;
  25778. this._cachedAnisotropicFilteringLevel = null;
  25779. switch (this._dataSource) {
  25780. case InternalTexture.DATASOURCE_TEMP:
  25781. return;
  25782. case InternalTexture.DATASOURCE_URL:
  25783. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25784. _this.isReady = true;
  25785. }, null, this._buffer, undefined, this.format);
  25786. proxy._swapAndDie(this);
  25787. return;
  25788. case InternalTexture.DATASOURCE_RAW:
  25789. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25790. proxy._swapAndDie(this);
  25791. this.isReady = true;
  25792. return;
  25793. case InternalTexture.DATASOURCE_RAW3D:
  25794. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25795. proxy._swapAndDie(this);
  25796. this.isReady = true;
  25797. return;
  25798. case InternalTexture.DATASOURCE_DYNAMIC:
  25799. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25800. proxy._swapAndDie(this);
  25801. // The engine will make sure to update content so no need to flag it as isReady = true
  25802. return;
  25803. case InternalTexture.DATASOURCE_RENDERTARGET:
  25804. var options = new BABYLON.RenderTargetCreationOptions();
  25805. options.generateDepthBuffer = this._generateDepthBuffer;
  25806. options.generateMipMaps = this.generateMipMaps;
  25807. options.generateStencilBuffer = this._generateStencilBuffer;
  25808. options.samplingMode = this.samplingMode;
  25809. options.type = this.type;
  25810. if (this.isCube) {
  25811. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25812. }
  25813. else {
  25814. var size = {
  25815. width: this.width,
  25816. height: this.height
  25817. };
  25818. proxy = this._engine.createRenderTargetTexture(size, options);
  25819. }
  25820. proxy._swapAndDie(this);
  25821. this.isReady = true;
  25822. return;
  25823. case InternalTexture.DATASOURCE_CUBE:
  25824. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25825. _this.isReady = true;
  25826. }, null, this.format, this._extension);
  25827. proxy._swapAndDie(this);
  25828. return;
  25829. case InternalTexture.DATASOURCE_CUBERAW:
  25830. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25831. proxy._swapAndDie(this);
  25832. this.isReady = true;
  25833. return;
  25834. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25835. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25836. if (proxy) {
  25837. proxy._swapAndDie(_this);
  25838. }
  25839. _this.isReady = true;
  25840. }, null, this.format, this._extension);
  25841. return;
  25842. }
  25843. };
  25844. InternalTexture.prototype._swapAndDie = function (target) {
  25845. target._webGLTexture = this._webGLTexture;
  25846. if (this._framebuffer) {
  25847. target._framebuffer = this._framebuffer;
  25848. }
  25849. if (this._depthStencilBuffer) {
  25850. target._depthStencilBuffer = this._depthStencilBuffer;
  25851. }
  25852. if (this._lodTextureHigh) {
  25853. if (target._lodTextureHigh) {
  25854. target._lodTextureHigh.dispose();
  25855. }
  25856. target._lodTextureHigh = this._lodTextureHigh;
  25857. }
  25858. if (this._lodTextureMid) {
  25859. if (target._lodTextureMid) {
  25860. target._lodTextureMid.dispose();
  25861. }
  25862. target._lodTextureMid = this._lodTextureMid;
  25863. }
  25864. if (this._lodTextureLow) {
  25865. if (target._lodTextureLow) {
  25866. target._lodTextureLow.dispose();
  25867. }
  25868. target._lodTextureLow = this._lodTextureLow;
  25869. }
  25870. var cache = this._engine.getLoadedTexturesCache();
  25871. var index = cache.indexOf(this);
  25872. if (index !== -1) {
  25873. cache.splice(index, 1);
  25874. }
  25875. };
  25876. /**
  25877. * Dispose the current allocated resources
  25878. */
  25879. InternalTexture.prototype.dispose = function () {
  25880. if (!this._webGLTexture) {
  25881. return;
  25882. }
  25883. this._references--;
  25884. if (this._references === 0) {
  25885. this._engine._releaseTexture(this);
  25886. this._webGLTexture = null;
  25887. this.previous = null;
  25888. this.next = null;
  25889. }
  25890. };
  25891. /**
  25892. * The source of the texture data is unknown
  25893. */
  25894. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25895. /**
  25896. * Texture data comes from an URL
  25897. */
  25898. InternalTexture.DATASOURCE_URL = 1;
  25899. /**
  25900. * Texture data is only used for temporary storage
  25901. */
  25902. InternalTexture.DATASOURCE_TEMP = 2;
  25903. /**
  25904. * Texture data comes from raw data (ArrayBuffer)
  25905. */
  25906. InternalTexture.DATASOURCE_RAW = 3;
  25907. /**
  25908. * Texture content is dynamic (video or dynamic texture)
  25909. */
  25910. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25911. /**
  25912. * Texture content is generated by rendering to it
  25913. */
  25914. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25915. /**
  25916. * Texture content is part of a multi render target process
  25917. */
  25918. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25919. /**
  25920. * Texture data comes from a cube data file
  25921. */
  25922. InternalTexture.DATASOURCE_CUBE = 7;
  25923. /**
  25924. * Texture data comes from a raw cube data
  25925. */
  25926. InternalTexture.DATASOURCE_CUBERAW = 8;
  25927. /**
  25928. * Texture data come from a prefiltered cube data file
  25929. */
  25930. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25931. /**
  25932. * Texture content is raw 3D data
  25933. */
  25934. InternalTexture.DATASOURCE_RAW3D = 10;
  25935. return InternalTexture;
  25936. }());
  25937. BABYLON.InternalTexture = InternalTexture;
  25938. })(BABYLON || (BABYLON = {}));
  25939. //# sourceMappingURL=babylon.internalTexture.js.map
  25940. var BABYLON;
  25941. (function (BABYLON) {
  25942. var BaseTexture = /** @class */ (function () {
  25943. function BaseTexture(scene) {
  25944. this._hasAlpha = false;
  25945. this.getAlphaFromRGB = false;
  25946. this.level = 1;
  25947. this.coordinatesIndex = 0;
  25948. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25949. /**
  25950. * | Value | Type | Description |
  25951. * | ----- | ------------------ | ----------- |
  25952. * | 0 | CLAMP_ADDRESSMODE | |
  25953. * | 1 | WRAP_ADDRESSMODE | |
  25954. * | 2 | MIRROR_ADDRESSMODE | |
  25955. */
  25956. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25957. /**
  25958. * | Value | Type | Description |
  25959. * | ----- | ------------------ | ----------- |
  25960. * | 0 | CLAMP_ADDRESSMODE | |
  25961. * | 1 | WRAP_ADDRESSMODE | |
  25962. * | 2 | MIRROR_ADDRESSMODE | |
  25963. */
  25964. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25965. /**
  25966. * | Value | Type | Description |
  25967. * | ----- | ------------------ | ----------- |
  25968. * | 0 | CLAMP_ADDRESSMODE | |
  25969. * | 1 | WRAP_ADDRESSMODE | |
  25970. * | 2 | MIRROR_ADDRESSMODE | |
  25971. */
  25972. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25973. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25974. this.isCube = false;
  25975. this.is3D = false;
  25976. this.gammaSpace = true;
  25977. this.invertZ = false;
  25978. this.lodLevelInAlpha = false;
  25979. this.lodGenerationOffset = 0.0;
  25980. this.lodGenerationScale = 0.8;
  25981. this.isRenderTarget = false;
  25982. this.animations = new Array();
  25983. /**
  25984. * An event triggered when the texture is disposed.
  25985. * @type {BABYLON.Observable}
  25986. */
  25987. this.onDisposeObservable = new BABYLON.Observable();
  25988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25989. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25990. if (this._scene) {
  25991. this._scene.textures.push(this);
  25992. }
  25993. this._uid = null;
  25994. }
  25995. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25996. get: function () {
  25997. return this._hasAlpha;
  25998. },
  25999. set: function (value) {
  26000. if (this._hasAlpha === value) {
  26001. return;
  26002. }
  26003. this._hasAlpha = value;
  26004. if (this._scene) {
  26005. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26006. }
  26007. },
  26008. enumerable: true,
  26009. configurable: true
  26010. });
  26011. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26012. get: function () {
  26013. return this._coordinatesMode;
  26014. },
  26015. /**
  26016. * How a texture is mapped.
  26017. *
  26018. * | Value | Type | Description |
  26019. * | ----- | ----------------------------------- | ----------- |
  26020. * | 0 | EXPLICIT_MODE | |
  26021. * | 1 | SPHERICAL_MODE | |
  26022. * | 2 | PLANAR_MODE | |
  26023. * | 3 | CUBIC_MODE | |
  26024. * | 4 | PROJECTION_MODE | |
  26025. * | 5 | SKYBOX_MODE | |
  26026. * | 6 | INVCUBIC_MODE | |
  26027. * | 7 | EQUIRECTANGULAR_MODE | |
  26028. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26029. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26030. */
  26031. set: function (value) {
  26032. if (this._coordinatesMode === value) {
  26033. return;
  26034. }
  26035. this._coordinatesMode = value;
  26036. if (this._scene) {
  26037. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26038. }
  26039. },
  26040. enumerable: true,
  26041. configurable: true
  26042. });
  26043. Object.defineProperty(BaseTexture.prototype, "uid", {
  26044. get: function () {
  26045. if (!this._uid) {
  26046. this._uid = BABYLON.Tools.RandomId();
  26047. }
  26048. return this._uid;
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. BaseTexture.prototype.toString = function () {
  26054. return this.name;
  26055. };
  26056. BaseTexture.prototype.getClassName = function () {
  26057. return "BaseTexture";
  26058. };
  26059. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26060. set: function (callback) {
  26061. if (this._onDisposeObserver) {
  26062. this.onDisposeObservable.remove(this._onDisposeObserver);
  26063. }
  26064. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26065. },
  26066. enumerable: true,
  26067. configurable: true
  26068. });
  26069. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26070. get: function () {
  26071. return true;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. BaseTexture.prototype.getScene = function () {
  26077. return this._scene;
  26078. };
  26079. BaseTexture.prototype.getTextureMatrix = function () {
  26080. return BABYLON.Matrix.IdentityReadOnly;
  26081. };
  26082. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26083. return BABYLON.Matrix.IdentityReadOnly;
  26084. };
  26085. BaseTexture.prototype.getInternalTexture = function () {
  26086. return this._texture;
  26087. };
  26088. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26089. return !this.isBlocking || this.isReady();
  26090. };
  26091. BaseTexture.prototype.isReady = function () {
  26092. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26093. this.delayLoad();
  26094. return false;
  26095. }
  26096. if (this._texture) {
  26097. return this._texture.isReady;
  26098. }
  26099. return false;
  26100. };
  26101. BaseTexture.prototype.getSize = function () {
  26102. if (this._texture && this._texture.width) {
  26103. return new BABYLON.Size(this._texture.width, this._texture.height);
  26104. }
  26105. if (this._texture && this._texture._size) {
  26106. return new BABYLON.Size(this._texture._size, this._texture._size);
  26107. }
  26108. return BABYLON.Size.Zero();
  26109. };
  26110. BaseTexture.prototype.getBaseSize = function () {
  26111. if (!this.isReady() || !this._texture)
  26112. return BABYLON.Size.Zero();
  26113. if (this._texture._size) {
  26114. return new BABYLON.Size(this._texture._size, this._texture._size);
  26115. }
  26116. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26117. };
  26118. BaseTexture.prototype.scale = function (ratio) {
  26119. };
  26120. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26121. get: function () {
  26122. return false;
  26123. },
  26124. enumerable: true,
  26125. configurable: true
  26126. });
  26127. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26128. if (!this._scene) {
  26129. return null;
  26130. }
  26131. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26132. for (var index = 0; index < texturesCache.length; index++) {
  26133. var texturesCacheEntry = texturesCache[index];
  26134. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26135. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26136. texturesCacheEntry.incrementReferences();
  26137. return texturesCacheEntry;
  26138. }
  26139. }
  26140. }
  26141. return null;
  26142. };
  26143. BaseTexture.prototype._rebuild = function () {
  26144. };
  26145. BaseTexture.prototype.delayLoad = function () {
  26146. };
  26147. BaseTexture.prototype.clone = function () {
  26148. return null;
  26149. };
  26150. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26151. get: function () {
  26152. if (!this._texture) {
  26153. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26154. }
  26155. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26156. },
  26157. enumerable: true,
  26158. configurable: true
  26159. });
  26160. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26161. get: function () {
  26162. if (!this._texture) {
  26163. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26164. }
  26165. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26166. },
  26167. enumerable: true,
  26168. configurable: true
  26169. });
  26170. BaseTexture.prototype.readPixels = function (faceIndex) {
  26171. if (faceIndex === void 0) { faceIndex = 0; }
  26172. if (!this._texture) {
  26173. return null;
  26174. }
  26175. var size = this.getSize();
  26176. var scene = this.getScene();
  26177. if (!scene) {
  26178. return null;
  26179. }
  26180. var engine = scene.getEngine();
  26181. if (this._texture.isCube) {
  26182. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26183. }
  26184. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26185. };
  26186. BaseTexture.prototype.releaseInternalTexture = function () {
  26187. if (this._texture) {
  26188. this._texture.dispose();
  26189. this._texture = null;
  26190. }
  26191. };
  26192. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26193. get: function () {
  26194. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26195. return null;
  26196. }
  26197. if (!this._texture._sphericalPolynomial) {
  26198. this._texture._sphericalPolynomial =
  26199. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26200. }
  26201. return this._texture._sphericalPolynomial;
  26202. },
  26203. set: function (value) {
  26204. if (this._texture) {
  26205. this._texture._sphericalPolynomial = value;
  26206. }
  26207. },
  26208. enumerable: true,
  26209. configurable: true
  26210. });
  26211. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26212. get: function () {
  26213. if (this._texture) {
  26214. return this._texture._lodTextureHigh;
  26215. }
  26216. return null;
  26217. },
  26218. enumerable: true,
  26219. configurable: true
  26220. });
  26221. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26222. get: function () {
  26223. if (this._texture) {
  26224. return this._texture._lodTextureMid;
  26225. }
  26226. return null;
  26227. },
  26228. enumerable: true,
  26229. configurable: true
  26230. });
  26231. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26232. get: function () {
  26233. if (this._texture) {
  26234. return this._texture._lodTextureLow;
  26235. }
  26236. return null;
  26237. },
  26238. enumerable: true,
  26239. configurable: true
  26240. });
  26241. BaseTexture.prototype.dispose = function () {
  26242. if (!this._scene) {
  26243. return;
  26244. }
  26245. // Animations
  26246. this._scene.stopAnimation(this);
  26247. // Remove from scene
  26248. this._scene._removePendingData(this);
  26249. var index = this._scene.textures.indexOf(this);
  26250. if (index >= 0) {
  26251. this._scene.textures.splice(index, 1);
  26252. }
  26253. if (this._texture === undefined) {
  26254. return;
  26255. }
  26256. // Release
  26257. this.releaseInternalTexture();
  26258. // Callback
  26259. this.onDisposeObservable.notifyObservers(this);
  26260. this.onDisposeObservable.clear();
  26261. };
  26262. BaseTexture.prototype.serialize = function () {
  26263. if (!this.name) {
  26264. return null;
  26265. }
  26266. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26267. // Animations
  26268. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26269. return serializationObject;
  26270. };
  26271. BaseTexture.WhenAllReady = function (textures, callback) {
  26272. var numRemaining = textures.length;
  26273. if (numRemaining === 0) {
  26274. callback();
  26275. return;
  26276. }
  26277. var _loop_1 = function () {
  26278. texture = textures[i];
  26279. if (texture.isReady()) {
  26280. if (--numRemaining === 0) {
  26281. callback();
  26282. }
  26283. }
  26284. else {
  26285. onLoadObservable = texture.onLoadObservable;
  26286. var onLoadCallback_1 = function () {
  26287. onLoadObservable.removeCallback(onLoadCallback_1);
  26288. if (--numRemaining === 0) {
  26289. callback();
  26290. }
  26291. };
  26292. onLoadObservable.add(onLoadCallback_1);
  26293. }
  26294. };
  26295. var texture, onLoadObservable;
  26296. for (var i = 0; i < textures.length; i++) {
  26297. _loop_1();
  26298. }
  26299. };
  26300. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26301. __decorate([
  26302. BABYLON.serialize()
  26303. ], BaseTexture.prototype, "name", void 0);
  26304. __decorate([
  26305. BABYLON.serialize("hasAlpha")
  26306. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26307. __decorate([
  26308. BABYLON.serialize()
  26309. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26310. __decorate([
  26311. BABYLON.serialize()
  26312. ], BaseTexture.prototype, "level", void 0);
  26313. __decorate([
  26314. BABYLON.serialize()
  26315. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26316. __decorate([
  26317. BABYLON.serialize("coordinatesMode")
  26318. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26319. __decorate([
  26320. BABYLON.serialize()
  26321. ], BaseTexture.prototype, "wrapU", void 0);
  26322. __decorate([
  26323. BABYLON.serialize()
  26324. ], BaseTexture.prototype, "wrapV", void 0);
  26325. __decorate([
  26326. BABYLON.serialize()
  26327. ], BaseTexture.prototype, "wrapR", void 0);
  26328. __decorate([
  26329. BABYLON.serialize()
  26330. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26331. __decorate([
  26332. BABYLON.serialize()
  26333. ], BaseTexture.prototype, "isCube", void 0);
  26334. __decorate([
  26335. BABYLON.serialize()
  26336. ], BaseTexture.prototype, "is3D", void 0);
  26337. __decorate([
  26338. BABYLON.serialize()
  26339. ], BaseTexture.prototype, "gammaSpace", void 0);
  26340. __decorate([
  26341. BABYLON.serialize()
  26342. ], BaseTexture.prototype, "invertZ", void 0);
  26343. __decorate([
  26344. BABYLON.serialize()
  26345. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26346. __decorate([
  26347. BABYLON.serialize()
  26348. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26349. __decorate([
  26350. BABYLON.serialize()
  26351. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26352. __decorate([
  26353. BABYLON.serialize()
  26354. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26355. return BaseTexture;
  26356. }());
  26357. BABYLON.BaseTexture = BaseTexture;
  26358. })(BABYLON || (BABYLON = {}));
  26359. //# sourceMappingURL=babylon.baseTexture.js.map
  26360. var BABYLON;
  26361. (function (BABYLON) {
  26362. var Texture = /** @class */ (function (_super) {
  26363. __extends(Texture, _super);
  26364. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26365. if (noMipmap === void 0) { noMipmap = false; }
  26366. if (invertY === void 0) { invertY = true; }
  26367. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26368. if (onLoad === void 0) { onLoad = null; }
  26369. if (onError === void 0) { onError = null; }
  26370. if (buffer === void 0) { buffer = null; }
  26371. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26372. var _this = _super.call(this, scene) || this;
  26373. _this.uOffset = 0;
  26374. _this.vOffset = 0;
  26375. _this.uScale = 1.0;
  26376. _this.vScale = 1.0;
  26377. _this.uAng = 0;
  26378. _this.vAng = 0;
  26379. _this.wAng = 0;
  26380. _this._isBlocking = true;
  26381. _this.name = url || "";
  26382. _this.url = url;
  26383. _this._noMipmap = noMipmap;
  26384. _this._invertY = invertY;
  26385. _this._samplingMode = samplingMode;
  26386. _this._buffer = buffer;
  26387. _this._deleteBuffer = deleteBuffer;
  26388. if (format) {
  26389. _this._format = format;
  26390. }
  26391. scene = _this.getScene();
  26392. if (!scene) {
  26393. return _this;
  26394. }
  26395. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26396. var load = function () {
  26397. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26398. _this.onLoadObservable.notifyObservers(_this);
  26399. }
  26400. if (onLoad) {
  26401. onLoad();
  26402. }
  26403. if (!_this.isBlocking && scene) {
  26404. scene.resetCachedMaterial();
  26405. }
  26406. };
  26407. if (!_this.url) {
  26408. _this._delayedOnLoad = load;
  26409. _this._delayedOnError = onError;
  26410. return _this;
  26411. }
  26412. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26413. if (!_this._texture) {
  26414. if (!scene.useDelayedTextureLoading) {
  26415. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26416. if (deleteBuffer) {
  26417. delete _this._buffer;
  26418. }
  26419. }
  26420. else {
  26421. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26422. _this._delayedOnLoad = load;
  26423. _this._delayedOnError = onError;
  26424. }
  26425. }
  26426. else {
  26427. if (_this._texture.isReady) {
  26428. BABYLON.Tools.SetImmediate(function () { return load(); });
  26429. }
  26430. else {
  26431. _this._texture.onLoadedObservable.add(load);
  26432. }
  26433. }
  26434. return _this;
  26435. }
  26436. Object.defineProperty(Texture.prototype, "noMipmap", {
  26437. get: function () {
  26438. return this._noMipmap;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(Texture.prototype, "isBlocking", {
  26444. get: function () {
  26445. return this._isBlocking;
  26446. },
  26447. set: function (value) {
  26448. this._isBlocking = value;
  26449. },
  26450. enumerable: true,
  26451. configurable: true
  26452. });
  26453. Object.defineProperty(Texture.prototype, "samplingMode", {
  26454. get: function () {
  26455. return this._samplingMode;
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. Texture.prototype.updateURL = function (url) {
  26461. this.url = url;
  26462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26463. this.delayLoad();
  26464. };
  26465. Texture.prototype.delayLoad = function () {
  26466. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26467. return;
  26468. }
  26469. var scene = this.getScene();
  26470. if (!scene) {
  26471. return;
  26472. }
  26473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26474. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26475. if (!this._texture) {
  26476. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26477. if (this._deleteBuffer) {
  26478. delete this._buffer;
  26479. }
  26480. }
  26481. else {
  26482. if (this._delayedOnLoad) {
  26483. if (this._texture.isReady) {
  26484. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26485. }
  26486. else {
  26487. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26488. }
  26489. }
  26490. }
  26491. this._delayedOnLoad = null;
  26492. this._delayedOnError = null;
  26493. };
  26494. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26495. if (!this._texture) {
  26496. return;
  26497. }
  26498. var scene = this.getScene();
  26499. if (!scene) {
  26500. return;
  26501. }
  26502. this._samplingMode = samplingMode;
  26503. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26504. };
  26505. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26506. x *= this.uScale;
  26507. y *= this.vScale;
  26508. x -= 0.5 * this.uScale;
  26509. y -= 0.5 * this.vScale;
  26510. z -= 0.5;
  26511. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26512. t.x += 0.5 * this.uScale + this.uOffset;
  26513. t.y += 0.5 * this.vScale + this.vOffset;
  26514. t.z += 0.5;
  26515. };
  26516. Texture.prototype.getTextureMatrix = function () {
  26517. var _this = this;
  26518. if (this.uOffset === this._cachedUOffset &&
  26519. this.vOffset === this._cachedVOffset &&
  26520. this.uScale === this._cachedUScale &&
  26521. this.vScale === this._cachedVScale &&
  26522. this.uAng === this._cachedUAng &&
  26523. this.vAng === this._cachedVAng &&
  26524. this.wAng === this._cachedWAng) {
  26525. return this._cachedTextureMatrix;
  26526. }
  26527. this._cachedUOffset = this.uOffset;
  26528. this._cachedVOffset = this.vOffset;
  26529. this._cachedUScale = this.uScale;
  26530. this._cachedVScale = this.vScale;
  26531. this._cachedUAng = this.uAng;
  26532. this._cachedVAng = this.vAng;
  26533. this._cachedWAng = this.wAng;
  26534. if (!this._cachedTextureMatrix) {
  26535. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26536. this._rowGenerationMatrix = new BABYLON.Matrix();
  26537. this._t0 = BABYLON.Vector3.Zero();
  26538. this._t1 = BABYLON.Vector3.Zero();
  26539. this._t2 = BABYLON.Vector3.Zero();
  26540. }
  26541. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26542. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26543. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26544. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26545. this._t1.subtractInPlace(this._t0);
  26546. this._t2.subtractInPlace(this._t0);
  26547. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26548. this._cachedTextureMatrix.m[0] = this._t1.x;
  26549. this._cachedTextureMatrix.m[1] = this._t1.y;
  26550. this._cachedTextureMatrix.m[2] = this._t1.z;
  26551. this._cachedTextureMatrix.m[4] = this._t2.x;
  26552. this._cachedTextureMatrix.m[5] = this._t2.y;
  26553. this._cachedTextureMatrix.m[6] = this._t2.z;
  26554. this._cachedTextureMatrix.m[8] = this._t0.x;
  26555. this._cachedTextureMatrix.m[9] = this._t0.y;
  26556. this._cachedTextureMatrix.m[10] = this._t0.z;
  26557. var scene = this.getScene();
  26558. if (!scene) {
  26559. return this._cachedTextureMatrix;
  26560. }
  26561. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26562. return mat.hasTexture(_this);
  26563. });
  26564. return this._cachedTextureMatrix;
  26565. };
  26566. Texture.prototype.getReflectionTextureMatrix = function () {
  26567. var _this = this;
  26568. var scene = this.getScene();
  26569. if (!scene) {
  26570. return this._cachedTextureMatrix;
  26571. }
  26572. if (this.uOffset === this._cachedUOffset &&
  26573. this.vOffset === this._cachedVOffset &&
  26574. this.uScale === this._cachedUScale &&
  26575. this.vScale === this._cachedVScale &&
  26576. this.coordinatesMode === this._cachedCoordinatesMode) {
  26577. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26578. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26579. return this._cachedTextureMatrix;
  26580. }
  26581. }
  26582. else {
  26583. return this._cachedTextureMatrix;
  26584. }
  26585. }
  26586. if (!this._cachedTextureMatrix) {
  26587. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26588. }
  26589. if (!this._projectionModeMatrix) {
  26590. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26591. }
  26592. this._cachedUOffset = this.uOffset;
  26593. this._cachedVOffset = this.vOffset;
  26594. this._cachedUScale = this.uScale;
  26595. this._cachedVScale = this.vScale;
  26596. this._cachedCoordinatesMode = this.coordinatesMode;
  26597. switch (this.coordinatesMode) {
  26598. case Texture.PLANAR_MODE:
  26599. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26600. this._cachedTextureMatrix[0] = this.uScale;
  26601. this._cachedTextureMatrix[5] = this.vScale;
  26602. this._cachedTextureMatrix[12] = this.uOffset;
  26603. this._cachedTextureMatrix[13] = this.vOffset;
  26604. break;
  26605. case Texture.PROJECTION_MODE:
  26606. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26607. this._projectionModeMatrix.m[0] = 0.5;
  26608. this._projectionModeMatrix.m[5] = -0.5;
  26609. this._projectionModeMatrix.m[10] = 0.0;
  26610. this._projectionModeMatrix.m[12] = 0.5;
  26611. this._projectionModeMatrix.m[13] = 0.5;
  26612. this._projectionModeMatrix.m[14] = 1.0;
  26613. this._projectionModeMatrix.m[15] = 1.0;
  26614. var projectionMatrix = scene.getProjectionMatrix();
  26615. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26616. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26617. break;
  26618. default:
  26619. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26620. break;
  26621. }
  26622. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26623. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26624. });
  26625. return this._cachedTextureMatrix;
  26626. };
  26627. Texture.prototype.clone = function () {
  26628. var _this = this;
  26629. return BABYLON.SerializationHelper.Clone(function () {
  26630. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26631. }, this);
  26632. };
  26633. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26634. get: function () {
  26635. if (!this._onLoadObservable) {
  26636. this._onLoadObservable = new BABYLON.Observable();
  26637. }
  26638. return this._onLoadObservable;
  26639. },
  26640. enumerable: true,
  26641. configurable: true
  26642. });
  26643. Texture.prototype.serialize = function () {
  26644. var serializationObject = _super.prototype.serialize.call(this);
  26645. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26646. serializationObject.base64String = this._buffer;
  26647. serializationObject.name = serializationObject.name.replace("data:", "");
  26648. }
  26649. return serializationObject;
  26650. };
  26651. Texture.prototype.getClassName = function () {
  26652. return "Texture";
  26653. };
  26654. Texture.prototype.dispose = function () {
  26655. _super.prototype.dispose.call(this);
  26656. if (this.onLoadObservable) {
  26657. this.onLoadObservable.clear();
  26658. this._onLoadObservable = null;
  26659. }
  26660. this._delayedOnLoad = null;
  26661. this._delayedOnError = null;
  26662. };
  26663. // Statics
  26664. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26665. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26666. if (onLoad === void 0) { onLoad = null; }
  26667. if (onError === void 0) { onError = null; }
  26668. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26669. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26670. };
  26671. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26672. if (parsedTexture.customType) {
  26673. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26674. // Update Sampling Mode
  26675. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26676. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26677. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26678. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26679. }
  26680. }
  26681. return parsedCustomTexture;
  26682. }
  26683. if (parsedTexture.isCube) {
  26684. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26685. }
  26686. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26687. return null;
  26688. }
  26689. var texture = BABYLON.SerializationHelper.Parse(function () {
  26690. var generateMipMaps = true;
  26691. if (parsedTexture.noMipmap) {
  26692. generateMipMaps = false;
  26693. }
  26694. if (parsedTexture.mirrorPlane) {
  26695. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26696. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26697. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26698. return mirrorTexture;
  26699. }
  26700. else if (parsedTexture.isRenderTarget) {
  26701. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26702. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26703. return renderTargetTexture;
  26704. }
  26705. else {
  26706. var texture;
  26707. if (parsedTexture.base64String) {
  26708. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26709. }
  26710. else {
  26711. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26712. }
  26713. return texture;
  26714. }
  26715. }, parsedTexture, scene);
  26716. // Update Sampling Mode
  26717. if (parsedTexture.samplingMode) {
  26718. var sampling = parsedTexture.samplingMode;
  26719. if (texture._samplingMode !== sampling) {
  26720. texture.updateSamplingMode(sampling);
  26721. }
  26722. }
  26723. // Animations
  26724. if (parsedTexture.animations) {
  26725. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26726. var parsedAnimation = parsedTexture.animations[animationIndex];
  26727. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26728. }
  26729. }
  26730. return texture;
  26731. };
  26732. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26733. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26734. if (noMipmap === void 0) { noMipmap = false; }
  26735. if (invertY === void 0) { invertY = true; }
  26736. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26737. if (onLoad === void 0) { onLoad = null; }
  26738. if (onError === void 0) { onError = null; }
  26739. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26740. if (name.substr(0, 5) !== "data:") {
  26741. name = "data:" + name;
  26742. }
  26743. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26744. };
  26745. // Constants
  26746. Texture.NEAREST_SAMPLINGMODE = 1;
  26747. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26748. Texture.BILINEAR_SAMPLINGMODE = 2;
  26749. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26750. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26751. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26752. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26753. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26754. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26755. Texture.NEAREST_LINEAR = 7;
  26756. Texture.NEAREST_NEAREST = 8;
  26757. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26758. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26759. Texture.LINEAR_LINEAR = 11;
  26760. Texture.LINEAR_NEAREST = 12;
  26761. Texture.EXPLICIT_MODE = 0;
  26762. Texture.SPHERICAL_MODE = 1;
  26763. Texture.PLANAR_MODE = 2;
  26764. Texture.CUBIC_MODE = 3;
  26765. Texture.PROJECTION_MODE = 4;
  26766. Texture.SKYBOX_MODE = 5;
  26767. Texture.INVCUBIC_MODE = 6;
  26768. Texture.EQUIRECTANGULAR_MODE = 7;
  26769. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26770. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26771. Texture.CLAMP_ADDRESSMODE = 0;
  26772. Texture.WRAP_ADDRESSMODE = 1;
  26773. Texture.MIRROR_ADDRESSMODE = 2;
  26774. __decorate([
  26775. BABYLON.serialize()
  26776. ], Texture.prototype, "url", void 0);
  26777. __decorate([
  26778. BABYLON.serialize()
  26779. ], Texture.prototype, "uOffset", void 0);
  26780. __decorate([
  26781. BABYLON.serialize()
  26782. ], Texture.prototype, "vOffset", void 0);
  26783. __decorate([
  26784. BABYLON.serialize()
  26785. ], Texture.prototype, "uScale", void 0);
  26786. __decorate([
  26787. BABYLON.serialize()
  26788. ], Texture.prototype, "vScale", void 0);
  26789. __decorate([
  26790. BABYLON.serialize()
  26791. ], Texture.prototype, "uAng", void 0);
  26792. __decorate([
  26793. BABYLON.serialize()
  26794. ], Texture.prototype, "vAng", void 0);
  26795. __decorate([
  26796. BABYLON.serialize()
  26797. ], Texture.prototype, "wAng", void 0);
  26798. __decorate([
  26799. BABYLON.serialize()
  26800. ], Texture.prototype, "isBlocking", null);
  26801. return Texture;
  26802. }(BABYLON.BaseTexture));
  26803. BABYLON.Texture = Texture;
  26804. })(BABYLON || (BABYLON = {}));
  26805. //# sourceMappingURL=babylon.texture.js.map
  26806. var BABYLON;
  26807. (function (BABYLON) {
  26808. var _InstancesBatch = /** @class */ (function () {
  26809. function _InstancesBatch() {
  26810. this.mustReturn = false;
  26811. this.visibleInstances = new Array();
  26812. this.renderSelf = new Array();
  26813. }
  26814. return _InstancesBatch;
  26815. }());
  26816. BABYLON._InstancesBatch = _InstancesBatch;
  26817. var Mesh = /** @class */ (function (_super) {
  26818. __extends(Mesh, _super);
  26819. /**
  26820. * @constructor
  26821. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26822. * @param {Scene} scene The scene to add this mesh to.
  26823. * @param {Node} parent The parent of this mesh, if it has one
  26824. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26825. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26826. * When false, achieved by calling a clone(), also passing False.
  26827. * This will make creation of children, recursive.
  26828. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26829. */
  26830. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26831. if (scene === void 0) { scene = null; }
  26832. if (parent === void 0) { parent = null; }
  26833. if (source === void 0) { source = null; }
  26834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26835. var _this = _super.call(this, name, scene) || this;
  26836. // Events
  26837. /**
  26838. * An event triggered before rendering the mesh
  26839. * @type {BABYLON.Observable}
  26840. */
  26841. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26842. /**
  26843. * An event triggered after rendering the mesh
  26844. * @type {BABYLON.Observable}
  26845. */
  26846. _this.onAfterRenderObservable = new BABYLON.Observable();
  26847. /**
  26848. * An event triggered before drawing the mesh
  26849. * @type {BABYLON.Observable}
  26850. */
  26851. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26852. // Members
  26853. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26854. _this.instances = new Array();
  26855. _this._LODLevels = new Array();
  26856. _this._visibleInstances = {};
  26857. _this._renderIdForInstances = new Array();
  26858. _this._batchCache = new _InstancesBatch();
  26859. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26860. // Use by builder only to know what orientation were the mesh build in.
  26861. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26862. _this.overrideMaterialSideOrientation = null;
  26863. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26864. // Will be used to save a source mesh reference, If any
  26865. _this._source = null;
  26866. scene = _this.getScene();
  26867. if (source) {
  26868. // Source mesh
  26869. _this._source = source;
  26870. // Geometry
  26871. if (source._geometry) {
  26872. source._geometry.applyToMesh(_this);
  26873. }
  26874. // Deep copy
  26875. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26876. // Metadata
  26877. if (source.metadata && source.metadata.clone) {
  26878. _this.metadata = source.metadata.clone();
  26879. }
  26880. else {
  26881. _this.metadata = source.metadata;
  26882. }
  26883. // Tags
  26884. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26885. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26886. }
  26887. // Parent
  26888. _this.parent = source.parent;
  26889. // Pivot
  26890. _this.setPivotMatrix(source.getPivotMatrix());
  26891. _this.id = name + "." + source.id;
  26892. // Material
  26893. _this.material = source.material;
  26894. var index;
  26895. if (!doNotCloneChildren) {
  26896. // Children
  26897. var directDescendants = source.getDescendants(true);
  26898. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26899. var child = directDescendants[index_1];
  26900. if (child.clone) {
  26901. child.clone(name + "." + child.name, _this);
  26902. }
  26903. }
  26904. }
  26905. // Physics clone
  26906. var physicsEngine = _this.getScene().getPhysicsEngine();
  26907. if (clonePhysicsImpostor && physicsEngine) {
  26908. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26909. if (impostor) {
  26910. _this.physicsImpostor = impostor.clone(_this);
  26911. }
  26912. }
  26913. // Particles
  26914. for (index = 0; index < scene.particleSystems.length; index++) {
  26915. var system = scene.particleSystems[index];
  26916. if (system.emitter === source) {
  26917. system.clone(system.name, _this);
  26918. }
  26919. }
  26920. _this.computeWorldMatrix(true);
  26921. }
  26922. // Parent
  26923. if (parent !== null) {
  26924. _this.parent = parent;
  26925. }
  26926. return _this;
  26927. }
  26928. Object.defineProperty(Mesh, "FRONTSIDE", {
  26929. /**
  26930. * Mesh side orientation : usually the external or front surface
  26931. */
  26932. get: function () {
  26933. return Mesh._FRONTSIDE;
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(Mesh, "BACKSIDE", {
  26939. /**
  26940. * Mesh side orientation : usually the internal or back surface
  26941. */
  26942. get: function () {
  26943. return Mesh._BACKSIDE;
  26944. },
  26945. enumerable: true,
  26946. configurable: true
  26947. });
  26948. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26949. /**
  26950. * Mesh side orientation : both internal and external or front and back surfaces
  26951. */
  26952. get: function () {
  26953. return Mesh._DOUBLESIDE;
  26954. },
  26955. enumerable: true,
  26956. configurable: true
  26957. });
  26958. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26959. /**
  26960. * Mesh side orientation : by default, `FRONTSIDE`
  26961. */
  26962. get: function () {
  26963. return Mesh._DEFAULTSIDE;
  26964. },
  26965. enumerable: true,
  26966. configurable: true
  26967. });
  26968. Object.defineProperty(Mesh, "NO_CAP", {
  26969. /**
  26970. * Mesh cap setting : no cap
  26971. */
  26972. get: function () {
  26973. return Mesh._NO_CAP;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. Object.defineProperty(Mesh, "CAP_START", {
  26979. /**
  26980. * Mesh cap setting : one cap at the beginning of the mesh
  26981. */
  26982. get: function () {
  26983. return Mesh._CAP_START;
  26984. },
  26985. enumerable: true,
  26986. configurable: true
  26987. });
  26988. Object.defineProperty(Mesh, "CAP_END", {
  26989. /**
  26990. * Mesh cap setting : one cap at the end of the mesh
  26991. */
  26992. get: function () {
  26993. return Mesh._CAP_END;
  26994. },
  26995. enumerable: true,
  26996. configurable: true
  26997. });
  26998. Object.defineProperty(Mesh, "CAP_ALL", {
  26999. /**
  27000. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27001. */
  27002. get: function () {
  27003. return Mesh._CAP_ALL;
  27004. },
  27005. enumerable: true,
  27006. configurable: true
  27007. });
  27008. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27009. set: function (callback) {
  27010. if (this._onBeforeDrawObserver) {
  27011. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27012. }
  27013. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27019. get: function () {
  27020. return this._morphTargetManager;
  27021. },
  27022. set: function (value) {
  27023. if (this._morphTargetManager === value) {
  27024. return;
  27025. }
  27026. this._morphTargetManager = value;
  27027. this._syncGeometryWithMorphTargetManager();
  27028. },
  27029. enumerable: true,
  27030. configurable: true
  27031. });
  27032. Object.defineProperty(Mesh.prototype, "source", {
  27033. get: function () {
  27034. return this._source;
  27035. },
  27036. enumerable: true,
  27037. configurable: true
  27038. });
  27039. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27040. get: function () {
  27041. return this._unIndexed;
  27042. },
  27043. set: function (value) {
  27044. if (this._unIndexed !== value) {
  27045. this._unIndexed = value;
  27046. this._markSubMeshesAsAttributesDirty();
  27047. }
  27048. },
  27049. enumerable: true,
  27050. configurable: true
  27051. });
  27052. // Methods
  27053. /**
  27054. * Returns the string "Mesh".
  27055. */
  27056. Mesh.prototype.getClassName = function () {
  27057. return "Mesh";
  27058. };
  27059. /**
  27060. * Returns a string.
  27061. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27062. */
  27063. Mesh.prototype.toString = function (fullDetails) {
  27064. var ret = _super.prototype.toString.call(this, fullDetails);
  27065. ret += ", n vertices: " + this.getTotalVertices();
  27066. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27067. if (this.animations) {
  27068. for (var i = 0; i < this.animations.length; i++) {
  27069. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27070. }
  27071. }
  27072. if (fullDetails) {
  27073. if (this._geometry) {
  27074. var ib = this.getIndices();
  27075. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27076. if (vb && ib) {
  27077. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27078. }
  27079. }
  27080. else {
  27081. ret += ", flat shading: UNKNOWN";
  27082. }
  27083. }
  27084. return ret;
  27085. };
  27086. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27087. /**
  27088. * True if the mesh has some Levels Of Details (LOD).
  27089. * Returns a boolean.
  27090. */
  27091. get: function () {
  27092. return this._LODLevels.length > 0;
  27093. },
  27094. enumerable: true,
  27095. configurable: true
  27096. });
  27097. /**
  27098. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27099. * @returns an array of {BABYLON.MeshLODLevel}
  27100. */
  27101. Mesh.prototype.getLODLevels = function () {
  27102. return this._LODLevels;
  27103. };
  27104. Mesh.prototype._sortLODLevels = function () {
  27105. this._LODLevels.sort(function (a, b) {
  27106. if (a.distance < b.distance) {
  27107. return 1;
  27108. }
  27109. if (a.distance > b.distance) {
  27110. return -1;
  27111. }
  27112. return 0;
  27113. });
  27114. };
  27115. /**
  27116. * Add a mesh as LOD level triggered at the given distance.
  27117. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27118. * @param {number} distance The distance from the center of the object to show this level
  27119. * @param {Mesh} mesh The mesh to be added as LOD level
  27120. * @return {Mesh} This mesh (for chaining)
  27121. */
  27122. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27123. if (mesh && mesh._masterMesh) {
  27124. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27125. return this;
  27126. }
  27127. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27128. this._LODLevels.push(level);
  27129. if (mesh) {
  27130. mesh._masterMesh = this;
  27131. }
  27132. this._sortLODLevels();
  27133. return this;
  27134. };
  27135. /**
  27136. * Returns the LOD level mesh at the passed distance or null if not found.
  27137. * It is related to the method `addLODLevel(distance, mesh)`.
  27138. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27139. * Returns an object Mesh or `null`.
  27140. */
  27141. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27142. for (var index = 0; index < this._LODLevels.length; index++) {
  27143. var level = this._LODLevels[index];
  27144. if (level.distance === distance) {
  27145. return level.mesh;
  27146. }
  27147. }
  27148. return null;
  27149. };
  27150. /**
  27151. * Remove a mesh from the LOD array
  27152. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27153. * @param {Mesh} mesh The mesh to be removed.
  27154. * @return {Mesh} This mesh (for chaining)
  27155. */
  27156. Mesh.prototype.removeLODLevel = function (mesh) {
  27157. for (var index = 0; index < this._LODLevels.length; index++) {
  27158. if (this._LODLevels[index].mesh === mesh) {
  27159. this._LODLevels.splice(index, 1);
  27160. if (mesh) {
  27161. mesh._masterMesh = null;
  27162. }
  27163. }
  27164. }
  27165. this._sortLODLevels();
  27166. return this;
  27167. };
  27168. /**
  27169. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27170. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27171. */
  27172. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27173. if (!this._LODLevels || this._LODLevels.length === 0) {
  27174. return this;
  27175. }
  27176. var bSphere;
  27177. if (boundingSphere) {
  27178. bSphere = boundingSphere;
  27179. }
  27180. else {
  27181. var boundingInfo = this.getBoundingInfo();
  27182. bSphere = boundingInfo.boundingSphere;
  27183. }
  27184. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27185. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27186. if (this.onLODLevelSelection) {
  27187. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27188. }
  27189. return this;
  27190. }
  27191. for (var index = 0; index < this._LODLevels.length; index++) {
  27192. var level = this._LODLevels[index];
  27193. if (level.distance < distanceToCamera) {
  27194. if (level.mesh) {
  27195. level.mesh._preActivate();
  27196. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27197. }
  27198. if (this.onLODLevelSelection) {
  27199. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27200. }
  27201. return level.mesh;
  27202. }
  27203. }
  27204. if (this.onLODLevelSelection) {
  27205. this.onLODLevelSelection(distanceToCamera, this, this);
  27206. }
  27207. return this;
  27208. };
  27209. Object.defineProperty(Mesh.prototype, "geometry", {
  27210. /**
  27211. * Returns the mesh internal Geometry object.
  27212. */
  27213. get: function () {
  27214. return this._geometry;
  27215. },
  27216. enumerable: true,
  27217. configurable: true
  27218. });
  27219. /**
  27220. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27221. */
  27222. Mesh.prototype.getTotalVertices = function () {
  27223. if (this._geometry === null || this._geometry === undefined) {
  27224. return 0;
  27225. }
  27226. return this._geometry.getTotalVertices();
  27227. };
  27228. /**
  27229. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27230. * 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.
  27231. * You can force the copy with forceCopy === true
  27232. * Returns null if the mesh has no geometry or no vertex buffer.
  27233. * Possible `kind` values :
  27234. * - BABYLON.VertexBuffer.PositionKind
  27235. * - BABYLON.VertexBuffer.UVKind
  27236. * - BABYLON.VertexBuffer.UV2Kind
  27237. * - BABYLON.VertexBuffer.UV3Kind
  27238. * - BABYLON.VertexBuffer.UV4Kind
  27239. * - BABYLON.VertexBuffer.UV5Kind
  27240. * - BABYLON.VertexBuffer.UV6Kind
  27241. * - BABYLON.VertexBuffer.ColorKind
  27242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27246. */
  27247. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27248. if (!this._geometry) {
  27249. return null;
  27250. }
  27251. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27252. };
  27253. /**
  27254. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27255. * Returns `null` if the mesh has no geometry.
  27256. * Possible `kind` values :
  27257. * - BABYLON.VertexBuffer.PositionKind
  27258. * - BABYLON.VertexBuffer.UVKind
  27259. * - BABYLON.VertexBuffer.UV2Kind
  27260. * - BABYLON.VertexBuffer.UV3Kind
  27261. * - BABYLON.VertexBuffer.UV4Kind
  27262. * - BABYLON.VertexBuffer.UV5Kind
  27263. * - BABYLON.VertexBuffer.UV6Kind
  27264. * - BABYLON.VertexBuffer.ColorKind
  27265. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27266. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27267. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27268. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27269. */
  27270. Mesh.prototype.getVertexBuffer = function (kind) {
  27271. if (!this._geometry) {
  27272. return null;
  27273. }
  27274. return this._geometry.getVertexBuffer(kind);
  27275. };
  27276. /**
  27277. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27278. * Possible `kind` values :
  27279. * - BABYLON.VertexBuffer.PositionKind
  27280. * - BABYLON.VertexBuffer.UVKind
  27281. * - BABYLON.VertexBuffer.UV2Kind
  27282. * - BABYLON.VertexBuffer.UV3Kind
  27283. * - BABYLON.VertexBuffer.UV4Kind
  27284. * - BABYLON.VertexBuffer.UV5Kind
  27285. * - BABYLON.VertexBuffer.UV6Kind
  27286. * - BABYLON.VertexBuffer.ColorKind
  27287. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27288. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27289. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27290. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27291. */
  27292. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27293. if (!this._geometry) {
  27294. if (this._delayInfo) {
  27295. return this._delayInfo.indexOf(kind) !== -1;
  27296. }
  27297. return false;
  27298. }
  27299. return this._geometry.isVerticesDataPresent(kind);
  27300. };
  27301. /**
  27302. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27303. * Possible `kind` values :
  27304. * - BABYLON.VertexBuffer.PositionKind
  27305. * - BABYLON.VertexBuffer.UVKind
  27306. * - BABYLON.VertexBuffer.UV2Kind
  27307. * - BABYLON.VertexBuffer.UV3Kind
  27308. * - BABYLON.VertexBuffer.UV4Kind
  27309. * - BABYLON.VertexBuffer.UV5Kind
  27310. * - BABYLON.VertexBuffer.UV6Kind
  27311. * - BABYLON.VertexBuffer.ColorKind
  27312. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27313. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27314. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27315. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27316. */
  27317. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27318. if (!this._geometry) {
  27319. if (this._delayInfo) {
  27320. return this._delayInfo.indexOf(kind) !== -1;
  27321. }
  27322. return false;
  27323. }
  27324. return this._geometry.isVertexBufferUpdatable(kind);
  27325. };
  27326. /**
  27327. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27328. * Possible `kind` values :
  27329. * - BABYLON.VertexBuffer.PositionKind
  27330. * - BABYLON.VertexBuffer.UVKind
  27331. * - BABYLON.VertexBuffer.UV2Kind
  27332. * - BABYLON.VertexBuffer.UV3Kind
  27333. * - BABYLON.VertexBuffer.UV4Kind
  27334. * - BABYLON.VertexBuffer.UV5Kind
  27335. * - BABYLON.VertexBuffer.UV6Kind
  27336. * - BABYLON.VertexBuffer.ColorKind
  27337. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27338. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27339. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27340. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27341. */
  27342. Mesh.prototype.getVerticesDataKinds = function () {
  27343. if (!this._geometry) {
  27344. var result = new Array();
  27345. if (this._delayInfo) {
  27346. this._delayInfo.forEach(function (kind, index, array) {
  27347. result.push(kind);
  27348. });
  27349. }
  27350. return result;
  27351. }
  27352. return this._geometry.getVerticesDataKinds();
  27353. };
  27354. /**
  27355. * Returns a positive integer : the total number of indices in this mesh geometry.
  27356. * Returns zero if the mesh has no geometry.
  27357. */
  27358. Mesh.prototype.getTotalIndices = function () {
  27359. if (!this._geometry) {
  27360. return 0;
  27361. }
  27362. return this._geometry.getTotalIndices();
  27363. };
  27364. /**
  27365. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27366. * 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.
  27367. * Returns an empty array if the mesh has no geometry.
  27368. */
  27369. Mesh.prototype.getIndices = function (copyWhenShared) {
  27370. if (!this._geometry) {
  27371. return [];
  27372. }
  27373. return this._geometry.getIndices(copyWhenShared);
  27374. };
  27375. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27376. get: function () {
  27377. return this._masterMesh !== null && this._masterMesh !== undefined;
  27378. },
  27379. enumerable: true,
  27380. configurable: true
  27381. });
  27382. /**
  27383. * Determine if the current mesh is ready to be rendered
  27384. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27385. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27386. * @returns true if all associated assets are ready (material, textures, shaders)
  27387. */
  27388. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27389. if (completeCheck === void 0) { completeCheck = false; }
  27390. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27391. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27392. return false;
  27393. }
  27394. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27395. return false;
  27396. }
  27397. if (!this.subMeshes || this.subMeshes.length === 0) {
  27398. return true;
  27399. }
  27400. if (!completeCheck) {
  27401. return true;
  27402. }
  27403. var engine = this.getEngine();
  27404. var scene = this.getScene();
  27405. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27406. this.computeWorldMatrix();
  27407. var mat = this.material || scene.defaultMaterial;
  27408. if (mat) {
  27409. if (mat.storeEffectOnSubMeshes) {
  27410. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27411. var subMesh = _a[_i];
  27412. var effectiveMaterial = subMesh.getMaterial();
  27413. if (effectiveMaterial) {
  27414. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27415. return false;
  27416. }
  27417. }
  27418. }
  27419. }
  27420. else {
  27421. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27422. return false;
  27423. }
  27424. }
  27425. }
  27426. // Shadows
  27427. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27428. var light = _c[_b];
  27429. var generator = light.getShadowGenerator();
  27430. if (generator) {
  27431. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27432. var subMesh = _e[_d];
  27433. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27434. return false;
  27435. }
  27436. }
  27437. }
  27438. }
  27439. // LOD
  27440. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27441. var lod = _g[_f];
  27442. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27443. return false;
  27444. }
  27445. }
  27446. return true;
  27447. };
  27448. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27449. /**
  27450. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27451. * This property is pertinent only for updatable parametric shapes.
  27452. */
  27453. get: function () {
  27454. return this._areNormalsFrozen;
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. /**
  27460. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27461. * It has no effect at all on other shapes.
  27462. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27463. * Returns the Mesh.
  27464. */
  27465. Mesh.prototype.freezeNormals = function () {
  27466. this._areNormalsFrozen = true;
  27467. return this;
  27468. };
  27469. /**
  27470. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27471. * It has no effect at all on other shapes.
  27472. * It reactivates the mesh normals computation if it was previously frozen.
  27473. * Returns the Mesh.
  27474. */
  27475. Mesh.prototype.unfreezeNormals = function () {
  27476. this._areNormalsFrozen = false;
  27477. return this;
  27478. };
  27479. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27480. /**
  27481. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27482. */
  27483. set: function (count) {
  27484. this._overridenInstanceCount = count;
  27485. },
  27486. enumerable: true,
  27487. configurable: true
  27488. });
  27489. // Methods
  27490. Mesh.prototype._preActivate = function () {
  27491. var sceneRenderId = this.getScene().getRenderId();
  27492. if (this._preActivateId === sceneRenderId) {
  27493. return this;
  27494. }
  27495. this._preActivateId = sceneRenderId;
  27496. this._visibleInstances = null;
  27497. return this;
  27498. };
  27499. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27500. if (this._visibleInstances) {
  27501. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27502. }
  27503. return this;
  27504. };
  27505. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27506. if (!this._visibleInstances) {
  27507. this._visibleInstances = {};
  27508. this._visibleInstances.defaultRenderId = renderId;
  27509. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27510. }
  27511. if (!this._visibleInstances[renderId]) {
  27512. this._visibleInstances[renderId] = new Array();
  27513. }
  27514. this._visibleInstances[renderId].push(instance);
  27515. return this;
  27516. };
  27517. /**
  27518. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27519. * This means the mesh underlying bounding box and sphere are recomputed.
  27520. * Returns the Mesh.
  27521. */
  27522. Mesh.prototype.refreshBoundingInfo = function () {
  27523. return this._refreshBoundingInfo(false);
  27524. };
  27525. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27526. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27527. return this;
  27528. }
  27529. var data = this._getPositionData(applySkeleton);
  27530. if (data) {
  27531. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27532. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27533. }
  27534. if (this.subMeshes) {
  27535. for (var index = 0; index < this.subMeshes.length; index++) {
  27536. this.subMeshes[index].refreshBoundingInfo();
  27537. }
  27538. }
  27539. this._updateBoundingInfo();
  27540. return this;
  27541. };
  27542. Mesh.prototype._getPositionData = function (applySkeleton) {
  27543. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27544. if (data && applySkeleton && this.skeleton) {
  27545. data = BABYLON.Tools.Slice(data);
  27546. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27547. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27548. if (matricesWeightsData && matricesIndicesData) {
  27549. var needExtras = this.numBoneInfluencers > 4;
  27550. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27551. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27552. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27553. var tempVector = BABYLON.Tmp.Vector3[0];
  27554. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27555. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27556. var matWeightIdx = 0;
  27557. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27558. finalMatrix.reset();
  27559. var inf;
  27560. var weight;
  27561. for (inf = 0; inf < 4; inf++) {
  27562. weight = matricesWeightsData[matWeightIdx + inf];
  27563. if (weight <= 0)
  27564. break;
  27565. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27566. finalMatrix.addToSelf(tempMatrix);
  27567. }
  27568. if (needExtras) {
  27569. for (inf = 0; inf < 4; inf++) {
  27570. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27571. if (weight <= 0)
  27572. break;
  27573. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27574. finalMatrix.addToSelf(tempMatrix);
  27575. }
  27576. }
  27577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27578. tempVector.toArray(data, index);
  27579. }
  27580. }
  27581. }
  27582. return data;
  27583. };
  27584. Mesh.prototype._createGlobalSubMesh = function (force) {
  27585. var totalVertices = this.getTotalVertices();
  27586. if (!totalVertices || !this.getIndices()) {
  27587. return null;
  27588. }
  27589. // Check if we need to recreate the submeshes
  27590. if (this.subMeshes && this.subMeshes.length > 0) {
  27591. var ib = this.getIndices();
  27592. if (!ib) {
  27593. return null;
  27594. }
  27595. var totalIndices = ib.length;
  27596. var needToRecreate = false;
  27597. if (force) {
  27598. needToRecreate = true;
  27599. }
  27600. else {
  27601. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27602. var submesh = _a[_i];
  27603. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27604. needToRecreate = true;
  27605. break;
  27606. }
  27607. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27608. needToRecreate = true;
  27609. break;
  27610. }
  27611. }
  27612. }
  27613. if (!needToRecreate) {
  27614. return this.subMeshes[0];
  27615. }
  27616. }
  27617. this.releaseSubMeshes();
  27618. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27619. };
  27620. Mesh.prototype.subdivide = function (count) {
  27621. if (count < 1) {
  27622. return;
  27623. }
  27624. var totalIndices = this.getTotalIndices();
  27625. var subdivisionSize = (totalIndices / count) | 0;
  27626. var offset = 0;
  27627. // Ensure that subdivisionSize is a multiple of 3
  27628. while (subdivisionSize % 3 !== 0) {
  27629. subdivisionSize++;
  27630. }
  27631. this.releaseSubMeshes();
  27632. for (var index = 0; index < count; index++) {
  27633. if (offset >= totalIndices) {
  27634. break;
  27635. }
  27636. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27637. offset += subdivisionSize;
  27638. }
  27639. this.synchronizeInstances();
  27640. };
  27641. /**
  27642. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27643. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27644. * The `data` are either a numeric array either a Float32Array.
  27645. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27646. * 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).
  27647. * Note that a new underlying VertexBuffer object is created each call.
  27648. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27649. *
  27650. * Possible `kind` values :
  27651. * - BABYLON.VertexBuffer.PositionKind
  27652. * - BABYLON.VertexBuffer.UVKind
  27653. * - BABYLON.VertexBuffer.UV2Kind
  27654. * - BABYLON.VertexBuffer.UV3Kind
  27655. * - BABYLON.VertexBuffer.UV4Kind
  27656. * - BABYLON.VertexBuffer.UV5Kind
  27657. * - BABYLON.VertexBuffer.UV6Kind
  27658. * - BABYLON.VertexBuffer.ColorKind
  27659. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27660. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27661. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27662. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27663. *
  27664. * Returns the Mesh.
  27665. */
  27666. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27667. if (updatable === void 0) { updatable = false; }
  27668. if (!this._geometry) {
  27669. var vertexData = new BABYLON.VertexData();
  27670. vertexData.set(data, kind);
  27671. var scene = this.getScene();
  27672. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27673. }
  27674. else {
  27675. this._geometry.setVerticesData(kind, data, updatable, stride);
  27676. }
  27677. return this;
  27678. };
  27679. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27680. if (updatable === void 0) { updatable = true; }
  27681. var vb = this.getVertexBuffer(kind);
  27682. if (!vb || vb.isUpdatable() === updatable) {
  27683. return;
  27684. }
  27685. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27686. };
  27687. /**
  27688. * Sets the mesh VertexBuffer.
  27689. * Returns the Mesh.
  27690. */
  27691. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27692. if (!this._geometry) {
  27693. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27694. }
  27695. this._geometry.setVerticesBuffer(buffer);
  27696. return this;
  27697. };
  27698. /**
  27699. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27700. * If the mesh has no geometry, it is simply returned as it is.
  27701. * The `data` are either a numeric array either a Float32Array.
  27702. * No new underlying VertexBuffer object is created.
  27703. * 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.
  27704. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27705. *
  27706. * Possible `kind` values :
  27707. * - BABYLON.VertexBuffer.PositionKind
  27708. * - BABYLON.VertexBuffer.UVKind
  27709. * - BABYLON.VertexBuffer.UV2Kind
  27710. * - BABYLON.VertexBuffer.UV3Kind
  27711. * - BABYLON.VertexBuffer.UV4Kind
  27712. * - BABYLON.VertexBuffer.UV5Kind
  27713. * - BABYLON.VertexBuffer.UV6Kind
  27714. * - BABYLON.VertexBuffer.ColorKind
  27715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27719. *
  27720. * Returns the Mesh.
  27721. */
  27722. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27723. if (!this._geometry) {
  27724. return this;
  27725. }
  27726. if (!makeItUnique) {
  27727. this._geometry.updateVerticesData(kind, data, updateExtends);
  27728. }
  27729. else {
  27730. this.makeGeometryUnique();
  27731. this.updateVerticesData(kind, data, updateExtends, false);
  27732. }
  27733. return this;
  27734. };
  27735. /**
  27736. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27737. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27738. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27739. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27740. * Returns the Mesh.
  27741. */
  27742. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27743. if (computeNormals === void 0) { computeNormals = true; }
  27744. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27745. if (!positions) {
  27746. return this;
  27747. }
  27748. positionFunction(positions);
  27749. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27750. if (computeNormals) {
  27751. var indices = this.getIndices();
  27752. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27753. if (!normals) {
  27754. return this;
  27755. }
  27756. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27757. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27758. }
  27759. return this;
  27760. };
  27761. /**
  27762. * Creates a un-shared specific occurence of the geometry for the mesh.
  27763. * Returns the Mesh.
  27764. */
  27765. Mesh.prototype.makeGeometryUnique = function () {
  27766. if (!this._geometry) {
  27767. return this;
  27768. }
  27769. var oldGeometry = this._geometry;
  27770. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27771. oldGeometry.releaseForMesh(this, true);
  27772. geometry.applyToMesh(this);
  27773. return this;
  27774. };
  27775. /**
  27776. * Sets the mesh indices.
  27777. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27778. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27779. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27780. * This method creates a new index buffer each call.
  27781. * Returns the Mesh.
  27782. */
  27783. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27784. if (totalVertices === void 0) { totalVertices = null; }
  27785. if (updatable === void 0) { updatable = false; }
  27786. if (!this._geometry) {
  27787. var vertexData = new BABYLON.VertexData();
  27788. vertexData.indices = indices;
  27789. var scene = this.getScene();
  27790. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27791. }
  27792. else {
  27793. this._geometry.setIndices(indices, totalVertices, updatable);
  27794. }
  27795. return this;
  27796. };
  27797. /**
  27798. * Update the current index buffer
  27799. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27800. * Returns the Mesh.
  27801. */
  27802. Mesh.prototype.updateIndices = function (indices, offset) {
  27803. if (!this._geometry) {
  27804. return this;
  27805. }
  27806. this._geometry.updateIndices(indices, offset);
  27807. return this;
  27808. };
  27809. /**
  27810. * Invert the geometry to move from a right handed system to a left handed one.
  27811. * Returns the Mesh.
  27812. */
  27813. Mesh.prototype.toLeftHanded = function () {
  27814. if (!this._geometry) {
  27815. return this;
  27816. }
  27817. this._geometry.toLeftHanded();
  27818. return this;
  27819. };
  27820. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27821. if (!this._geometry) {
  27822. return this;
  27823. }
  27824. var engine = this.getScene().getEngine();
  27825. // Wireframe
  27826. var indexToBind;
  27827. if (this._unIndexed) {
  27828. indexToBind = null;
  27829. }
  27830. else {
  27831. switch (fillMode) {
  27832. case BABYLON.Material.PointFillMode:
  27833. indexToBind = null;
  27834. break;
  27835. case BABYLON.Material.WireFrameFillMode:
  27836. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27837. break;
  27838. default:
  27839. case BABYLON.Material.TriangleFillMode:
  27840. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27841. break;
  27842. }
  27843. }
  27844. // VBOs
  27845. this._geometry._bind(effect, indexToBind);
  27846. return this;
  27847. };
  27848. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27849. if (alternate === void 0) { alternate = false; }
  27850. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27851. return this;
  27852. }
  27853. this.onBeforeDrawObservable.notifyObservers(this);
  27854. var scene = this.getScene();
  27855. var engine = scene.getEngine();
  27856. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27857. // or triangles as points
  27858. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27859. }
  27860. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27861. // Triangles as wireframe
  27862. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27863. }
  27864. else {
  27865. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27866. }
  27867. if (scene._isAlternateRenderingEnabled && !alternate) {
  27868. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27869. if (!effect || !scene.activeCamera) {
  27870. return this;
  27871. }
  27872. scene._switchToAlternateCameraConfiguration(true);
  27873. this._effectiveMaterial.bindView(effect);
  27874. this._effectiveMaterial.bindViewProjection(effect);
  27875. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27876. this._draw(subMesh, fillMode, instancesCount, true);
  27877. engine.setViewport(scene.activeCamera.viewport);
  27878. scene._switchToAlternateCameraConfiguration(false);
  27879. this._effectiveMaterial.bindView(effect);
  27880. this._effectiveMaterial.bindViewProjection(effect);
  27881. }
  27882. return this;
  27883. };
  27884. /**
  27885. * Registers for this mesh a javascript function called just before the rendering process.
  27886. * This function is passed the current mesh.
  27887. * Return the Mesh.
  27888. */
  27889. Mesh.prototype.registerBeforeRender = function (func) {
  27890. this.onBeforeRenderObservable.add(func);
  27891. return this;
  27892. };
  27893. /**
  27894. * Disposes a previously registered javascript function called before the rendering.
  27895. * This function is passed the current mesh.
  27896. * Returns the Mesh.
  27897. */
  27898. Mesh.prototype.unregisterBeforeRender = function (func) {
  27899. this.onBeforeRenderObservable.removeCallback(func);
  27900. return this;
  27901. };
  27902. /**
  27903. * Registers for this mesh a javascript function called just after the rendering is complete.
  27904. * This function is passed the current mesh.
  27905. * Returns the Mesh.
  27906. */
  27907. Mesh.prototype.registerAfterRender = function (func) {
  27908. this.onAfterRenderObservable.add(func);
  27909. return this;
  27910. };
  27911. /**
  27912. * Disposes a previously registered javascript function called after the rendering.
  27913. * This function is passed the current mesh.
  27914. * Return the Mesh.
  27915. */
  27916. Mesh.prototype.unregisterAfterRender = function (func) {
  27917. this.onAfterRenderObservable.removeCallback(func);
  27918. return this;
  27919. };
  27920. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27921. var scene = this.getScene();
  27922. this._batchCache.mustReturn = false;
  27923. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27924. this._batchCache.visibleInstances[subMeshId] = null;
  27925. if (this._visibleInstances) {
  27926. var currentRenderId = scene.getRenderId();
  27927. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27928. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27929. var selfRenderId = this._renderId;
  27930. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27931. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27932. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27933. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27934. }
  27935. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27936. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27937. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27938. this._batchCache.mustReturn = true;
  27939. return this._batchCache;
  27940. }
  27941. if (currentRenderId !== selfRenderId) {
  27942. this._batchCache.renderSelf[subMeshId] = false;
  27943. }
  27944. }
  27945. this._renderIdForInstances[subMeshId] = currentRenderId;
  27946. }
  27947. return this._batchCache;
  27948. };
  27949. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27950. var visibleInstances = batch.visibleInstances[subMesh._id];
  27951. if (!visibleInstances) {
  27952. return this;
  27953. }
  27954. var matricesCount = visibleInstances.length + 1;
  27955. var bufferSize = matricesCount * 16 * 4;
  27956. var currentInstancesBufferSize = this._instancesBufferSize;
  27957. var instancesBuffer = this._instancesBuffer;
  27958. while (this._instancesBufferSize < bufferSize) {
  27959. this._instancesBufferSize *= 2;
  27960. }
  27961. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27962. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27963. }
  27964. var offset = 0;
  27965. var instancesCount = 0;
  27966. var world = this.getWorldMatrix();
  27967. if (batch.renderSelf[subMesh._id]) {
  27968. world.copyToArray(this._instancesData, offset);
  27969. offset += 16;
  27970. instancesCount++;
  27971. }
  27972. if (visibleInstances) {
  27973. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27974. var instance = visibleInstances[instanceIndex];
  27975. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27976. offset += 16;
  27977. instancesCount++;
  27978. }
  27979. }
  27980. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27981. if (instancesBuffer) {
  27982. instancesBuffer.dispose();
  27983. }
  27984. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27985. this._instancesBuffer = instancesBuffer;
  27986. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27987. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27988. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27989. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27990. }
  27991. else {
  27992. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27993. }
  27994. this._bind(subMesh, effect, fillMode);
  27995. this._draw(subMesh, fillMode, instancesCount);
  27996. engine.unbindInstanceAttributes();
  27997. return this;
  27998. };
  27999. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28000. var scene = this.getScene();
  28001. var engine = scene.getEngine();
  28002. if (hardwareInstancedRendering) {
  28003. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28004. }
  28005. else {
  28006. if (batch.renderSelf[subMesh._id]) {
  28007. // Draw
  28008. if (onBeforeDraw) {
  28009. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28010. }
  28011. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28012. }
  28013. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28014. if (visibleInstancesForSubMesh) {
  28015. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28016. var instance = visibleInstancesForSubMesh[instanceIndex];
  28017. // World
  28018. var world = instance.getWorldMatrix();
  28019. if (onBeforeDraw) {
  28020. onBeforeDraw(true, world, effectiveMaterial);
  28021. }
  28022. // Draw
  28023. this._draw(subMesh, fillMode);
  28024. }
  28025. }
  28026. }
  28027. return this;
  28028. };
  28029. /**
  28030. * Triggers the draw call for the mesh.
  28031. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28032. * Returns the Mesh.
  28033. */
  28034. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28035. this.checkOcclusionQuery();
  28036. if (this._isOccluded) {
  28037. return this;
  28038. }
  28039. var scene = this.getScene();
  28040. // Managing instances
  28041. var batch = this._getInstancesRenderList(subMesh._id);
  28042. if (batch.mustReturn) {
  28043. return this;
  28044. }
  28045. // Checking geometry state
  28046. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28047. return this;
  28048. }
  28049. this.onBeforeRenderObservable.notifyObservers(this);
  28050. var engine = scene.getEngine();
  28051. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28052. // Material
  28053. var material = subMesh.getMaterial();
  28054. if (!material) {
  28055. return this;
  28056. }
  28057. this._effectiveMaterial = material;
  28058. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28059. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28060. return this;
  28061. }
  28062. }
  28063. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28064. return this;
  28065. }
  28066. // Alpha mode
  28067. if (enableAlphaMode) {
  28068. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28069. }
  28070. // Outline - step 1
  28071. var savedDepthWrite = engine.getDepthWrite();
  28072. if (this.renderOutline) {
  28073. engine.setDepthWrite(false);
  28074. scene.getOutlineRenderer().render(subMesh, batch);
  28075. engine.setDepthWrite(savedDepthWrite);
  28076. }
  28077. var effect;
  28078. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28079. effect = subMesh.effect;
  28080. }
  28081. else {
  28082. effect = this._effectiveMaterial.getEffect();
  28083. }
  28084. if (!effect) {
  28085. return this;
  28086. }
  28087. var sideOrientation = this.overrideMaterialSideOrientation;
  28088. if (sideOrientation == null) {
  28089. sideOrientation = this._effectiveMaterial.sideOrientation;
  28090. if (this._getWorldMatrixDeterminant() < 0) {
  28091. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28092. }
  28093. }
  28094. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28095. if (this._effectiveMaterial.forceDepthWrite) {
  28096. engine.setDepthWrite(true);
  28097. }
  28098. // Bind
  28099. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28100. if (!hardwareInstancedRendering) {
  28101. this._bind(subMesh, effect, fillMode);
  28102. }
  28103. var world = this.getWorldMatrix();
  28104. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28105. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28106. }
  28107. else {
  28108. this._effectiveMaterial.bind(world, this);
  28109. }
  28110. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28111. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28112. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28113. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28114. }
  28115. // Draw
  28116. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28117. // Unbind
  28118. this._effectiveMaterial.unbind();
  28119. // Outline - step 2
  28120. if (this.renderOutline && savedDepthWrite) {
  28121. engine.setDepthWrite(true);
  28122. engine.setColorWrite(false);
  28123. scene.getOutlineRenderer().render(subMesh, batch);
  28124. engine.setColorWrite(true);
  28125. }
  28126. // Overlay
  28127. if (this.renderOverlay) {
  28128. var currentMode = engine.getAlphaMode();
  28129. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28130. scene.getOutlineRenderer().render(subMesh, batch, true);
  28131. engine.setAlphaMode(currentMode);
  28132. }
  28133. this.onAfterRenderObservable.notifyObservers(this);
  28134. return this;
  28135. };
  28136. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28137. if (isInstance && effectiveMaterial) {
  28138. effectiveMaterial.bindOnlyWorldMatrix(world);
  28139. }
  28140. };
  28141. /**
  28142. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28143. */
  28144. Mesh.prototype.getEmittedParticleSystems = function () {
  28145. var results = new Array();
  28146. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28147. var particleSystem = this.getScene().particleSystems[index];
  28148. if (particleSystem.emitter === this) {
  28149. results.push(particleSystem);
  28150. }
  28151. }
  28152. return results;
  28153. };
  28154. /**
  28155. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28156. */
  28157. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28158. var results = new Array();
  28159. var descendants = this.getDescendants();
  28160. descendants.push(this);
  28161. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28162. var particleSystem = this.getScene().particleSystems[index];
  28163. var emitter = particleSystem.emitter;
  28164. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28165. results.push(particleSystem);
  28166. }
  28167. }
  28168. return results;
  28169. };
  28170. Mesh.prototype._checkDelayState = function () {
  28171. var scene = this.getScene();
  28172. if (this._geometry) {
  28173. this._geometry.load(scene);
  28174. }
  28175. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28177. this._queueLoad(scene);
  28178. }
  28179. return this;
  28180. };
  28181. Mesh.prototype._queueLoad = function (scene) {
  28182. var _this = this;
  28183. scene._addPendingData(this);
  28184. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28185. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28186. if (data instanceof ArrayBuffer) {
  28187. _this._delayLoadingFunction(data, _this);
  28188. }
  28189. else {
  28190. _this._delayLoadingFunction(JSON.parse(data), _this);
  28191. }
  28192. _this.instances.forEach(function (instance) {
  28193. instance._syncSubMeshes();
  28194. });
  28195. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28196. scene._removePendingData(_this);
  28197. }, function () { }, scene.database, getBinaryData);
  28198. return this;
  28199. };
  28200. /**
  28201. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28202. */
  28203. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28204. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28205. return false;
  28206. }
  28207. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28208. return false;
  28209. }
  28210. this._checkDelayState();
  28211. return true;
  28212. };
  28213. /**
  28214. * Sets the mesh material by the material or multiMaterial `id` property.
  28215. * The material `id` is a string identifying the material or the multiMaterial.
  28216. * This method returns the Mesh.
  28217. */
  28218. Mesh.prototype.setMaterialByID = function (id) {
  28219. var materials = this.getScene().materials;
  28220. var index;
  28221. for (index = materials.length - 1; index > -1; index--) {
  28222. if (materials[index].id === id) {
  28223. this.material = materials[index];
  28224. return this;
  28225. }
  28226. }
  28227. // Multi
  28228. var multiMaterials = this.getScene().multiMaterials;
  28229. for (index = multiMaterials.length - 1; index > -1; index--) {
  28230. if (multiMaterials[index].id === id) {
  28231. this.material = multiMaterials[index];
  28232. return this;
  28233. }
  28234. }
  28235. return this;
  28236. };
  28237. /**
  28238. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28239. */
  28240. Mesh.prototype.getAnimatables = function () {
  28241. var results = new Array();
  28242. if (this.material) {
  28243. results.push(this.material);
  28244. }
  28245. if (this.skeleton) {
  28246. results.push(this.skeleton);
  28247. }
  28248. return results;
  28249. };
  28250. /**
  28251. * Modifies the mesh geometry according to the passed transformation matrix.
  28252. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28253. * The mesh normals are modified accordingly the same transformation.
  28254. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28255. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28256. * Returns the Mesh.
  28257. */
  28258. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28259. // Position
  28260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28261. return this;
  28262. }
  28263. var submeshes = this.subMeshes.splice(0);
  28264. this._resetPointsArrayCache();
  28265. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28266. var temp = new Array();
  28267. var index;
  28268. for (index = 0; index < data.length; index += 3) {
  28269. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28270. }
  28271. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28272. // Normals
  28273. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28274. return this;
  28275. }
  28276. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28277. temp = [];
  28278. for (index = 0; index < data.length; index += 3) {
  28279. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28280. }
  28281. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28282. // flip faces?
  28283. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28284. this.flipFaces();
  28285. }
  28286. // Restore submeshes
  28287. this.releaseSubMeshes();
  28288. this.subMeshes = submeshes;
  28289. return this;
  28290. };
  28291. /**
  28292. * Modifies the mesh geometry according to its own current World Matrix.
  28293. * The mesh World Matrix is then reset.
  28294. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28295. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28296. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28297. * Returns the Mesh.
  28298. */
  28299. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28300. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28301. this.scaling.copyFromFloats(1, 1, 1);
  28302. this.position.copyFromFloats(0, 0, 0);
  28303. this.rotation.copyFromFloats(0, 0, 0);
  28304. //only if quaternion is already set
  28305. if (this.rotationQuaternion) {
  28306. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28307. }
  28308. this._worldMatrix = BABYLON.Matrix.Identity();
  28309. return this;
  28310. };
  28311. Object.defineProperty(Mesh.prototype, "_positions", {
  28312. // Cache
  28313. get: function () {
  28314. if (this._geometry) {
  28315. return this._geometry._positions;
  28316. }
  28317. return null;
  28318. },
  28319. enumerable: true,
  28320. configurable: true
  28321. });
  28322. Mesh.prototype._resetPointsArrayCache = function () {
  28323. if (this._geometry) {
  28324. this._geometry._resetPointsArrayCache();
  28325. }
  28326. return this;
  28327. };
  28328. Mesh.prototype._generatePointsArray = function () {
  28329. if (this._geometry) {
  28330. return this._geometry._generatePointsArray();
  28331. }
  28332. return false;
  28333. };
  28334. /**
  28335. * Returns a new Mesh object generated from the current mesh properties.
  28336. * This method must not get confused with createInstance().
  28337. * The parameter `name` is a string, the name given to the new mesh.
  28338. * The optional parameter `newParent` can be any Node object (default `null`).
  28339. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28340. * 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.
  28341. */
  28342. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28343. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28344. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28345. };
  28346. /**
  28347. * Disposes the Mesh.
  28348. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28349. * Returns nothing.
  28350. */
  28351. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28352. var _this = this;
  28353. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28354. this.morphTargetManager = null;
  28355. if (this._geometry) {
  28356. this._geometry.releaseForMesh(this, true);
  28357. }
  28358. // Sources
  28359. var meshes = this.getScene().meshes;
  28360. meshes.forEach(function (abstractMesh) {
  28361. var mesh = abstractMesh;
  28362. if (mesh._source && mesh._source === _this) {
  28363. mesh._source = null;
  28364. }
  28365. });
  28366. this._source = null;
  28367. // Instances
  28368. if (this._instancesBuffer) {
  28369. this._instancesBuffer.dispose();
  28370. this._instancesBuffer = null;
  28371. }
  28372. while (this.instances.length) {
  28373. this.instances[0].dispose();
  28374. }
  28375. // Effect layers.
  28376. var effectLayers = this.getScene().effectLayers;
  28377. for (var i = 0; i < effectLayers.length; i++) {
  28378. var effectLayer = effectLayers[i];
  28379. if (effectLayer) {
  28380. effectLayer._disposeMesh(this);
  28381. }
  28382. }
  28383. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28384. };
  28385. /**
  28386. * Modifies the mesh geometry according to a displacement map.
  28387. * 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.
  28388. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28389. * This method returns nothing.
  28390. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28391. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28392. * 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.
  28393. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28394. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28395. *
  28396. * Returns the Mesh.
  28397. */
  28398. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28399. var _this = this;
  28400. var scene = this.getScene();
  28401. var onload = function (img) {
  28402. // Getting height map data
  28403. var canvas = document.createElement("canvas");
  28404. var context = canvas.getContext("2d");
  28405. var heightMapWidth = img.width;
  28406. var heightMapHeight = img.height;
  28407. canvas.width = heightMapWidth;
  28408. canvas.height = heightMapHeight;
  28409. context.drawImage(img, 0, 0);
  28410. // Create VertexData from map data
  28411. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28412. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28413. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28414. //execute success callback, if set
  28415. if (onSuccess) {
  28416. onSuccess(_this);
  28417. }
  28418. };
  28419. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28420. return this;
  28421. };
  28422. /**
  28423. * Modifies the mesh geometry according to a displacementMap buffer.
  28424. * 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.
  28425. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28426. * This method returns nothing.
  28427. * 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.
  28428. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28429. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28430. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28431. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28432. *
  28433. * Returns the Mesh.
  28434. */
  28435. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28436. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28437. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28438. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28439. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28440. return this;
  28441. }
  28442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28443. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28444. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28445. var position = BABYLON.Vector3.Zero();
  28446. var normal = BABYLON.Vector3.Zero();
  28447. var uv = BABYLON.Vector2.Zero();
  28448. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28449. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28450. for (var index = 0; index < positions.length; index += 3) {
  28451. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28452. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28453. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28454. // Compute height
  28455. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28456. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28457. var pos = (u + v * heightMapWidth) * 4;
  28458. var r = buffer[pos] / 255.0;
  28459. var g = buffer[pos + 1] / 255.0;
  28460. var b = buffer[pos + 2] / 255.0;
  28461. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28462. normal.normalize();
  28463. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28464. position = position.add(normal);
  28465. position.toArray(positions, index);
  28466. }
  28467. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28468. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28469. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28470. return this;
  28471. };
  28472. /**
  28473. * Modify the mesh to get a flat shading rendering.
  28474. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28475. * This method returns the Mesh.
  28476. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28477. */
  28478. Mesh.prototype.convertToFlatShadedMesh = function () {
  28479. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28480. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28481. var kinds = this.getVerticesDataKinds();
  28482. var vbs = {};
  28483. var data = {};
  28484. var newdata = {};
  28485. var updatableNormals = false;
  28486. var kindIndex;
  28487. var kind;
  28488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28489. kind = kinds[kindIndex];
  28490. var vertexBuffer = this.getVertexBuffer(kind);
  28491. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28492. updatableNormals = vertexBuffer.isUpdatable();
  28493. kinds.splice(kindIndex, 1);
  28494. kindIndex--;
  28495. continue;
  28496. }
  28497. vbs[kind] = vertexBuffer;
  28498. data[kind] = vbs[kind].getData();
  28499. newdata[kind] = [];
  28500. }
  28501. // Save previous submeshes
  28502. var previousSubmeshes = this.subMeshes.slice(0);
  28503. var indices = this.getIndices();
  28504. var totalIndices = this.getTotalIndices();
  28505. // Generating unique vertices per face
  28506. var index;
  28507. for (index = 0; index < totalIndices; index++) {
  28508. var vertexIndex = indices[index];
  28509. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28510. kind = kinds[kindIndex];
  28511. var stride = vbs[kind].getStrideSize();
  28512. for (var offset = 0; offset < stride; offset++) {
  28513. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28514. }
  28515. }
  28516. }
  28517. // Updating faces & normal
  28518. var normals = [];
  28519. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28520. for (index = 0; index < totalIndices; index += 3) {
  28521. indices[index] = index;
  28522. indices[index + 1] = index + 1;
  28523. indices[index + 2] = index + 2;
  28524. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28525. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28526. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28527. var p1p2 = p1.subtract(p2);
  28528. var p3p2 = p3.subtract(p2);
  28529. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28530. // Store same normals for every vertex
  28531. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28532. normals.push(normal.x);
  28533. normals.push(normal.y);
  28534. normals.push(normal.z);
  28535. }
  28536. }
  28537. this.setIndices(indices);
  28538. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28539. // Updating vertex buffers
  28540. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28541. kind = kinds[kindIndex];
  28542. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28543. }
  28544. // Updating submeshes
  28545. this.releaseSubMeshes();
  28546. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28547. var previousOne = previousSubmeshes[submeshIndex];
  28548. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28549. }
  28550. this.synchronizeInstances();
  28551. return this;
  28552. };
  28553. /**
  28554. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28555. * In other words, more vertices, no more indices and a single bigger VBO.
  28556. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28557. * Returns the Mesh.
  28558. */
  28559. Mesh.prototype.convertToUnIndexedMesh = function () {
  28560. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28561. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28562. var kinds = this.getVerticesDataKinds();
  28563. var vbs = {};
  28564. var data = {};
  28565. var newdata = {};
  28566. var kindIndex;
  28567. var kind;
  28568. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28569. kind = kinds[kindIndex];
  28570. var vertexBuffer = this.getVertexBuffer(kind);
  28571. vbs[kind] = vertexBuffer;
  28572. data[kind] = vbs[kind].getData();
  28573. newdata[kind] = [];
  28574. }
  28575. // Save previous submeshes
  28576. var previousSubmeshes = this.subMeshes.slice(0);
  28577. var indices = this.getIndices();
  28578. var totalIndices = this.getTotalIndices();
  28579. // Generating unique vertices per face
  28580. var index;
  28581. for (index = 0; index < totalIndices; index++) {
  28582. var vertexIndex = indices[index];
  28583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28584. kind = kinds[kindIndex];
  28585. var stride = vbs[kind].getStrideSize();
  28586. for (var offset = 0; offset < stride; offset++) {
  28587. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28588. }
  28589. }
  28590. }
  28591. // Updating indices
  28592. for (index = 0; index < totalIndices; index += 3) {
  28593. indices[index] = index;
  28594. indices[index + 1] = index + 1;
  28595. indices[index + 2] = index + 2;
  28596. }
  28597. this.setIndices(indices);
  28598. // Updating vertex buffers
  28599. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28600. kind = kinds[kindIndex];
  28601. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28602. }
  28603. // Updating submeshes
  28604. this.releaseSubMeshes();
  28605. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28606. var previousOne = previousSubmeshes[submeshIndex];
  28607. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28608. }
  28609. this._unIndexed = true;
  28610. this.synchronizeInstances();
  28611. return this;
  28612. };
  28613. /**
  28614. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28615. * This method returns the Mesh.
  28616. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28617. */
  28618. Mesh.prototype.flipFaces = function (flipNormals) {
  28619. if (flipNormals === void 0) { flipNormals = false; }
  28620. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28621. var i;
  28622. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28623. for (i = 0; i < vertex_data.normals.length; i++) {
  28624. vertex_data.normals[i] *= -1;
  28625. }
  28626. }
  28627. if (vertex_data.indices) {
  28628. var temp;
  28629. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28630. // reassign indices
  28631. temp = vertex_data.indices[i + 1];
  28632. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28633. vertex_data.indices[i + 2] = temp;
  28634. }
  28635. }
  28636. vertex_data.applyToMesh(this);
  28637. return this;
  28638. };
  28639. // Instances
  28640. /**
  28641. * Creates a new InstancedMesh object from the mesh model.
  28642. * An instance shares the same properties and the same material than its model.
  28643. * Only these properties of each instance can then be set individually :
  28644. * - position
  28645. * - rotation
  28646. * - rotationQuaternion
  28647. * - setPivotMatrix
  28648. * - scaling
  28649. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28650. * Warning : this method is not supported for Line mesh and LineSystem
  28651. */
  28652. Mesh.prototype.createInstance = function (name) {
  28653. return new BABYLON.InstancedMesh(name, this);
  28654. };
  28655. /**
  28656. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28657. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28658. * This method returns the Mesh.
  28659. */
  28660. Mesh.prototype.synchronizeInstances = function () {
  28661. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28662. var instance = this.instances[instanceIndex];
  28663. instance._syncSubMeshes();
  28664. }
  28665. return this;
  28666. };
  28667. /**
  28668. * Simplify the mesh according to the given array of settings.
  28669. * Function will return immediately and will simplify async. It returns the Mesh.
  28670. * @param settings a collection of simplification settings.
  28671. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28672. * @param type the type of simplification to run.
  28673. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28674. */
  28675. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28677. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28678. this.getScene().simplificationQueue.addTask({
  28679. settings: settings,
  28680. parallelProcessing: parallelProcessing,
  28681. mesh: this,
  28682. simplificationType: simplificationType,
  28683. successCallback: successCallback
  28684. });
  28685. return this;
  28686. };
  28687. /**
  28688. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28689. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28690. * This should be used together with the simplification to avoid disappearing triangles.
  28691. * Returns the Mesh.
  28692. * @param successCallback an optional success callback to be called after the optimization finished.
  28693. */
  28694. Mesh.prototype.optimizeIndices = function (successCallback) {
  28695. var _this = this;
  28696. var indices = this.getIndices();
  28697. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28698. if (!positions || !indices) {
  28699. return this;
  28700. }
  28701. var vectorPositions = new Array();
  28702. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28703. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28704. }
  28705. var dupes = new Array();
  28706. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28707. var realPos = vectorPositions.length - 1 - iteration;
  28708. var testedPosition = vectorPositions[realPos];
  28709. for (var j = 0; j < realPos; ++j) {
  28710. var againstPosition = vectorPositions[j];
  28711. if (testedPosition.equals(againstPosition)) {
  28712. dupes[realPos] = j;
  28713. break;
  28714. }
  28715. }
  28716. }, function () {
  28717. for (var i = 0; i < indices.length; ++i) {
  28718. indices[i] = dupes[indices[i]] || indices[i];
  28719. }
  28720. //indices are now reordered
  28721. var originalSubMeshes = _this.subMeshes.slice(0);
  28722. _this.setIndices(indices);
  28723. _this.subMeshes = originalSubMeshes;
  28724. if (successCallback) {
  28725. successCallback(_this);
  28726. }
  28727. });
  28728. return this;
  28729. };
  28730. Mesh.prototype.serialize = function (serializationObject) {
  28731. serializationObject.name = this.name;
  28732. serializationObject.id = this.id;
  28733. serializationObject.type = this.getClassName();
  28734. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28735. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28736. }
  28737. serializationObject.position = this.position.asArray();
  28738. if (this.rotationQuaternion) {
  28739. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28740. }
  28741. else if (this.rotation) {
  28742. serializationObject.rotation = this.rotation.asArray();
  28743. }
  28744. serializationObject.scaling = this.scaling.asArray();
  28745. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28746. serializationObject.isEnabled = this.isEnabled(false);
  28747. serializationObject.isVisible = this.isVisible;
  28748. serializationObject.infiniteDistance = this.infiniteDistance;
  28749. serializationObject.pickable = this.isPickable;
  28750. serializationObject.receiveShadows = this.receiveShadows;
  28751. serializationObject.billboardMode = this.billboardMode;
  28752. serializationObject.visibility = this.visibility;
  28753. serializationObject.checkCollisions = this.checkCollisions;
  28754. serializationObject.isBlocker = this.isBlocker;
  28755. // Parent
  28756. if (this.parent) {
  28757. serializationObject.parentId = this.parent.id;
  28758. }
  28759. // Geometry
  28760. serializationObject.isUnIndexed = this.isUnIndexed;
  28761. var geometry = this._geometry;
  28762. if (geometry) {
  28763. var geometryId = geometry.id;
  28764. serializationObject.geometryId = geometryId;
  28765. // SubMeshes
  28766. serializationObject.subMeshes = [];
  28767. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28768. var subMesh = this.subMeshes[subIndex];
  28769. serializationObject.subMeshes.push({
  28770. materialIndex: subMesh.materialIndex,
  28771. verticesStart: subMesh.verticesStart,
  28772. verticesCount: subMesh.verticesCount,
  28773. indexStart: subMesh.indexStart,
  28774. indexCount: subMesh.indexCount
  28775. });
  28776. }
  28777. }
  28778. // Material
  28779. if (this.material) {
  28780. serializationObject.materialId = this.material.id;
  28781. }
  28782. else {
  28783. this.material = null;
  28784. }
  28785. // Morph targets
  28786. if (this.morphTargetManager) {
  28787. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28788. }
  28789. // Skeleton
  28790. if (this.skeleton) {
  28791. serializationObject.skeletonId = this.skeleton.id;
  28792. }
  28793. // Physics
  28794. //TODO implement correct serialization for physics impostors.
  28795. var impostor = this.getPhysicsImpostor();
  28796. if (impostor) {
  28797. serializationObject.physicsMass = impostor.getParam("mass");
  28798. serializationObject.physicsFriction = impostor.getParam("friction");
  28799. serializationObject.physicsRestitution = impostor.getParam("mass");
  28800. serializationObject.physicsImpostor = impostor.type;
  28801. }
  28802. // Metadata
  28803. if (this.metadata) {
  28804. serializationObject.metadata = this.metadata;
  28805. }
  28806. // Instances
  28807. serializationObject.instances = [];
  28808. for (var index = 0; index < this.instances.length; index++) {
  28809. var instance = this.instances[index];
  28810. var serializationInstance = {
  28811. name: instance.name,
  28812. id: instance.id,
  28813. position: instance.position.asArray(),
  28814. scaling: instance.scaling.asArray()
  28815. };
  28816. if (instance.rotationQuaternion) {
  28817. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28818. }
  28819. else if (instance.rotation) {
  28820. serializationInstance.rotation = instance.rotation.asArray();
  28821. }
  28822. serializationObject.instances.push(serializationInstance);
  28823. // Animations
  28824. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28825. serializationInstance.ranges = instance.serializeAnimationRanges();
  28826. }
  28827. //
  28828. // Animations
  28829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28830. serializationObject.ranges = this.serializeAnimationRanges();
  28831. // Layer mask
  28832. serializationObject.layerMask = this.layerMask;
  28833. // Alpha
  28834. serializationObject.alphaIndex = this.alphaIndex;
  28835. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28836. // Overlay
  28837. serializationObject.overlayAlpha = this.overlayAlpha;
  28838. serializationObject.overlayColor = this.overlayColor.asArray();
  28839. serializationObject.renderOverlay = this.renderOverlay;
  28840. // Fog
  28841. serializationObject.applyFog = this.applyFog;
  28842. // Action Manager
  28843. if (this.actionManager) {
  28844. serializationObject.actions = this.actionManager.serialize(this.name);
  28845. }
  28846. };
  28847. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28848. if (!this.geometry) {
  28849. return;
  28850. }
  28851. this._markSubMeshesAsAttributesDirty();
  28852. var morphTargetManager = this._morphTargetManager;
  28853. if (morphTargetManager && morphTargetManager.vertexCount) {
  28854. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28855. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28856. this.morphTargetManager = null;
  28857. return;
  28858. }
  28859. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28860. var morphTarget = morphTargetManager.getActiveTarget(index);
  28861. var positions = morphTarget.getPositions();
  28862. if (!positions) {
  28863. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28864. return;
  28865. }
  28866. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28867. var normals = morphTarget.getNormals();
  28868. if (normals) {
  28869. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28870. }
  28871. var tangents = morphTarget.getTangents();
  28872. if (tangents) {
  28873. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28874. }
  28875. }
  28876. }
  28877. else {
  28878. var index = 0;
  28879. // Positions
  28880. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28881. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28882. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28883. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28884. }
  28885. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28886. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28887. }
  28888. index++;
  28889. }
  28890. }
  28891. };
  28892. // Statics
  28893. /**
  28894. * Returns a new Mesh object parsed from the source provided.
  28895. * The parameter `parsedMesh` is the source.
  28896. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28897. */
  28898. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28899. var mesh;
  28900. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28901. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28902. }
  28903. else {
  28904. mesh = new Mesh(parsedMesh.name, scene);
  28905. }
  28906. mesh.id = parsedMesh.id;
  28907. if (BABYLON.Tags) {
  28908. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28909. }
  28910. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28911. if (parsedMesh.metadata !== undefined) {
  28912. mesh.metadata = parsedMesh.metadata;
  28913. }
  28914. if (parsedMesh.rotationQuaternion) {
  28915. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28916. }
  28917. else if (parsedMesh.rotation) {
  28918. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28919. }
  28920. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28921. if (parsedMesh.localMatrix) {
  28922. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28923. }
  28924. else if (parsedMesh.pivotMatrix) {
  28925. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28926. }
  28927. mesh.setEnabled(parsedMesh.isEnabled);
  28928. mesh.isVisible = parsedMesh.isVisible;
  28929. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28930. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28931. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28932. if (parsedMesh.applyFog !== undefined) {
  28933. mesh.applyFog = parsedMesh.applyFog;
  28934. }
  28935. if (parsedMesh.pickable !== undefined) {
  28936. mesh.isPickable = parsedMesh.pickable;
  28937. }
  28938. if (parsedMesh.alphaIndex !== undefined) {
  28939. mesh.alphaIndex = parsedMesh.alphaIndex;
  28940. }
  28941. mesh.receiveShadows = parsedMesh.receiveShadows;
  28942. mesh.billboardMode = parsedMesh.billboardMode;
  28943. if (parsedMesh.visibility !== undefined) {
  28944. mesh.visibility = parsedMesh.visibility;
  28945. }
  28946. mesh.checkCollisions = parsedMesh.checkCollisions;
  28947. if (parsedMesh.isBlocker !== undefined) {
  28948. mesh.isBlocker = parsedMesh.isBlocker;
  28949. }
  28950. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28951. // freezeWorldMatrix
  28952. if (parsedMesh.freezeWorldMatrix) {
  28953. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28954. }
  28955. // Parent
  28956. if (parsedMesh.parentId) {
  28957. mesh._waitingParentId = parsedMesh.parentId;
  28958. }
  28959. // Actions
  28960. if (parsedMesh.actions !== undefined) {
  28961. mesh._waitingActions = parsedMesh.actions;
  28962. }
  28963. // Overlay
  28964. if (parsedMesh.overlayAlpha !== undefined) {
  28965. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28966. }
  28967. if (parsedMesh.overlayColor !== undefined) {
  28968. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28969. }
  28970. if (parsedMesh.renderOverlay !== undefined) {
  28971. mesh.renderOverlay = parsedMesh.renderOverlay;
  28972. }
  28973. // Geometry
  28974. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28975. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28976. if (parsedMesh.delayLoadingFile) {
  28977. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28978. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28979. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28980. if (parsedMesh._binaryInfo) {
  28981. mesh._binaryInfo = parsedMesh._binaryInfo;
  28982. }
  28983. mesh._delayInfo = [];
  28984. if (parsedMesh.hasUVs) {
  28985. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28986. }
  28987. if (parsedMesh.hasUVs2) {
  28988. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28989. }
  28990. if (parsedMesh.hasUVs3) {
  28991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28992. }
  28993. if (parsedMesh.hasUVs4) {
  28994. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28995. }
  28996. if (parsedMesh.hasUVs5) {
  28997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28998. }
  28999. if (parsedMesh.hasUVs6) {
  29000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29001. }
  29002. if (parsedMesh.hasColors) {
  29003. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29004. }
  29005. if (parsedMesh.hasMatricesIndices) {
  29006. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29007. }
  29008. if (parsedMesh.hasMatricesWeights) {
  29009. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29010. }
  29011. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29012. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29013. mesh._checkDelayState();
  29014. }
  29015. }
  29016. else {
  29017. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29018. }
  29019. // Material
  29020. if (parsedMesh.materialId) {
  29021. mesh.setMaterialByID(parsedMesh.materialId);
  29022. }
  29023. else {
  29024. mesh.material = null;
  29025. }
  29026. // Morph targets
  29027. if (parsedMesh.morphTargetManagerId > -1) {
  29028. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29029. }
  29030. // Skeleton
  29031. if (parsedMesh.skeletonId > -1) {
  29032. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29033. if (parsedMesh.numBoneInfluencers) {
  29034. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29035. }
  29036. }
  29037. // Animations
  29038. if (parsedMesh.animations) {
  29039. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29040. var parsedAnimation = parsedMesh.animations[animationIndex];
  29041. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29042. }
  29043. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29044. }
  29045. if (parsedMesh.autoAnimate) {
  29046. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29047. }
  29048. // Layer Mask
  29049. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29050. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29051. }
  29052. else {
  29053. mesh.layerMask = 0x0FFFFFFF;
  29054. }
  29055. // Physics
  29056. if (parsedMesh.physicsImpostor) {
  29057. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29058. mass: parsedMesh.physicsMass,
  29059. friction: parsedMesh.physicsFriction,
  29060. restitution: parsedMesh.physicsRestitution
  29061. }, scene);
  29062. }
  29063. // Instances
  29064. if (parsedMesh.instances) {
  29065. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29066. var parsedInstance = parsedMesh.instances[index];
  29067. var instance = mesh.createInstance(parsedInstance.name);
  29068. if (parsedInstance.id) {
  29069. instance.id = parsedInstance.id;
  29070. }
  29071. if (BABYLON.Tags) {
  29072. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29073. }
  29074. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29075. if (parsedInstance.parentId) {
  29076. instance._waitingParentId = parsedInstance.parentId;
  29077. }
  29078. if (parsedInstance.rotationQuaternion) {
  29079. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29080. }
  29081. else if (parsedInstance.rotation) {
  29082. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29083. }
  29084. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29085. instance.checkCollisions = mesh.checkCollisions;
  29086. if (parsedMesh.animations) {
  29087. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29088. parsedAnimation = parsedMesh.animations[animationIndex];
  29089. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29090. }
  29091. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29092. }
  29093. }
  29094. }
  29095. return mesh;
  29096. };
  29097. /**
  29098. * Creates a ribbon mesh.
  29099. * Please consider using the same method from the MeshBuilder class instead.
  29100. * 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.
  29101. *
  29102. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29103. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29104. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29105. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29106. * 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.
  29107. * 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.
  29108. * 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
  29109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29112. */
  29113. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29114. if (closeArray === void 0) { closeArray = false; }
  29115. if (updatable === void 0) { updatable = false; }
  29116. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29117. pathArray: pathArray,
  29118. closeArray: closeArray,
  29119. closePath: closePath,
  29120. offset: offset,
  29121. updatable: updatable,
  29122. sideOrientation: sideOrientation,
  29123. instance: instance
  29124. }, scene);
  29125. };
  29126. /**
  29127. * Creates a plane polygonal mesh. By default, this is a disc.
  29128. * Please consider using the same method from the MeshBuilder class instead.
  29129. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29130. * 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.
  29131. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29132. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29134. */
  29135. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29136. if (scene === void 0) { scene = null; }
  29137. var options = {
  29138. radius: radius,
  29139. tessellation: tessellation,
  29140. sideOrientation: sideOrientation,
  29141. updatable: updatable
  29142. };
  29143. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29144. };
  29145. /**
  29146. * Creates a box mesh.
  29147. * Please consider using the same method from the MeshBuilder class instead.
  29148. * The parameter `size` sets the size (float) of each box side (default 1).
  29149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29152. */
  29153. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29154. if (scene === void 0) { scene = null; }
  29155. var options = {
  29156. size: size,
  29157. sideOrientation: sideOrientation,
  29158. updatable: updatable
  29159. };
  29160. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29161. };
  29162. /**
  29163. * Creates a sphere mesh.
  29164. * Please consider using the same method from the MeshBuilder class instead.
  29165. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29166. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29170. */
  29171. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29172. var options = {
  29173. segments: segments,
  29174. diameterX: diameter,
  29175. diameterY: diameter,
  29176. diameterZ: diameter,
  29177. sideOrientation: sideOrientation,
  29178. updatable: updatable
  29179. };
  29180. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29181. };
  29182. /**
  29183. * Creates a cylinder or a cone mesh.
  29184. * Please consider using the same method from the MeshBuilder class instead.
  29185. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29186. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29187. * 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.
  29188. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29189. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29191. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29193. */
  29194. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29195. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29196. if (scene !== undefined) {
  29197. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29198. updatable = scene;
  29199. }
  29200. scene = subdivisions;
  29201. subdivisions = 1;
  29202. }
  29203. var options = {
  29204. height: height,
  29205. diameterTop: diameterTop,
  29206. diameterBottom: diameterBottom,
  29207. tessellation: tessellation,
  29208. subdivisions: subdivisions,
  29209. sideOrientation: sideOrientation,
  29210. updatable: updatable
  29211. };
  29212. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29213. };
  29214. // Torus (Code from SharpDX.org)
  29215. /**
  29216. * Creates a torus mesh.
  29217. * Please consider using the same method from the MeshBuilder class instead.
  29218. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29219. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29220. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29221. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29222. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29224. */
  29225. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29226. var options = {
  29227. diameter: diameter,
  29228. thickness: thickness,
  29229. tessellation: tessellation,
  29230. sideOrientation: sideOrientation,
  29231. updatable: updatable
  29232. };
  29233. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29234. };
  29235. /**
  29236. * Creates a torus knot mesh.
  29237. * Please consider using the same method from the MeshBuilder class instead.
  29238. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29239. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29240. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29241. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29245. */
  29246. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29247. var options = {
  29248. radius: radius,
  29249. tube: tube,
  29250. radialSegments: radialSegments,
  29251. tubularSegments: tubularSegments,
  29252. p: p,
  29253. q: q,
  29254. sideOrientation: sideOrientation,
  29255. updatable: updatable
  29256. };
  29257. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29258. };
  29259. /**
  29260. * Creates a line mesh.
  29261. * Please consider using the same method from the MeshBuilder class instead.
  29262. * 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.
  29263. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29264. * The parameter `points` is an array successive Vector3.
  29265. * 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
  29266. * When updating an instance, remember that only point positions can change, not the number of points.
  29267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29268. */
  29269. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29270. if (scene === void 0) { scene = null; }
  29271. if (updatable === void 0) { updatable = false; }
  29272. if (instance === void 0) { instance = null; }
  29273. var options = {
  29274. points: points,
  29275. updatable: updatable,
  29276. instance: instance
  29277. };
  29278. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29279. };
  29280. /**
  29281. * Creates a dashed line mesh.
  29282. * Please consider using the same method from the MeshBuilder class instead.
  29283. * 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.
  29284. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29285. * The parameter `points` is an array successive Vector3.
  29286. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29287. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29288. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29289. * 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
  29290. * When updating an instance, remember that only point positions can change, not the number of points.
  29291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29292. */
  29293. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29294. if (scene === void 0) { scene = null; }
  29295. var options = {
  29296. points: points,
  29297. dashSize: dashSize,
  29298. gapSize: gapSize,
  29299. dashNb: dashNb,
  29300. updatable: updatable,
  29301. instance: instance
  29302. };
  29303. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29304. };
  29305. /**
  29306. * Creates a polygon mesh.
  29307. * Please consider using the same method from the MeshBuilder class instead.
  29308. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29309. * 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.
  29310. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29312. * Remember you can only change the shape positions, not their number when updating a polygon.
  29313. */
  29314. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29315. var options = {
  29316. shape: shape,
  29317. holes: holes,
  29318. updatable: updatable,
  29319. sideOrientation: sideOrientation
  29320. };
  29321. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29322. };
  29323. /**
  29324. * Creates an extruded polygon mesh, with depth in the Y direction.
  29325. * Please consider using the same method from the MeshBuilder class instead.
  29326. */
  29327. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29328. var options = {
  29329. shape: shape,
  29330. holes: holes,
  29331. depth: depth,
  29332. updatable: updatable,
  29333. sideOrientation: sideOrientation
  29334. };
  29335. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29336. };
  29337. /**
  29338. * Creates an extruded shape mesh.
  29339. * 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.
  29340. * Please consider using the same method from the MeshBuilder class instead.
  29341. *
  29342. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29343. * 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
  29344. * extruded along the Z axis.
  29345. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29346. * 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.
  29347. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29348. * 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
  29349. * 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
  29350. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29354. */
  29355. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29356. if (scene === void 0) { scene = null; }
  29357. var options = {
  29358. shape: shape,
  29359. path: path,
  29360. scale: scale,
  29361. rotation: rotation,
  29362. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29363. sideOrientation: sideOrientation,
  29364. instance: instance,
  29365. updatable: updatable
  29366. };
  29367. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29368. };
  29369. /**
  29370. * Creates an custom extruded shape mesh.
  29371. * 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.
  29372. * Please consider using the same method from the MeshBuilder class instead.
  29373. *
  29374. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29375. * 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
  29376. * extruded along the Z axis.
  29377. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29378. * 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
  29379. * and the distance of this point from the begining of the path :
  29380. * ```javascript
  29381. * var rotationFunction = function(i, distance) {
  29382. * // do things
  29383. * return rotationValue; }
  29384. * ```
  29385. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29386. * 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
  29387. * and the distance of this point from the begining of the path :
  29388. * ```javascript
  29389. * var scaleFunction = function(i, distance) {
  29390. * // do things
  29391. * return scaleValue;}
  29392. * ```
  29393. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29394. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29395. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29396. * 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
  29397. * 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
  29398. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29402. */
  29403. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29404. var options = {
  29405. shape: shape,
  29406. path: path,
  29407. scaleFunction: scaleFunction,
  29408. rotationFunction: rotationFunction,
  29409. ribbonCloseArray: ribbonCloseArray,
  29410. ribbonClosePath: ribbonClosePath,
  29411. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29412. sideOrientation: sideOrientation,
  29413. instance: instance,
  29414. updatable: updatable
  29415. };
  29416. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29417. };
  29418. /**
  29419. * Creates lathe mesh.
  29420. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29421. * Please consider using the same method from the MeshBuilder class instead.
  29422. * 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
  29423. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29424. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29425. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29426. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29429. */
  29430. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29431. var options = {
  29432. shape: shape,
  29433. radius: radius,
  29434. tessellation: tessellation,
  29435. sideOrientation: sideOrientation,
  29436. updatable: updatable
  29437. };
  29438. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29439. };
  29440. /**
  29441. * Creates a plane mesh.
  29442. * Please consider using the same method from the MeshBuilder class instead.
  29443. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29447. */
  29448. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29449. var options = {
  29450. size: size,
  29451. width: size,
  29452. height: size,
  29453. sideOrientation: sideOrientation,
  29454. updatable: updatable
  29455. };
  29456. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29457. };
  29458. /**
  29459. * Creates a ground mesh.
  29460. * Please consider using the same method from the MeshBuilder class instead.
  29461. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29462. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29464. */
  29465. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29466. var options = {
  29467. width: width,
  29468. height: height,
  29469. subdivisions: subdivisions,
  29470. updatable: updatable
  29471. };
  29472. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29473. };
  29474. /**
  29475. * Creates a tiled ground mesh.
  29476. * Please consider using the same method from the MeshBuilder class instead.
  29477. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29478. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29479. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29480. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29481. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29482. * numbers of subdivisions on the ground width and height of each tile.
  29483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29484. */
  29485. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29486. var options = {
  29487. xmin: xmin,
  29488. zmin: zmin,
  29489. xmax: xmax,
  29490. zmax: zmax,
  29491. subdivisions: subdivisions,
  29492. precision: precision,
  29493. updatable: updatable
  29494. };
  29495. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29496. };
  29497. /**
  29498. * Creates a ground mesh from a height map.
  29499. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29500. * Please consider using the same method from the MeshBuilder class instead.
  29501. * The parameter `url` sets the URL of the height map image resource.
  29502. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29503. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29504. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29505. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29506. * 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).
  29507. * This function is passed the newly built mesh :
  29508. * ```javascript
  29509. * function(mesh) { // do things
  29510. * return; }
  29511. * ```
  29512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29513. */
  29514. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29515. var options = {
  29516. width: width,
  29517. height: height,
  29518. subdivisions: subdivisions,
  29519. minHeight: minHeight,
  29520. maxHeight: maxHeight,
  29521. updatable: updatable,
  29522. onReady: onReady
  29523. };
  29524. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29525. };
  29526. /**
  29527. * Creates a tube mesh.
  29528. * 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.
  29529. * Please consider using the same method from the MeshBuilder class instead.
  29530. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29531. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29532. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29533. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29534. * 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.
  29535. * It must return a radius value (positive float) :
  29536. * ```javascript
  29537. * var radiusFunction = function(i, distance) {
  29538. * // do things
  29539. * return radius; }
  29540. * ```
  29541. * 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
  29542. * 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
  29543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29544. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29545. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29546. */
  29547. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29548. var options = {
  29549. path: path,
  29550. radius: radius,
  29551. tessellation: tessellation,
  29552. radiusFunction: radiusFunction,
  29553. arc: 1,
  29554. cap: cap,
  29555. updatable: updatable,
  29556. sideOrientation: sideOrientation,
  29557. instance: instance
  29558. };
  29559. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29560. };
  29561. /**
  29562. * Creates a polyhedron mesh.
  29563. * Please consider using the same method from the MeshBuilder class instead.
  29564. * 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
  29565. * to choose the wanted type.
  29566. * The parameter `size` (positive float, default 1) sets the polygon size.
  29567. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29568. * 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`.
  29569. * 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
  29570. * 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)`).
  29571. * 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
  29572. * 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.
  29573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29576. */
  29577. Mesh.CreatePolyhedron = function (name, options, scene) {
  29578. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29579. };
  29580. /**
  29581. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29582. * Please consider using the same method from the MeshBuilder class instead.
  29583. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29584. * 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`).
  29585. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29586. * 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.
  29587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29590. */
  29591. Mesh.CreateIcoSphere = function (name, options, scene) {
  29592. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29593. };
  29594. /**
  29595. * Creates a decal mesh.
  29596. * Please consider using the same method from the MeshBuilder class instead.
  29597. * 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.
  29598. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29599. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29600. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29601. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29602. */
  29603. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29604. var options = {
  29605. position: position,
  29606. normal: normal,
  29607. size: size,
  29608. angle: angle
  29609. };
  29610. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29611. };
  29612. // Skeletons
  29613. /**
  29614. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29615. */
  29616. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29617. if (!this._sourcePositions) {
  29618. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29619. if (!source) {
  29620. return this._sourcePositions;
  29621. }
  29622. this._sourcePositions = new Float32Array(source);
  29623. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29624. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29625. }
  29626. }
  29627. return this._sourcePositions;
  29628. };
  29629. /**
  29630. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29631. */
  29632. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29633. if (!this._sourceNormals) {
  29634. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29635. if (!source) {
  29636. return this._sourceNormals;
  29637. }
  29638. this._sourceNormals = new Float32Array(source);
  29639. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29641. }
  29642. }
  29643. return this._sourceNormals;
  29644. };
  29645. /**
  29646. * Updates the vertex buffer by applying transformation from the bones.
  29647. * Returns the Mesh.
  29648. *
  29649. * @param {skeleton} skeleton to apply
  29650. */
  29651. Mesh.prototype.applySkeleton = function (skeleton) {
  29652. if (!this.geometry) {
  29653. return this;
  29654. }
  29655. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29656. return this;
  29657. }
  29658. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29659. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29660. return this;
  29661. }
  29662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29663. return this;
  29664. }
  29665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29666. return this;
  29667. }
  29668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29669. return this;
  29670. }
  29671. if (!this._sourcePositions) {
  29672. var submeshes = this.subMeshes.slice();
  29673. this.setPositionsForCPUSkinning();
  29674. this.subMeshes = submeshes;
  29675. }
  29676. if (!this._sourceNormals) {
  29677. this.setNormalsForCPUSkinning();
  29678. }
  29679. // positionsData checks for not being Float32Array will only pass at most once
  29680. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29681. if (!positionsData) {
  29682. return this;
  29683. }
  29684. if (!(positionsData instanceof Float32Array)) {
  29685. positionsData = new Float32Array(positionsData);
  29686. }
  29687. // normalsData checks for not being Float32Array will only pass at most once
  29688. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29689. if (!normalsData) {
  29690. return this;
  29691. }
  29692. if (!(normalsData instanceof Float32Array)) {
  29693. normalsData = new Float32Array(normalsData);
  29694. }
  29695. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29696. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29697. if (!matricesWeightsData || !matricesIndicesData) {
  29698. return this;
  29699. }
  29700. var needExtras = this.numBoneInfluencers > 4;
  29701. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29702. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29703. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29704. var tempVector3 = BABYLON.Vector3.Zero();
  29705. var finalMatrix = new BABYLON.Matrix();
  29706. var tempMatrix = new BABYLON.Matrix();
  29707. var matWeightIdx = 0;
  29708. var inf;
  29709. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29710. var weight;
  29711. for (inf = 0; inf < 4; inf++) {
  29712. weight = matricesWeightsData[matWeightIdx + inf];
  29713. if (weight > 0) {
  29714. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29715. finalMatrix.addToSelf(tempMatrix);
  29716. }
  29717. else
  29718. break;
  29719. }
  29720. if (needExtras) {
  29721. for (inf = 0; inf < 4; inf++) {
  29722. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29723. if (weight > 0) {
  29724. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29725. finalMatrix.addToSelf(tempMatrix);
  29726. }
  29727. else
  29728. break;
  29729. }
  29730. }
  29731. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29732. tempVector3.toArray(positionsData, index);
  29733. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29734. tempVector3.toArray(normalsData, index);
  29735. finalMatrix.reset();
  29736. }
  29737. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29738. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29739. return this;
  29740. };
  29741. // Tools
  29742. /**
  29743. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29744. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29745. */
  29746. Mesh.MinMax = function (meshes) {
  29747. var minVector = null;
  29748. var maxVector = null;
  29749. meshes.forEach(function (mesh, index, array) {
  29750. var boundingInfo = mesh.getBoundingInfo();
  29751. var boundingBox = boundingInfo.boundingBox;
  29752. if (!minVector || !maxVector) {
  29753. minVector = boundingBox.minimumWorld;
  29754. maxVector = boundingBox.maximumWorld;
  29755. }
  29756. else {
  29757. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29758. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29759. }
  29760. });
  29761. if (!minVector || !maxVector) {
  29762. return {
  29763. min: BABYLON.Vector3.Zero(),
  29764. max: BABYLON.Vector3.Zero()
  29765. };
  29766. }
  29767. return {
  29768. min: minVector,
  29769. max: maxVector
  29770. };
  29771. };
  29772. /**
  29773. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29774. */
  29775. Mesh.Center = function (meshesOrMinMaxVector) {
  29776. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29777. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29778. };
  29779. /**
  29780. * Merge the array of meshes into a single mesh for performance reasons.
  29781. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29782. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29783. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29784. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29785. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29786. */
  29787. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29788. if (disposeSource === void 0) { disposeSource = true; }
  29789. var index;
  29790. if (!allow32BitsIndices) {
  29791. var totalVertices = 0;
  29792. // Counting vertices
  29793. for (index = 0; index < meshes.length; index++) {
  29794. if (meshes[index]) {
  29795. totalVertices += meshes[index].getTotalVertices();
  29796. if (totalVertices > 65536) {
  29797. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29798. return null;
  29799. }
  29800. }
  29801. }
  29802. }
  29803. // Merge
  29804. var vertexData = null;
  29805. var otherVertexData;
  29806. var indiceArray = new Array();
  29807. var source = null;
  29808. for (index = 0; index < meshes.length; index++) {
  29809. if (meshes[index]) {
  29810. meshes[index].computeWorldMatrix(true);
  29811. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29812. otherVertexData.transform(meshes[index].getWorldMatrix());
  29813. if (vertexData) {
  29814. vertexData.merge(otherVertexData);
  29815. }
  29816. else {
  29817. vertexData = otherVertexData;
  29818. source = meshes[index];
  29819. }
  29820. if (subdivideWithSubMeshes) {
  29821. indiceArray.push(meshes[index].getTotalIndices());
  29822. }
  29823. }
  29824. }
  29825. source = source;
  29826. if (!meshSubclass) {
  29827. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29828. }
  29829. vertexData.applyToMesh(meshSubclass);
  29830. // Setting properties
  29831. meshSubclass.material = source.material;
  29832. meshSubclass.checkCollisions = source.checkCollisions;
  29833. // Cleaning
  29834. if (disposeSource) {
  29835. for (index = 0; index < meshes.length; index++) {
  29836. if (meshes[index]) {
  29837. meshes[index].dispose();
  29838. }
  29839. }
  29840. }
  29841. // Subdivide
  29842. if (subdivideWithSubMeshes) {
  29843. //-- Suppresions du submesh global
  29844. meshSubclass.releaseSubMeshes();
  29845. index = 0;
  29846. var offset = 0;
  29847. //-- aplique la subdivision en fonction du tableau d'indices
  29848. while (index < indiceArray.length) {
  29849. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29850. offset += indiceArray[index];
  29851. index++;
  29852. }
  29853. }
  29854. return meshSubclass;
  29855. };
  29856. // Consts
  29857. Mesh._FRONTSIDE = 0;
  29858. Mesh._BACKSIDE = 1;
  29859. Mesh._DOUBLESIDE = 2;
  29860. Mesh._DEFAULTSIDE = 0;
  29861. Mesh._NO_CAP = 0;
  29862. Mesh._CAP_START = 1;
  29863. Mesh._CAP_END = 2;
  29864. Mesh._CAP_ALL = 3;
  29865. return Mesh;
  29866. }(BABYLON.AbstractMesh));
  29867. BABYLON.Mesh = Mesh;
  29868. })(BABYLON || (BABYLON = {}));
  29869. //# sourceMappingURL=babylon.mesh.js.map
  29870. var BABYLON;
  29871. (function (BABYLON) {
  29872. var BaseSubMesh = /** @class */ (function () {
  29873. function BaseSubMesh() {
  29874. }
  29875. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29876. get: function () {
  29877. return this._materialEffect;
  29878. },
  29879. enumerable: true,
  29880. configurable: true
  29881. });
  29882. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29883. if (defines === void 0) { defines = null; }
  29884. if (this._materialEffect === effect) {
  29885. if (!effect) {
  29886. this._materialDefines = null;
  29887. }
  29888. return;
  29889. }
  29890. this._materialDefines = defines;
  29891. this._materialEffect = effect;
  29892. };
  29893. return BaseSubMesh;
  29894. }());
  29895. BABYLON.BaseSubMesh = BaseSubMesh;
  29896. var SubMesh = /** @class */ (function (_super) {
  29897. __extends(SubMesh, _super);
  29898. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29899. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29900. var _this = _super.call(this) || this;
  29901. _this.materialIndex = materialIndex;
  29902. _this.verticesStart = verticesStart;
  29903. _this.verticesCount = verticesCount;
  29904. _this.indexStart = indexStart;
  29905. _this.indexCount = indexCount;
  29906. _this._renderId = 0;
  29907. _this._mesh = mesh;
  29908. _this._renderingMesh = renderingMesh || mesh;
  29909. mesh.subMeshes.push(_this);
  29910. _this._trianglePlanes = [];
  29911. _this._id = mesh.subMeshes.length - 1;
  29912. if (createBoundingBox) {
  29913. _this.refreshBoundingInfo();
  29914. mesh.computeWorldMatrix(true);
  29915. }
  29916. return _this;
  29917. }
  29918. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29919. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29920. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29921. };
  29922. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29923. get: function () {
  29924. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29925. },
  29926. enumerable: true,
  29927. configurable: true
  29928. });
  29929. /**
  29930. * Returns the submesh BoudingInfo object.
  29931. */
  29932. SubMesh.prototype.getBoundingInfo = function () {
  29933. if (this.IsGlobal) {
  29934. return this._mesh.getBoundingInfo();
  29935. }
  29936. return this._boundingInfo;
  29937. };
  29938. /**
  29939. * Sets the submesh BoundingInfo.
  29940. * Return the SubMesh.
  29941. */
  29942. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29943. this._boundingInfo = boundingInfo;
  29944. return this;
  29945. };
  29946. /**
  29947. * Returns the mesh of the current submesh.
  29948. */
  29949. SubMesh.prototype.getMesh = function () {
  29950. return this._mesh;
  29951. };
  29952. /**
  29953. * Returns the rendering mesh of the submesh.
  29954. */
  29955. SubMesh.prototype.getRenderingMesh = function () {
  29956. return this._renderingMesh;
  29957. };
  29958. /**
  29959. * Returns the submesh material.
  29960. */
  29961. SubMesh.prototype.getMaterial = function () {
  29962. var rootMaterial = this._renderingMesh.material;
  29963. if (rootMaterial === null || rootMaterial === undefined) {
  29964. return this._mesh.getScene().defaultMaterial;
  29965. }
  29966. else if (rootMaterial.getSubMaterial) {
  29967. var multiMaterial = rootMaterial;
  29968. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29969. if (this._currentMaterial !== effectiveMaterial) {
  29970. this._currentMaterial = effectiveMaterial;
  29971. this._materialDefines = null;
  29972. }
  29973. return effectiveMaterial;
  29974. }
  29975. return rootMaterial;
  29976. };
  29977. // Methods
  29978. /**
  29979. * Sets a new updated BoundingInfo object to the submesh.
  29980. * Returns the SubMesh.
  29981. */
  29982. SubMesh.prototype.refreshBoundingInfo = function () {
  29983. this._lastColliderWorldVertices = null;
  29984. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29985. return this;
  29986. }
  29987. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29988. if (!data) {
  29989. this._boundingInfo = this._mesh.getBoundingInfo();
  29990. return this;
  29991. }
  29992. var indices = this._renderingMesh.getIndices();
  29993. var extend;
  29994. //is this the only submesh?
  29995. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29996. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29997. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29998. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29999. }
  30000. else {
  30001. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30002. }
  30003. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30004. return this;
  30005. };
  30006. SubMesh.prototype._checkCollision = function (collider) {
  30007. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30008. return boundingInfo._checkCollision(collider);
  30009. };
  30010. /**
  30011. * Updates the submesh BoundingInfo.
  30012. * Returns the Submesh.
  30013. */
  30014. SubMesh.prototype.updateBoundingInfo = function (world) {
  30015. var boundingInfo = this.getBoundingInfo();
  30016. if (!boundingInfo) {
  30017. this.refreshBoundingInfo();
  30018. boundingInfo = this.getBoundingInfo();
  30019. }
  30020. boundingInfo.update(world);
  30021. return this;
  30022. };
  30023. /**
  30024. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30025. * Boolean returned.
  30026. */
  30027. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30028. var boundingInfo = this.getBoundingInfo();
  30029. if (!boundingInfo) {
  30030. return false;
  30031. }
  30032. return boundingInfo.isInFrustum(frustumPlanes);
  30033. };
  30034. /**
  30035. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30036. * Boolean returned.
  30037. */
  30038. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30039. var boundingInfo = this.getBoundingInfo();
  30040. if (!boundingInfo) {
  30041. return false;
  30042. }
  30043. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30044. };
  30045. /**
  30046. * Renders the submesh.
  30047. * Returns it.
  30048. */
  30049. SubMesh.prototype.render = function (enableAlphaMode) {
  30050. this._renderingMesh.render(this, enableAlphaMode);
  30051. return this;
  30052. };
  30053. /**
  30054. * Returns a new Index Buffer.
  30055. * Type returned : WebGLBuffer.
  30056. */
  30057. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30058. if (!this._linesIndexBuffer) {
  30059. var linesIndices = [];
  30060. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30061. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30062. }
  30063. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30064. this.linesIndexCount = linesIndices.length;
  30065. }
  30066. return this._linesIndexBuffer;
  30067. };
  30068. /**
  30069. * True is the passed Ray intersects the submesh bounding box.
  30070. * Boolean returned.
  30071. */
  30072. SubMesh.prototype.canIntersects = function (ray) {
  30073. var boundingInfo = this.getBoundingInfo();
  30074. if (!boundingInfo) {
  30075. return false;
  30076. }
  30077. return ray.intersectsBox(boundingInfo.boundingBox);
  30078. };
  30079. /**
  30080. * Returns an object IntersectionInfo.
  30081. */
  30082. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30083. var intersectInfo = null;
  30084. // LineMesh first as it's also a Mesh...
  30085. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30086. var lineMesh = this._mesh;
  30087. // Line test
  30088. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30089. var p0 = positions[indices[index]];
  30090. var p1 = positions[indices[index + 1]];
  30091. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30092. if (length < 0) {
  30093. continue;
  30094. }
  30095. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30096. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30097. if (fastCheck) {
  30098. break;
  30099. }
  30100. }
  30101. }
  30102. }
  30103. else {
  30104. // Triangles test
  30105. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30106. var p0 = positions[indices[index]];
  30107. var p1 = positions[indices[index + 1]];
  30108. var p2 = positions[indices[index + 2]];
  30109. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30110. if (currentIntersectInfo) {
  30111. if (currentIntersectInfo.distance < 0) {
  30112. continue;
  30113. }
  30114. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30115. intersectInfo = currentIntersectInfo;
  30116. intersectInfo.faceId = index / 3;
  30117. if (fastCheck) {
  30118. break;
  30119. }
  30120. }
  30121. }
  30122. }
  30123. }
  30124. return intersectInfo;
  30125. };
  30126. SubMesh.prototype._rebuild = function () {
  30127. if (this._linesIndexBuffer) {
  30128. this._linesIndexBuffer = null;
  30129. }
  30130. };
  30131. // Clone
  30132. /**
  30133. * Creates a new Submesh from the passed Mesh.
  30134. */
  30135. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30136. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30137. if (!this.IsGlobal) {
  30138. var boundingInfo = this.getBoundingInfo();
  30139. if (!boundingInfo) {
  30140. return result;
  30141. }
  30142. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30143. }
  30144. return result;
  30145. };
  30146. // Dispose
  30147. /**
  30148. * Disposes the Submesh.
  30149. * Returns nothing.
  30150. */
  30151. SubMesh.prototype.dispose = function () {
  30152. if (this._linesIndexBuffer) {
  30153. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30154. this._linesIndexBuffer = null;
  30155. }
  30156. // Remove from mesh
  30157. var index = this._mesh.subMeshes.indexOf(this);
  30158. this._mesh.subMeshes.splice(index, 1);
  30159. };
  30160. // Statics
  30161. /**
  30162. * Creates a new Submesh from the passed parameters :
  30163. * - materialIndex (integer) : the index of the main mesh material.
  30164. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30165. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30166. * - mesh (Mesh) : the main mesh to create the submesh from.
  30167. * - renderingMesh (optional Mesh) : rendering mesh.
  30168. */
  30169. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30170. var minVertexIndex = Number.MAX_VALUE;
  30171. var maxVertexIndex = -Number.MAX_VALUE;
  30172. renderingMesh = (renderingMesh || mesh);
  30173. var indices = renderingMesh.getIndices();
  30174. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30175. var vertexIndex = indices[index];
  30176. if (vertexIndex < minVertexIndex)
  30177. minVertexIndex = vertexIndex;
  30178. if (vertexIndex > maxVertexIndex)
  30179. maxVertexIndex = vertexIndex;
  30180. }
  30181. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30182. };
  30183. return SubMesh;
  30184. }(BaseSubMesh));
  30185. BABYLON.SubMesh = SubMesh;
  30186. })(BABYLON || (BABYLON = {}));
  30187. //# sourceMappingURL=babylon.subMesh.js.map
  30188. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30189. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30190. s = arguments[i];
  30191. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30192. t[p] = s[p];
  30193. }
  30194. return t;
  30195. };
  30196. var BABYLON;
  30197. (function (BABYLON) {
  30198. /**
  30199. * Manages the defines for the Material.
  30200. */
  30201. var MaterialDefines = /** @class */ (function () {
  30202. function MaterialDefines() {
  30203. this._isDirty = true;
  30204. this._areLightsDirty = true;
  30205. this._areAttributesDirty = true;
  30206. this._areTexturesDirty = true;
  30207. this._areFresnelDirty = true;
  30208. this._areMiscDirty = true;
  30209. this._areImageProcessingDirty = true;
  30210. this._normals = false;
  30211. this._uvs = false;
  30212. this._needNormals = false;
  30213. this._needUVs = false;
  30214. }
  30215. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30216. /**
  30217. * Specifies if the material needs to be re-calculated.
  30218. */
  30219. get: function () {
  30220. return this._isDirty;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. /**
  30226. * Marks the material to indicate that it has been re-calculated.
  30227. */
  30228. MaterialDefines.prototype.markAsProcessed = function () {
  30229. this._isDirty = false;
  30230. this._areAttributesDirty = false;
  30231. this._areTexturesDirty = false;
  30232. this._areFresnelDirty = false;
  30233. this._areLightsDirty = false;
  30234. this._areMiscDirty = false;
  30235. this._areImageProcessingDirty = false;
  30236. };
  30237. /**
  30238. * Marks the material to indicate that it needs to be re-calculated.
  30239. */
  30240. MaterialDefines.prototype.markAsUnprocessed = function () {
  30241. this._isDirty = true;
  30242. };
  30243. /**
  30244. * Marks the material to indicate all of its defines need to be re-calculated.
  30245. */
  30246. MaterialDefines.prototype.markAllAsDirty = function () {
  30247. this._areTexturesDirty = true;
  30248. this._areAttributesDirty = true;
  30249. this._areLightsDirty = true;
  30250. this._areFresnelDirty = true;
  30251. this._areMiscDirty = true;
  30252. this._areImageProcessingDirty = true;
  30253. this._isDirty = true;
  30254. };
  30255. /**
  30256. * Marks the material to indicate that image processing needs to be re-calculated.
  30257. */
  30258. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30259. this._areImageProcessingDirty = true;
  30260. this._isDirty = true;
  30261. };
  30262. /**
  30263. * Marks the material to indicate the lights need to be re-calculated.
  30264. */
  30265. MaterialDefines.prototype.markAsLightDirty = function () {
  30266. this._areLightsDirty = true;
  30267. this._isDirty = true;
  30268. };
  30269. /**
  30270. * Marks the attribute state as changed.
  30271. */
  30272. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30273. this._areAttributesDirty = true;
  30274. this._isDirty = true;
  30275. };
  30276. /**
  30277. * Marks the texture state as changed.
  30278. */
  30279. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30280. this._areTexturesDirty = true;
  30281. this._isDirty = true;
  30282. };
  30283. /**
  30284. * Marks the fresnel state as changed.
  30285. */
  30286. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30287. this._areFresnelDirty = true;
  30288. this._isDirty = true;
  30289. };
  30290. /**
  30291. * Marks the misc state as changed.
  30292. */
  30293. MaterialDefines.prototype.markAsMiscDirty = function () {
  30294. this._areMiscDirty = true;
  30295. this._isDirty = true;
  30296. };
  30297. /**
  30298. * Rebuilds the material defines.
  30299. */
  30300. MaterialDefines.prototype.rebuild = function () {
  30301. if (this._keys) {
  30302. delete this._keys;
  30303. }
  30304. this._keys = [];
  30305. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30306. var key = _a[_i];
  30307. if (key[0] === "_") {
  30308. continue;
  30309. }
  30310. this._keys.push(key);
  30311. }
  30312. };
  30313. /**
  30314. * Specifies if two material defines are equal.
  30315. * @param other - A material define instance to compare to.
  30316. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30317. */
  30318. MaterialDefines.prototype.isEqual = function (other) {
  30319. if (this._keys.length !== other._keys.length) {
  30320. return false;
  30321. }
  30322. for (var index = 0; index < this._keys.length; index++) {
  30323. var prop = this._keys[index];
  30324. if (this[prop] !== other[prop]) {
  30325. return false;
  30326. }
  30327. }
  30328. return true;
  30329. };
  30330. /**
  30331. * Clones this instance's defines to another instance.
  30332. * @param other - material defines to clone values to.
  30333. */
  30334. MaterialDefines.prototype.cloneTo = function (other) {
  30335. if (this._keys.length !== other._keys.length) {
  30336. other._keys = this._keys.slice(0);
  30337. }
  30338. for (var index = 0; index < this._keys.length; index++) {
  30339. var prop = this._keys[index];
  30340. other[prop] = this[prop];
  30341. }
  30342. };
  30343. /**
  30344. * Resets the material define values.
  30345. */
  30346. MaterialDefines.prototype.reset = function () {
  30347. for (var index = 0; index < this._keys.length; index++) {
  30348. var prop = this._keys[index];
  30349. if (typeof (this[prop]) === "number") {
  30350. this[prop] = 0;
  30351. }
  30352. else {
  30353. this[prop] = false;
  30354. }
  30355. }
  30356. };
  30357. /**
  30358. * Converts the material define values to a string.
  30359. * @returns - String of material define information.
  30360. */
  30361. MaterialDefines.prototype.toString = function () {
  30362. var result = "";
  30363. for (var index = 0; index < this._keys.length; index++) {
  30364. var prop = this._keys[index];
  30365. var value = this[prop];
  30366. if (typeof (value) === "number") {
  30367. result += "#define " + prop + " " + this[prop] + "\n";
  30368. }
  30369. else if (value) {
  30370. result += "#define " + prop + "\n";
  30371. }
  30372. }
  30373. return result;
  30374. };
  30375. return MaterialDefines;
  30376. }());
  30377. BABYLON.MaterialDefines = MaterialDefines;
  30378. /**
  30379. * This offers the main features of a material in BJS.
  30380. */
  30381. var Material = /** @class */ (function () {
  30382. /**
  30383. * Creates a material instance.
  30384. * @param name - The name of the material.
  30385. * @param scene - The BJS scene to reference.
  30386. * @param doNotAdd - Specifies if the material should be added to the scene.
  30387. */
  30388. function Material(name, scene, doNotAdd) {
  30389. /**
  30390. * Specifies if the ready state should be checked on each call.
  30391. */
  30392. this.checkReadyOnEveryCall = false;
  30393. /**
  30394. * Specifies if the ready state should be checked once.
  30395. */
  30396. this.checkReadyOnlyOnce = false;
  30397. /**
  30398. * The state of the material.
  30399. */
  30400. this.state = "";
  30401. /**
  30402. * The alpha value of the material.
  30403. */
  30404. this._alpha = 1.0;
  30405. /**
  30406. * Specifies if back face culling is enabled.
  30407. */
  30408. this._backFaceCulling = true;
  30409. /**
  30410. * Specifies if the material should be serialized.
  30411. */
  30412. this.doNotSerialize = false;
  30413. /**
  30414. * Specifies if the effect should be stored on sub meshes.
  30415. */
  30416. this.storeEffectOnSubMeshes = false;
  30417. /**
  30418. * An event triggered when the material is disposed.
  30419. * @type {BABYLON.Observable}
  30420. */
  30421. this.onDisposeObservable = new BABYLON.Observable();
  30422. /**
  30423. * An event triggered when the material is bound.
  30424. * @type {BABYLON.Observable}
  30425. */
  30426. this.onBindObservable = new BABYLON.Observable();
  30427. /**
  30428. * An event triggered when the material is unbound.
  30429. * @type {BABYLON.Observable}
  30430. */
  30431. this.onUnBindObservable = new BABYLON.Observable();
  30432. /**
  30433. * Stores the value of the alpha mode.
  30434. */
  30435. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30436. /**
  30437. * Stores the state of the need depth pre-pass value.
  30438. */
  30439. this._needDepthPrePass = false;
  30440. /**
  30441. * Specifies if depth writing should be disabled.
  30442. */
  30443. this.disableDepthWrite = false;
  30444. /**
  30445. * Specifies if depth writing should be forced.
  30446. */
  30447. this.forceDepthWrite = false;
  30448. /**
  30449. * Specifies if there should be a separate pass for culling.
  30450. */
  30451. this.separateCullingPass = false;
  30452. /**
  30453. * Stores the state specifing if fog should be enabled.
  30454. */
  30455. this._fogEnabled = true;
  30456. /**
  30457. * Stores the size of points.
  30458. */
  30459. this.pointSize = 1.0;
  30460. /**
  30461. * Stores the z offset value.
  30462. */
  30463. this.zOffset = 0;
  30464. /**
  30465. * Specifies if the material was previously ready.
  30466. */
  30467. this._wasPreviouslyReady = false;
  30468. /**
  30469. * Stores the fill mode state.
  30470. */
  30471. this._fillMode = Material.TriangleFillMode;
  30472. this.name = name;
  30473. this.id = name || BABYLON.Tools.RandomId();
  30474. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30475. if (this._scene.useRightHandedSystem) {
  30476. this.sideOrientation = Material.ClockWiseSideOrientation;
  30477. }
  30478. else {
  30479. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30480. }
  30481. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30482. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30483. if (!doNotAdd) {
  30484. this._scene.materials.push(this);
  30485. }
  30486. }
  30487. Object.defineProperty(Material, "TriangleFillMode", {
  30488. /**
  30489. * Returns the triangle fill mode.
  30490. */
  30491. get: function () {
  30492. return Material._TriangleFillMode;
  30493. },
  30494. enumerable: true,
  30495. configurable: true
  30496. });
  30497. Object.defineProperty(Material, "WireFrameFillMode", {
  30498. /**
  30499. * Returns the wireframe mode.
  30500. */
  30501. get: function () {
  30502. return Material._WireFrameFillMode;
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(Material, "PointFillMode", {
  30508. /**
  30509. * Returns the point fill mode.
  30510. */
  30511. get: function () {
  30512. return Material._PointFillMode;
  30513. },
  30514. enumerable: true,
  30515. configurable: true
  30516. });
  30517. Object.defineProperty(Material, "PointListDrawMode", {
  30518. /**
  30519. * Returns the point list draw mode.
  30520. */
  30521. get: function () {
  30522. return Material._PointListDrawMode;
  30523. },
  30524. enumerable: true,
  30525. configurable: true
  30526. });
  30527. Object.defineProperty(Material, "LineListDrawMode", {
  30528. /**
  30529. * Returns the line list draw mode.
  30530. */
  30531. get: function () {
  30532. return Material._LineListDrawMode;
  30533. },
  30534. enumerable: true,
  30535. configurable: true
  30536. });
  30537. Object.defineProperty(Material, "LineLoopDrawMode", {
  30538. /**
  30539. * Returns the line loop draw mode.
  30540. */
  30541. get: function () {
  30542. return Material._LineLoopDrawMode;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(Material, "LineStripDrawMode", {
  30548. /**
  30549. * Returns the line strip draw mode.
  30550. */
  30551. get: function () {
  30552. return Material._LineStripDrawMode;
  30553. },
  30554. enumerable: true,
  30555. configurable: true
  30556. });
  30557. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30558. /**
  30559. * Returns the triangle strip draw mode.
  30560. */
  30561. get: function () {
  30562. return Material._TriangleStripDrawMode;
  30563. },
  30564. enumerable: true,
  30565. configurable: true
  30566. });
  30567. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30568. /**
  30569. * Returns the triangle fan draw mode.
  30570. */
  30571. get: function () {
  30572. return Material._TriangleFanDrawMode;
  30573. },
  30574. enumerable: true,
  30575. configurable: true
  30576. });
  30577. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30578. /**
  30579. * Returns the clock-wise side orientation.
  30580. */
  30581. get: function () {
  30582. return Material._ClockWiseSideOrientation;
  30583. },
  30584. enumerable: true,
  30585. configurable: true
  30586. });
  30587. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30588. /**
  30589. * Returns the counter clock-wise side orientation.
  30590. */
  30591. get: function () {
  30592. return Material._CounterClockWiseSideOrientation;
  30593. },
  30594. enumerable: true,
  30595. configurable: true
  30596. });
  30597. Object.defineProperty(Material, "TextureDirtyFlag", {
  30598. /**
  30599. * Returns the dirty texture flag value.
  30600. */
  30601. get: function () {
  30602. return Material._TextureDirtyFlag;
  30603. },
  30604. enumerable: true,
  30605. configurable: true
  30606. });
  30607. Object.defineProperty(Material, "LightDirtyFlag", {
  30608. /**
  30609. * Returns the dirty light flag value.
  30610. */
  30611. get: function () {
  30612. return Material._LightDirtyFlag;
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30618. /**
  30619. * Returns the dirty fresnel flag value.
  30620. */
  30621. get: function () {
  30622. return Material._FresnelDirtyFlag;
  30623. },
  30624. enumerable: true,
  30625. configurable: true
  30626. });
  30627. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30628. /**
  30629. * Returns the dirty attributes flag value.
  30630. */
  30631. get: function () {
  30632. return Material._AttributesDirtyFlag;
  30633. },
  30634. enumerable: true,
  30635. configurable: true
  30636. });
  30637. Object.defineProperty(Material, "MiscDirtyFlag", {
  30638. /**
  30639. * Returns the dirty misc flag value.
  30640. */
  30641. get: function () {
  30642. return Material._MiscDirtyFlag;
  30643. },
  30644. enumerable: true,
  30645. configurable: true
  30646. });
  30647. Object.defineProperty(Material.prototype, "alpha", {
  30648. /**
  30649. * Gets the alpha value of the material.
  30650. */
  30651. get: function () {
  30652. return this._alpha;
  30653. },
  30654. /**
  30655. * Sets the alpha value of the material.
  30656. */
  30657. set: function (value) {
  30658. if (this._alpha === value) {
  30659. return;
  30660. }
  30661. this._alpha = value;
  30662. this.markAsDirty(Material.MiscDirtyFlag);
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30668. /**
  30669. * Gets the back-face culling state.
  30670. */
  30671. get: function () {
  30672. return this._backFaceCulling;
  30673. },
  30674. /**
  30675. * Sets the back-face culling state.
  30676. */
  30677. set: function (value) {
  30678. if (this._backFaceCulling === value) {
  30679. return;
  30680. }
  30681. this._backFaceCulling = value;
  30682. this.markAsDirty(Material.TextureDirtyFlag);
  30683. },
  30684. enumerable: true,
  30685. configurable: true
  30686. });
  30687. Object.defineProperty(Material.prototype, "onDispose", {
  30688. /**
  30689. * Called during a dispose event.
  30690. */
  30691. set: function (callback) {
  30692. if (this._onDisposeObserver) {
  30693. this.onDisposeObservable.remove(this._onDisposeObserver);
  30694. }
  30695. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(Material.prototype, "onBind", {
  30701. /**
  30702. * Called during a bind event.
  30703. */
  30704. set: function (callback) {
  30705. if (this._onBindObserver) {
  30706. this.onBindObservable.remove(this._onBindObserver);
  30707. }
  30708. this._onBindObserver = this.onBindObservable.add(callback);
  30709. },
  30710. enumerable: true,
  30711. configurable: true
  30712. });
  30713. Object.defineProperty(Material.prototype, "alphaMode", {
  30714. /**
  30715. * Gets the value of the alpha mode.
  30716. */
  30717. get: function () {
  30718. return this._alphaMode;
  30719. },
  30720. /**
  30721. * Sets the value of the alpha mode.
  30722. */
  30723. set: function (value) {
  30724. if (this._alphaMode === value) {
  30725. return;
  30726. }
  30727. this._alphaMode = value;
  30728. this.markAsDirty(Material.TextureDirtyFlag);
  30729. },
  30730. enumerable: true,
  30731. configurable: true
  30732. });
  30733. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30734. /**
  30735. * Gets the depth pre-pass value.
  30736. */
  30737. get: function () {
  30738. return this._needDepthPrePass;
  30739. },
  30740. /**
  30741. * Sets the need depth pre-pass value.
  30742. */
  30743. set: function (value) {
  30744. if (this._needDepthPrePass === value) {
  30745. return;
  30746. }
  30747. this._needDepthPrePass = value;
  30748. if (this._needDepthPrePass) {
  30749. this.checkReadyOnEveryCall = true;
  30750. }
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. Object.defineProperty(Material.prototype, "fogEnabled", {
  30756. /**
  30757. * Gets the value of the fog enabled state.
  30758. */
  30759. get: function () {
  30760. return this._fogEnabled;
  30761. },
  30762. /**
  30763. * Sets the state for enabling fog.
  30764. */
  30765. set: function (value) {
  30766. if (this._fogEnabled === value) {
  30767. return;
  30768. }
  30769. this._fogEnabled = value;
  30770. this.markAsDirty(Material.MiscDirtyFlag);
  30771. },
  30772. enumerable: true,
  30773. configurable: true
  30774. });
  30775. Object.defineProperty(Material.prototype, "wireframe", {
  30776. /**
  30777. * Gets a value specifying if wireframe mode is enabled.
  30778. */
  30779. get: function () {
  30780. return this._fillMode === Material.WireFrameFillMode;
  30781. },
  30782. /**
  30783. * Sets the state of wireframe mode.
  30784. */
  30785. set: function (value) {
  30786. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30787. },
  30788. enumerable: true,
  30789. configurable: true
  30790. });
  30791. Object.defineProperty(Material.prototype, "pointsCloud", {
  30792. /**
  30793. * Gets the value specifying if point clouds are enabled.
  30794. */
  30795. get: function () {
  30796. return this._fillMode === Material.PointFillMode;
  30797. },
  30798. /**
  30799. * Sets the state of point cloud mode.
  30800. */
  30801. set: function (value) {
  30802. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. Object.defineProperty(Material.prototype, "fillMode", {
  30808. /**
  30809. * Gets the material fill mode.
  30810. */
  30811. get: function () {
  30812. return this._fillMode;
  30813. },
  30814. /**
  30815. * Sets the material fill mode.
  30816. */
  30817. set: function (value) {
  30818. if (this._fillMode === value) {
  30819. return;
  30820. }
  30821. this._fillMode = value;
  30822. this.markAsDirty(Material.MiscDirtyFlag);
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. /**
  30828. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30829. * subclasses should override adding information pertainent to themselves.
  30830. * @returns - String with material information.
  30831. */
  30832. Material.prototype.toString = function (fullDetails) {
  30833. var ret = "Name: " + this.name;
  30834. if (fullDetails) {
  30835. }
  30836. return ret;
  30837. };
  30838. /**
  30839. * Gets the class name of the material.
  30840. * @returns - String with the class name of the material.
  30841. */
  30842. Material.prototype.getClassName = function () {
  30843. return "Material";
  30844. };
  30845. Object.defineProperty(Material.prototype, "isFrozen", {
  30846. /**
  30847. * Specifies if updates for the material been locked.
  30848. */
  30849. get: function () {
  30850. return this.checkReadyOnlyOnce;
  30851. },
  30852. enumerable: true,
  30853. configurable: true
  30854. });
  30855. /**
  30856. * Locks updates for the material.
  30857. */
  30858. Material.prototype.freeze = function () {
  30859. this.checkReadyOnlyOnce = true;
  30860. };
  30861. /**
  30862. * Unlocks updates for the material.
  30863. */
  30864. Material.prototype.unfreeze = function () {
  30865. this.checkReadyOnlyOnce = false;
  30866. };
  30867. /**
  30868. * Specifies if the material is ready to be used.
  30869. * @param mesh - BJS mesh.
  30870. * @param useInstances - Specifies if instances should be used.
  30871. * @returns - Boolean indicating if the material is ready to be used.
  30872. */
  30873. Material.prototype.isReady = function (mesh, useInstances) {
  30874. return true;
  30875. };
  30876. /**
  30877. * Specifies that the submesh is ready to be used.
  30878. * @param mesh - BJS mesh.
  30879. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30880. * @param useInstances - Specifies that instances should be used.
  30881. * @returns - boolean indicating that the submesh is ready or not.
  30882. */
  30883. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30884. return false;
  30885. };
  30886. /**
  30887. * Returns the material effect.
  30888. * @returns - Nullable material effect.
  30889. */
  30890. Material.prototype.getEffect = function () {
  30891. return this._effect;
  30892. };
  30893. /**
  30894. * Returns the BJS scene.
  30895. * @returns - BJS Scene.
  30896. */
  30897. Material.prototype.getScene = function () {
  30898. return this._scene;
  30899. };
  30900. /**
  30901. * Specifies if the material will require alpha blending
  30902. * @returns - Boolean specifying if alpha blending is needed.
  30903. */
  30904. Material.prototype.needAlphaBlending = function () {
  30905. return (this.alpha < 1.0);
  30906. };
  30907. /**
  30908. * Specifies if the mesh will require alpha blending.
  30909. * @param mesh - BJS mesh.
  30910. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30911. */
  30912. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30913. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30914. };
  30915. /**
  30916. * Specifies if this material should be rendered in alpha test mode.
  30917. * @returns - Boolean specifying if an alpha test is needed.
  30918. */
  30919. Material.prototype.needAlphaTesting = function () {
  30920. return false;
  30921. };
  30922. /**
  30923. * Gets the texture used for the alpha test.
  30924. * @returns - Nullable alpha test texture.
  30925. */
  30926. Material.prototype.getAlphaTestTexture = function () {
  30927. return null;
  30928. };
  30929. /**
  30930. * Marks the material to indicate that it needs to be re-calculated.
  30931. */
  30932. Material.prototype.markDirty = function () {
  30933. this._wasPreviouslyReady = false;
  30934. };
  30935. Material.prototype._preBind = function (effect, overrideOrientation) {
  30936. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30937. var engine = this._scene.getEngine();
  30938. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30939. var reverse = orientation === Material.ClockWiseSideOrientation;
  30940. engine.enableEffect(effect ? effect : this._effect);
  30941. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30942. return reverse;
  30943. };
  30944. /**
  30945. * Binds the material to the mesh.
  30946. * @param world - World transformation matrix.
  30947. * @param mesh - Mesh to bind the material to.
  30948. */
  30949. Material.prototype.bind = function (world, mesh) {
  30950. };
  30951. /**
  30952. * Binds the submesh to the material.
  30953. * @param world - World transformation matrix.
  30954. * @param mesh - Mesh containing the submesh.
  30955. * @param subMesh - Submesh to bind the material to.
  30956. */
  30957. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30958. };
  30959. /**
  30960. * Binds the world matrix to the material.
  30961. * @param world - World transformation matrix.
  30962. */
  30963. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30964. };
  30965. /**
  30966. * Binds the scene's uniform buffer to the effect.
  30967. * @param effect - Effect to bind to the scene uniform buffer.
  30968. * @param sceneUbo - Scene uniform buffer.
  30969. */
  30970. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30971. sceneUbo.bindToEffect(effect, "Scene");
  30972. };
  30973. /**
  30974. * Binds the view matrix to the effect.
  30975. * @param effect - Effect to bind the view matrix to.
  30976. */
  30977. Material.prototype.bindView = function (effect) {
  30978. if (!this._useUBO) {
  30979. effect.setMatrix("view", this.getScene().getViewMatrix());
  30980. }
  30981. else {
  30982. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30983. }
  30984. };
  30985. /**
  30986. * Binds the view projection matrix to the effect.
  30987. * @param effect - Effect to bind the view projection matrix to.
  30988. */
  30989. Material.prototype.bindViewProjection = function (effect) {
  30990. if (!this._useUBO) {
  30991. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30992. }
  30993. else {
  30994. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30995. }
  30996. };
  30997. /**
  30998. * Specifies if material alpha testing should be turned on for the mesh.
  30999. * @param mesh - BJS mesh.
  31000. */
  31001. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31002. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31003. };
  31004. /**
  31005. * Processes to execute after binding the material to a mesh.
  31006. * @param mesh - BJS mesh.
  31007. */
  31008. Material.prototype._afterBind = function (mesh) {
  31009. this._scene._cachedMaterial = this;
  31010. if (mesh) {
  31011. this._scene._cachedVisibility = mesh.visibility;
  31012. }
  31013. else {
  31014. this._scene._cachedVisibility = 1;
  31015. }
  31016. if (mesh) {
  31017. this.onBindObservable.notifyObservers(mesh);
  31018. }
  31019. if (this.disableDepthWrite) {
  31020. var engine = this._scene.getEngine();
  31021. this._cachedDepthWriteState = engine.getDepthWrite();
  31022. engine.setDepthWrite(false);
  31023. }
  31024. };
  31025. /**
  31026. * Unbinds the material from the mesh.
  31027. */
  31028. Material.prototype.unbind = function () {
  31029. this.onUnBindObservable.notifyObservers(this);
  31030. if (this.disableDepthWrite) {
  31031. var engine = this._scene.getEngine();
  31032. engine.setDepthWrite(this._cachedDepthWriteState);
  31033. }
  31034. };
  31035. /**
  31036. * Gets the active textures from the material.
  31037. * @returns - Array of textures.
  31038. */
  31039. Material.prototype.getActiveTextures = function () {
  31040. return [];
  31041. };
  31042. /**
  31043. * Specifies if the material uses a texture.
  31044. * @param texture - Texture to check against the material.
  31045. * @returns - Boolean specifying if the material uses the texture.
  31046. */
  31047. Material.prototype.hasTexture = function (texture) {
  31048. return false;
  31049. };
  31050. /**
  31051. * Makes a duplicate of the material, and gives it a new name.
  31052. * @param name - Name to call the duplicated material.
  31053. * @returns - Nullable cloned material
  31054. */
  31055. Material.prototype.clone = function (name) {
  31056. return null;
  31057. };
  31058. /**
  31059. * Gets the meshes bound to the material.
  31060. * @returns - Array of meshes bound to the material.
  31061. */
  31062. Material.prototype.getBindedMeshes = function () {
  31063. var result = new Array();
  31064. for (var index = 0; index < this._scene.meshes.length; index++) {
  31065. var mesh = this._scene.meshes[index];
  31066. if (mesh.material === this) {
  31067. result.push(mesh);
  31068. }
  31069. }
  31070. return result;
  31071. };
  31072. /**
  31073. * Force shader compilation
  31074. * @param mesh - BJS mesh.
  31075. * @param onCompiled - function to execute once the material is compiled.
  31076. * @param options - options to pass to this function.
  31077. */
  31078. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31079. var _this = this;
  31080. var localOptions = __assign({ clipPlane: false }, options);
  31081. var subMesh = new BABYLON.BaseSubMesh();
  31082. var scene = this.getScene();
  31083. var checkReady = function () {
  31084. if (!_this._scene || !_this._scene.getEngine()) {
  31085. return;
  31086. }
  31087. if (subMesh._materialDefines) {
  31088. subMesh._materialDefines._renderId = -1;
  31089. }
  31090. var clipPlaneState = scene.clipPlane;
  31091. if (localOptions.clipPlane) {
  31092. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31093. }
  31094. if (_this.storeEffectOnSubMeshes) {
  31095. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31096. if (onCompiled) {
  31097. onCompiled(_this);
  31098. }
  31099. }
  31100. else {
  31101. setTimeout(checkReady, 16);
  31102. }
  31103. }
  31104. else {
  31105. if (_this.isReady(mesh)) {
  31106. if (onCompiled) {
  31107. onCompiled(_this);
  31108. }
  31109. }
  31110. else {
  31111. setTimeout(checkReady, 16);
  31112. }
  31113. }
  31114. if (localOptions.clipPlane) {
  31115. scene.clipPlane = clipPlaneState;
  31116. }
  31117. };
  31118. checkReady();
  31119. };
  31120. /**
  31121. * Force shader compilation.
  31122. * @param mesh The mesh that will use this material
  31123. * @param options Additional options for compiling the shaders
  31124. * @returns A promise that resolves when the compilation completes
  31125. */
  31126. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31127. var _this = this;
  31128. return new Promise(function (resolve) {
  31129. _this.forceCompilation(mesh, function () {
  31130. resolve();
  31131. }, options);
  31132. });
  31133. };
  31134. /**
  31135. * Marks a define in the material to indicate that it needs to be re-computed.
  31136. * @param flag - Material define flag.
  31137. */
  31138. Material.prototype.markAsDirty = function (flag) {
  31139. if (flag & Material.TextureDirtyFlag) {
  31140. this._markAllSubMeshesAsTexturesDirty();
  31141. }
  31142. if (flag & Material.LightDirtyFlag) {
  31143. this._markAllSubMeshesAsLightsDirty();
  31144. }
  31145. if (flag & Material.FresnelDirtyFlag) {
  31146. this._markAllSubMeshesAsFresnelDirty();
  31147. }
  31148. if (flag & Material.AttributesDirtyFlag) {
  31149. this._markAllSubMeshesAsAttributesDirty();
  31150. }
  31151. if (flag & Material.MiscDirtyFlag) {
  31152. this._markAllSubMeshesAsMiscDirty();
  31153. }
  31154. this.getScene().resetCachedMaterial();
  31155. };
  31156. /**
  31157. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31158. * @param func - function which checks material defines against the submeshes.
  31159. */
  31160. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31161. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31162. var mesh = _a[_i];
  31163. if (!mesh.subMeshes) {
  31164. continue;
  31165. }
  31166. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31167. var subMesh = _c[_b];
  31168. if (subMesh.getMaterial() !== this) {
  31169. continue;
  31170. }
  31171. if (!subMesh._materialDefines) {
  31172. continue;
  31173. }
  31174. func(subMesh._materialDefines);
  31175. }
  31176. }
  31177. };
  31178. /**
  31179. * Indicates that image processing needs to be re-calculated for all submeshes.
  31180. */
  31181. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31182. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31183. };
  31184. /**
  31185. * Indicates that textures need to be re-calculated for all submeshes.
  31186. */
  31187. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31188. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31189. };
  31190. /**
  31191. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31192. */
  31193. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31194. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31195. };
  31196. /**
  31197. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31198. */
  31199. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31200. this._markAllSubMeshesAsDirty(function (defines) {
  31201. defines.markAsFresnelDirty();
  31202. defines.markAsMiscDirty();
  31203. });
  31204. };
  31205. /**
  31206. * Indicates that lights need to be re-calculated for all submeshes.
  31207. */
  31208. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31209. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31210. };
  31211. /**
  31212. * Indicates that attributes need to be re-calculated for all submeshes.
  31213. */
  31214. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31215. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31216. };
  31217. /**
  31218. * Indicates that misc needs to be re-calculated for all submeshes.
  31219. */
  31220. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31221. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31222. };
  31223. /**
  31224. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31225. */
  31226. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31227. this._markAllSubMeshesAsDirty(function (defines) {
  31228. defines.markAsTexturesDirty();
  31229. defines.markAsMiscDirty();
  31230. });
  31231. };
  31232. /**
  31233. * Disposes the material.
  31234. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31235. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31236. */
  31237. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31238. // Animations
  31239. this.getScene().stopAnimation(this);
  31240. // Remove from scene
  31241. var index = this._scene.materials.indexOf(this);
  31242. if (index >= 0) {
  31243. this._scene.materials.splice(index, 1);
  31244. }
  31245. // Remove from meshes
  31246. for (index = 0; index < this._scene.meshes.length; index++) {
  31247. var mesh = this._scene.meshes[index];
  31248. if (mesh.material === this) {
  31249. mesh.material = null;
  31250. if (mesh.geometry) {
  31251. var geometry = (mesh.geometry);
  31252. if (this.storeEffectOnSubMeshes) {
  31253. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31254. var subMesh = _a[_i];
  31255. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31256. if (forceDisposeEffect && subMesh._materialEffect) {
  31257. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31258. }
  31259. }
  31260. }
  31261. else {
  31262. geometry._releaseVertexArrayObject(this._effect);
  31263. }
  31264. }
  31265. }
  31266. }
  31267. this._uniformBuffer.dispose();
  31268. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31269. if (forceDisposeEffect && this._effect) {
  31270. if (!this.storeEffectOnSubMeshes) {
  31271. this._scene.getEngine()._releaseEffect(this._effect);
  31272. }
  31273. this._effect = null;
  31274. }
  31275. // Callback
  31276. this.onDisposeObservable.notifyObservers(this);
  31277. this.onDisposeObservable.clear();
  31278. this.onBindObservable.clear();
  31279. this.onUnBindObservable.clear();
  31280. };
  31281. /**
  31282. * Serializes this material.
  31283. * @returns - serialized material object.
  31284. */
  31285. Material.prototype.serialize = function () {
  31286. return BABYLON.SerializationHelper.Serialize(this);
  31287. };
  31288. /**
  31289. * Creates a MultiMaterial from parse MultiMaterial data.
  31290. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31291. * @param scene - BJS scene.
  31292. * @returns - MultiMaterial.
  31293. */
  31294. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31295. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31296. multiMaterial.id = parsedMultiMaterial.id;
  31297. if (BABYLON.Tags) {
  31298. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31299. }
  31300. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31301. var subMatId = parsedMultiMaterial.materials[matIndex];
  31302. if (subMatId) {
  31303. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31304. }
  31305. else {
  31306. multiMaterial.subMaterials.push(null);
  31307. }
  31308. }
  31309. return multiMaterial;
  31310. };
  31311. /**
  31312. * Creates a material from parsed material data.
  31313. * @param parsedMaterial - Parsed material data.
  31314. * @param scene - BJS scene.
  31315. * @param rootUrl - Root URL containing the material information.
  31316. * @returns - Parsed material.
  31317. */
  31318. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31319. if (!parsedMaterial.customType) {
  31320. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31321. }
  31322. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31323. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31324. if (!BABYLON.LegacyPBRMaterial) {
  31325. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31326. return;
  31327. }
  31328. }
  31329. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31330. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31331. ;
  31332. };
  31333. // Triangle views
  31334. Material._TriangleFillMode = 0;
  31335. Material._WireFrameFillMode = 1;
  31336. Material._PointFillMode = 2;
  31337. // Draw modes
  31338. Material._PointListDrawMode = 3;
  31339. Material._LineListDrawMode = 4;
  31340. Material._LineLoopDrawMode = 5;
  31341. Material._LineStripDrawMode = 6;
  31342. Material._TriangleStripDrawMode = 7;
  31343. Material._TriangleFanDrawMode = 8;
  31344. /**
  31345. * Stores the clock-wise side orientation.
  31346. */
  31347. Material._ClockWiseSideOrientation = 0;
  31348. /**
  31349. * Stores the counter clock-wise side orientation.
  31350. */
  31351. Material._CounterClockWiseSideOrientation = 1;
  31352. /**
  31353. * The dirty texture flag value.
  31354. */
  31355. Material._TextureDirtyFlag = 1;
  31356. /**
  31357. * The dirty light flag value.
  31358. */
  31359. Material._LightDirtyFlag = 2;
  31360. /**
  31361. * The dirty fresnel flag value.
  31362. */
  31363. Material._FresnelDirtyFlag = 4;
  31364. /**
  31365. * The dirty attribute flag value.
  31366. */
  31367. Material._AttributesDirtyFlag = 8;
  31368. /**
  31369. * The dirty misc flag value.
  31370. */
  31371. Material._MiscDirtyFlag = 16;
  31372. __decorate([
  31373. BABYLON.serialize()
  31374. ], Material.prototype, "id", void 0);
  31375. __decorate([
  31376. BABYLON.serialize()
  31377. ], Material.prototype, "name", void 0);
  31378. __decorate([
  31379. BABYLON.serialize()
  31380. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31381. __decorate([
  31382. BABYLON.serialize()
  31383. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31384. __decorate([
  31385. BABYLON.serialize()
  31386. ], Material.prototype, "state", void 0);
  31387. __decorate([
  31388. BABYLON.serialize("alpha")
  31389. ], Material.prototype, "_alpha", void 0);
  31390. __decorate([
  31391. BABYLON.serialize("backFaceCulling")
  31392. ], Material.prototype, "_backFaceCulling", void 0);
  31393. __decorate([
  31394. BABYLON.serialize()
  31395. ], Material.prototype, "sideOrientation", void 0);
  31396. __decorate([
  31397. BABYLON.serialize("alphaMode")
  31398. ], Material.prototype, "_alphaMode", void 0);
  31399. __decorate([
  31400. BABYLON.serialize()
  31401. ], Material.prototype, "_needDepthPrePass", void 0);
  31402. __decorate([
  31403. BABYLON.serialize()
  31404. ], Material.prototype, "disableDepthWrite", void 0);
  31405. __decorate([
  31406. BABYLON.serialize()
  31407. ], Material.prototype, "forceDepthWrite", void 0);
  31408. __decorate([
  31409. BABYLON.serialize()
  31410. ], Material.prototype, "separateCullingPass", void 0);
  31411. __decorate([
  31412. BABYLON.serialize("fogEnabled")
  31413. ], Material.prototype, "_fogEnabled", void 0);
  31414. __decorate([
  31415. BABYLON.serialize()
  31416. ], Material.prototype, "pointSize", void 0);
  31417. __decorate([
  31418. BABYLON.serialize()
  31419. ], Material.prototype, "zOffset", void 0);
  31420. __decorate([
  31421. BABYLON.serialize()
  31422. ], Material.prototype, "wireframe", null);
  31423. __decorate([
  31424. BABYLON.serialize()
  31425. ], Material.prototype, "pointsCloud", null);
  31426. __decorate([
  31427. BABYLON.serialize()
  31428. ], Material.prototype, "fillMode", null);
  31429. return Material;
  31430. }());
  31431. BABYLON.Material = Material;
  31432. })(BABYLON || (BABYLON = {}));
  31433. //# sourceMappingURL=babylon.material.js.map
  31434. var BABYLON;
  31435. (function (BABYLON) {
  31436. var UniformBuffer = /** @class */ (function () {
  31437. /**
  31438. * Uniform buffer objects.
  31439. *
  31440. * Handles blocks of uniform on the GPU.
  31441. *
  31442. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31443. *
  31444. * For more information, please refer to :
  31445. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31446. */
  31447. function UniformBuffer(engine, data, dynamic) {
  31448. this._engine = engine;
  31449. this._noUBO = !engine.supportsUniformBuffers;
  31450. this._dynamic = dynamic;
  31451. this._data = data || [];
  31452. this._uniformLocations = {};
  31453. this._uniformSizes = {};
  31454. this._uniformLocationPointer = 0;
  31455. this._needSync = false;
  31456. if (this._noUBO) {
  31457. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31458. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31459. this.updateFloat = this._updateFloatForEffect;
  31460. this.updateFloat2 = this._updateFloat2ForEffect;
  31461. this.updateFloat3 = this._updateFloat3ForEffect;
  31462. this.updateFloat4 = this._updateFloat4ForEffect;
  31463. this.updateMatrix = this._updateMatrixForEffect;
  31464. this.updateVector3 = this._updateVector3ForEffect;
  31465. this.updateVector4 = this._updateVector4ForEffect;
  31466. this.updateColor3 = this._updateColor3ForEffect;
  31467. this.updateColor4 = this._updateColor4ForEffect;
  31468. }
  31469. else {
  31470. this._engine._uniformBuffers.push(this);
  31471. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31472. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31473. this.updateFloat = this._updateFloatForUniform;
  31474. this.updateFloat2 = this._updateFloat2ForUniform;
  31475. this.updateFloat3 = this._updateFloat3ForUniform;
  31476. this.updateFloat4 = this._updateFloat4ForUniform;
  31477. this.updateMatrix = this._updateMatrixForUniform;
  31478. this.updateVector3 = this._updateVector3ForUniform;
  31479. this.updateVector4 = this._updateVector4ForUniform;
  31480. this.updateColor3 = this._updateColor3ForUniform;
  31481. this.updateColor4 = this._updateColor4ForUniform;
  31482. }
  31483. }
  31484. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31485. // Properties
  31486. /**
  31487. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31488. * or just falling back on setUniformXXX calls.
  31489. */
  31490. get: function () {
  31491. return !this._noUBO;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31497. /**
  31498. * Indicates if the WebGL underlying uniform buffer is in sync
  31499. * with the javascript cache data.
  31500. */
  31501. get: function () {
  31502. return !this._needSync;
  31503. },
  31504. enumerable: true,
  31505. configurable: true
  31506. });
  31507. /**
  31508. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31509. * Also, a dynamic UniformBuffer will disable cache verification and always
  31510. * update the underlying WebGL uniform buffer to the GPU.
  31511. */
  31512. UniformBuffer.prototype.isDynamic = function () {
  31513. return this._dynamic !== undefined;
  31514. };
  31515. /**
  31516. * The data cache on JS side.
  31517. */
  31518. UniformBuffer.prototype.getData = function () {
  31519. return this._bufferData;
  31520. };
  31521. /**
  31522. * The underlying WebGL Uniform buffer.
  31523. */
  31524. UniformBuffer.prototype.getBuffer = function () {
  31525. return this._buffer;
  31526. };
  31527. /**
  31528. * std140 layout specifies how to align data within an UBO structure.
  31529. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31530. * for specs.
  31531. */
  31532. UniformBuffer.prototype._fillAlignment = function (size) {
  31533. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31534. // and 4x4 matrices
  31535. // TODO : change if other types are used
  31536. var alignment;
  31537. if (size <= 2) {
  31538. alignment = size;
  31539. }
  31540. else {
  31541. alignment = 4;
  31542. }
  31543. if ((this._uniformLocationPointer % alignment) !== 0) {
  31544. var oldPointer = this._uniformLocationPointer;
  31545. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31546. var diff = this._uniformLocationPointer - oldPointer;
  31547. for (var i = 0; i < diff; i++) {
  31548. this._data.push(0);
  31549. }
  31550. }
  31551. };
  31552. /**
  31553. * Adds an uniform in the buffer.
  31554. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31555. * for the layout to be correct !
  31556. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31557. * @param {number|number[]} size Data size, or data directly.
  31558. */
  31559. UniformBuffer.prototype.addUniform = function (name, size) {
  31560. if (this._noUBO) {
  31561. return;
  31562. }
  31563. if (this._uniformLocations[name] !== undefined) {
  31564. // Already existing uniform
  31565. return;
  31566. }
  31567. // This function must be called in the order of the shader layout !
  31568. // size can be the size of the uniform, or data directly
  31569. var data;
  31570. if (size instanceof Array) {
  31571. data = size;
  31572. size = data.length;
  31573. }
  31574. else {
  31575. size = size;
  31576. data = [];
  31577. // Fill with zeros
  31578. for (var i = 0; i < size; i++) {
  31579. data.push(0);
  31580. }
  31581. }
  31582. this._fillAlignment(size);
  31583. this._uniformSizes[name] = size;
  31584. this._uniformLocations[name] = this._uniformLocationPointer;
  31585. this._uniformLocationPointer += size;
  31586. for (var i = 0; i < size; i++) {
  31587. this._data.push(data[i]);
  31588. }
  31589. this._needSync = true;
  31590. };
  31591. /**
  31592. * Wrapper for addUniform.
  31593. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31594. * @param {Matrix} mat A 4x4 matrix.
  31595. */
  31596. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31597. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31598. };
  31599. /**
  31600. * Wrapper for addUniform.
  31601. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31602. * @param {number} x
  31603. * @param {number} y
  31604. */
  31605. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31606. var temp = [x, y];
  31607. this.addUniform(name, temp);
  31608. };
  31609. /**
  31610. * Wrapper for addUniform.
  31611. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31612. * @param {number} x
  31613. * @param {number} y
  31614. * @param {number} z
  31615. */
  31616. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31617. var temp = [x, y, z];
  31618. this.addUniform(name, temp);
  31619. };
  31620. /**
  31621. * Wrapper for addUniform.
  31622. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31623. * @param {Color3} color
  31624. */
  31625. UniformBuffer.prototype.addColor3 = function (name, color) {
  31626. var temp = new Array();
  31627. color.toArray(temp);
  31628. this.addUniform(name, temp);
  31629. };
  31630. /**
  31631. * Wrapper for addUniform.
  31632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31633. * @param {Color3} color
  31634. * @param {number} alpha
  31635. */
  31636. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31637. var temp = new Array();
  31638. color.toArray(temp);
  31639. temp.push(alpha);
  31640. this.addUniform(name, temp);
  31641. };
  31642. /**
  31643. * Wrapper for addUniform.
  31644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31645. * @param {Vector3} vector
  31646. */
  31647. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31648. var temp = new Array();
  31649. vector.toArray(temp);
  31650. this.addUniform(name, temp);
  31651. };
  31652. /**
  31653. * Wrapper for addUniform.
  31654. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31655. */
  31656. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31657. this.addUniform(name, 12);
  31658. };
  31659. /**
  31660. * Wrapper for addUniform.
  31661. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31662. */
  31663. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31664. this.addUniform(name, 8);
  31665. };
  31666. /**
  31667. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31668. */
  31669. UniformBuffer.prototype.create = function () {
  31670. if (this._noUBO) {
  31671. return;
  31672. }
  31673. if (this._buffer) {
  31674. return; // nothing to do
  31675. }
  31676. // See spec, alignment must be filled as a vec4
  31677. this._fillAlignment(4);
  31678. this._bufferData = new Float32Array(this._data);
  31679. this._rebuild();
  31680. this._needSync = true;
  31681. };
  31682. UniformBuffer.prototype._rebuild = function () {
  31683. if (this._noUBO) {
  31684. return;
  31685. }
  31686. if (this._dynamic) {
  31687. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31688. }
  31689. else {
  31690. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31691. }
  31692. };
  31693. /**
  31694. * Updates the WebGL Uniform Buffer on the GPU.
  31695. * If the `dynamic` flag is set to true, no cache comparison is done.
  31696. * Otherwise, the buffer will be updated only if the cache differs.
  31697. */
  31698. UniformBuffer.prototype.update = function () {
  31699. if (!this._buffer) {
  31700. this.create();
  31701. return;
  31702. }
  31703. if (!this._dynamic && !this._needSync) {
  31704. return;
  31705. }
  31706. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31707. this._needSync = false;
  31708. };
  31709. /**
  31710. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31711. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31712. * @param {number[]|Float32Array} data Flattened data
  31713. * @param {number} size Size of the data.
  31714. */
  31715. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31716. var location = this._uniformLocations[uniformName];
  31717. if (location === undefined) {
  31718. if (this._buffer) {
  31719. // Cannot add an uniform if the buffer is already created
  31720. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31721. return;
  31722. }
  31723. this.addUniform(uniformName, size);
  31724. location = this._uniformLocations[uniformName];
  31725. }
  31726. if (!this._buffer) {
  31727. this.create();
  31728. }
  31729. if (!this._dynamic) {
  31730. // Cache for static uniform buffers
  31731. var changed = false;
  31732. for (var i = 0; i < size; i++) {
  31733. if (this._bufferData[location + i] !== data[i]) {
  31734. changed = true;
  31735. this._bufferData[location + i] = data[i];
  31736. }
  31737. }
  31738. this._needSync = this._needSync || changed;
  31739. }
  31740. else {
  31741. // No cache for dynamic
  31742. for (var i = 0; i < size; i++) {
  31743. this._bufferData[location + i] = data[i];
  31744. }
  31745. }
  31746. };
  31747. // Update methods
  31748. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31749. // To match std140, matrix must be realigned
  31750. for (var i = 0; i < 3; i++) {
  31751. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31752. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31753. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31754. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31755. }
  31756. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31757. };
  31758. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31759. this._currentEffect.setMatrix3x3(name, matrix);
  31760. };
  31761. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31762. this._currentEffect.setMatrix2x2(name, matrix);
  31763. };
  31764. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31765. // To match std140, matrix must be realigned
  31766. for (var i = 0; i < 2; i++) {
  31767. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31768. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31769. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31770. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31771. }
  31772. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31773. };
  31774. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31775. this._currentEffect.setFloat(name, x);
  31776. };
  31777. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31778. UniformBuffer._tempBuffer[0] = x;
  31779. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31780. };
  31781. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31782. if (suffix === void 0) { suffix = ""; }
  31783. this._currentEffect.setFloat2(name + suffix, x, y);
  31784. };
  31785. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31786. if (suffix === void 0) { suffix = ""; }
  31787. UniformBuffer._tempBuffer[0] = x;
  31788. UniformBuffer._tempBuffer[1] = y;
  31789. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31790. };
  31791. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31792. if (suffix === void 0) { suffix = ""; }
  31793. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31794. };
  31795. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31796. if (suffix === void 0) { suffix = ""; }
  31797. UniformBuffer._tempBuffer[0] = x;
  31798. UniformBuffer._tempBuffer[1] = y;
  31799. UniformBuffer._tempBuffer[2] = z;
  31800. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31801. };
  31802. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31803. if (suffix === void 0) { suffix = ""; }
  31804. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31805. };
  31806. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31807. if (suffix === void 0) { suffix = ""; }
  31808. UniformBuffer._tempBuffer[0] = x;
  31809. UniformBuffer._tempBuffer[1] = y;
  31810. UniformBuffer._tempBuffer[2] = z;
  31811. UniformBuffer._tempBuffer[3] = w;
  31812. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31813. };
  31814. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31815. this._currentEffect.setMatrix(name, mat);
  31816. };
  31817. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31818. this.updateUniform(name, mat.toArray(), 16);
  31819. };
  31820. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31821. this._currentEffect.setVector3(name, vector);
  31822. };
  31823. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31824. vector.toArray(UniformBuffer._tempBuffer);
  31825. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31826. };
  31827. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31828. this._currentEffect.setVector4(name, vector);
  31829. };
  31830. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31831. vector.toArray(UniformBuffer._tempBuffer);
  31832. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31833. };
  31834. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31835. if (suffix === void 0) { suffix = ""; }
  31836. this._currentEffect.setColor3(name + suffix, color);
  31837. };
  31838. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31839. if (suffix === void 0) { suffix = ""; }
  31840. color.toArray(UniformBuffer._tempBuffer);
  31841. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31842. };
  31843. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31844. if (suffix === void 0) { suffix = ""; }
  31845. this._currentEffect.setColor4(name + suffix, color, alpha);
  31846. };
  31847. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31848. if (suffix === void 0) { suffix = ""; }
  31849. color.toArray(UniformBuffer._tempBuffer);
  31850. UniformBuffer._tempBuffer[3] = alpha;
  31851. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31852. };
  31853. /**
  31854. * Sets a sampler uniform on the effect.
  31855. * @param {string} name Name of the sampler.
  31856. * @param {Texture} texture
  31857. */
  31858. UniformBuffer.prototype.setTexture = function (name, texture) {
  31859. this._currentEffect.setTexture(name, texture);
  31860. };
  31861. /**
  31862. * Directly updates the value of the uniform in the cache AND on the GPU.
  31863. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31864. * @param {number[]|Float32Array} data Flattened data
  31865. */
  31866. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31867. this.updateUniform(uniformName, data, data.length);
  31868. this.update();
  31869. };
  31870. /**
  31871. * Binds this uniform buffer to an effect.
  31872. * @param {Effect} effect
  31873. * @param {string} name Name of the uniform block in the shader.
  31874. */
  31875. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31876. this._currentEffect = effect;
  31877. if (this._noUBO || !this._buffer) {
  31878. return;
  31879. }
  31880. effect.bindUniformBuffer(this._buffer, name);
  31881. };
  31882. /**
  31883. * Disposes the uniform buffer.
  31884. */
  31885. UniformBuffer.prototype.dispose = function () {
  31886. if (this._noUBO) {
  31887. return;
  31888. }
  31889. var index = this._engine._uniformBuffers.indexOf(this);
  31890. if (index !== -1) {
  31891. this._engine._uniformBuffers.splice(index, 1);
  31892. }
  31893. if (!this._buffer) {
  31894. return;
  31895. }
  31896. if (this._engine._releaseBuffer(this._buffer)) {
  31897. this._buffer = null;
  31898. }
  31899. };
  31900. // Pool for avoiding memory leaks
  31901. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31902. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31903. return UniformBuffer;
  31904. }());
  31905. BABYLON.UniformBuffer = UniformBuffer;
  31906. })(BABYLON || (BABYLON = {}));
  31907. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31908. var BABYLON;
  31909. (function (BABYLON) {
  31910. var VertexData = /** @class */ (function () {
  31911. function VertexData() {
  31912. }
  31913. VertexData.prototype.set = function (data, kind) {
  31914. switch (kind) {
  31915. case BABYLON.VertexBuffer.PositionKind:
  31916. this.positions = data;
  31917. break;
  31918. case BABYLON.VertexBuffer.NormalKind:
  31919. this.normals = data;
  31920. break;
  31921. case BABYLON.VertexBuffer.TangentKind:
  31922. this.tangents = data;
  31923. break;
  31924. case BABYLON.VertexBuffer.UVKind:
  31925. this.uvs = data;
  31926. break;
  31927. case BABYLON.VertexBuffer.UV2Kind:
  31928. this.uvs2 = data;
  31929. break;
  31930. case BABYLON.VertexBuffer.UV3Kind:
  31931. this.uvs3 = data;
  31932. break;
  31933. case BABYLON.VertexBuffer.UV4Kind:
  31934. this.uvs4 = data;
  31935. break;
  31936. case BABYLON.VertexBuffer.UV5Kind:
  31937. this.uvs5 = data;
  31938. break;
  31939. case BABYLON.VertexBuffer.UV6Kind:
  31940. this.uvs6 = data;
  31941. break;
  31942. case BABYLON.VertexBuffer.ColorKind:
  31943. this.colors = data;
  31944. break;
  31945. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31946. this.matricesIndices = data;
  31947. break;
  31948. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31949. this.matricesWeights = data;
  31950. break;
  31951. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31952. this.matricesIndicesExtra = data;
  31953. break;
  31954. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31955. this.matricesWeightsExtra = data;
  31956. break;
  31957. }
  31958. };
  31959. /**
  31960. * Associates the vertexData to the passed Mesh.
  31961. * Sets it as updatable or not (default `false`).
  31962. * Returns the VertexData.
  31963. */
  31964. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31965. this._applyTo(mesh, updatable);
  31966. return this;
  31967. };
  31968. /**
  31969. * Associates the vertexData to the passed Geometry.
  31970. * Sets it as updatable or not (default `false`).
  31971. * Returns the VertexData.
  31972. */
  31973. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31974. this._applyTo(geometry, updatable);
  31975. return this;
  31976. };
  31977. /**
  31978. * Updates the associated mesh.
  31979. * Returns the VertexData.
  31980. */
  31981. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31982. this._update(mesh);
  31983. return this;
  31984. };
  31985. /**
  31986. * Updates the associated geometry.
  31987. * Returns the VertexData.
  31988. */
  31989. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31990. this._update(geometry);
  31991. return this;
  31992. };
  31993. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31994. if (updatable === void 0) { updatable = false; }
  31995. if (this.positions) {
  31996. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31997. }
  31998. if (this.normals) {
  31999. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32000. }
  32001. if (this.tangents) {
  32002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32003. }
  32004. if (this.uvs) {
  32005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32006. }
  32007. if (this.uvs2) {
  32008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32009. }
  32010. if (this.uvs3) {
  32011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32012. }
  32013. if (this.uvs4) {
  32014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32015. }
  32016. if (this.uvs5) {
  32017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32018. }
  32019. if (this.uvs6) {
  32020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32021. }
  32022. if (this.colors) {
  32023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32024. }
  32025. if (this.matricesIndices) {
  32026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32027. }
  32028. if (this.matricesWeights) {
  32029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32030. }
  32031. if (this.matricesIndicesExtra) {
  32032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32033. }
  32034. if (this.matricesWeightsExtra) {
  32035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32036. }
  32037. if (this.indices) {
  32038. meshOrGeometry.setIndices(this.indices, null, updatable);
  32039. }
  32040. return this;
  32041. };
  32042. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32043. if (this.positions) {
  32044. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32045. }
  32046. if (this.normals) {
  32047. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32048. }
  32049. if (this.tangents) {
  32050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32051. }
  32052. if (this.uvs) {
  32053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32054. }
  32055. if (this.uvs2) {
  32056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32057. }
  32058. if (this.uvs3) {
  32059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32060. }
  32061. if (this.uvs4) {
  32062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32063. }
  32064. if (this.uvs5) {
  32065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32066. }
  32067. if (this.uvs6) {
  32068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32069. }
  32070. if (this.colors) {
  32071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32072. }
  32073. if (this.matricesIndices) {
  32074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32075. }
  32076. if (this.matricesWeights) {
  32077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32078. }
  32079. if (this.matricesIndicesExtra) {
  32080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32081. }
  32082. if (this.matricesWeightsExtra) {
  32083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32084. }
  32085. if (this.indices) {
  32086. meshOrGeometry.setIndices(this.indices, null);
  32087. }
  32088. return this;
  32089. };
  32090. /**
  32091. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32092. * Returns the VertexData.
  32093. */
  32094. VertexData.prototype.transform = function (matrix) {
  32095. var transformed = BABYLON.Vector3.Zero();
  32096. var index;
  32097. if (this.positions) {
  32098. var position = BABYLON.Vector3.Zero();
  32099. for (index = 0; index < this.positions.length; index += 3) {
  32100. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32101. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32102. this.positions[index] = transformed.x;
  32103. this.positions[index + 1] = transformed.y;
  32104. this.positions[index + 2] = transformed.z;
  32105. }
  32106. }
  32107. if (this.normals) {
  32108. var normal = BABYLON.Vector3.Zero();
  32109. for (index = 0; index < this.normals.length; index += 3) {
  32110. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32111. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32112. this.normals[index] = transformed.x;
  32113. this.normals[index + 1] = transformed.y;
  32114. this.normals[index + 2] = transformed.z;
  32115. }
  32116. }
  32117. if (this.tangents) {
  32118. var tangent = BABYLON.Vector4.Zero();
  32119. var tangentTransformed = BABYLON.Vector4.Zero();
  32120. for (index = 0; index < this.tangents.length; index += 4) {
  32121. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32122. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32123. this.tangents[index] = tangentTransformed.x;
  32124. this.tangents[index + 1] = tangentTransformed.y;
  32125. this.tangents[index + 2] = tangentTransformed.z;
  32126. this.tangents[index + 3] = tangentTransformed.w;
  32127. }
  32128. }
  32129. return this;
  32130. };
  32131. /**
  32132. * Merges the passed VertexData into the current one.
  32133. * Returns the modified VertexData.
  32134. */
  32135. VertexData.prototype.merge = function (other) {
  32136. this._validate();
  32137. other._validate();
  32138. if (!this.normals !== !other.normals ||
  32139. !this.tangents !== !other.tangents ||
  32140. !this.uvs !== !other.uvs ||
  32141. !this.uvs2 !== !other.uvs2 ||
  32142. !this.uvs3 !== !other.uvs3 ||
  32143. !this.uvs4 !== !other.uvs4 ||
  32144. !this.uvs5 !== !other.uvs5 ||
  32145. !this.uvs6 !== !other.uvs6 ||
  32146. !this.colors !== !other.colors ||
  32147. !this.matricesIndices !== !other.matricesIndices ||
  32148. !this.matricesWeights !== !other.matricesWeights ||
  32149. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32150. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32151. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32152. }
  32153. if (other.indices) {
  32154. if (!this.indices) {
  32155. this.indices = [];
  32156. }
  32157. var offset = this.positions ? this.positions.length / 3 : 0;
  32158. for (var index = 0; index < other.indices.length; index++) {
  32159. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32160. this.indices.push(other.indices[index] + offset);
  32161. }
  32162. }
  32163. this.positions = this._mergeElement(this.positions, other.positions);
  32164. this.normals = this._mergeElement(this.normals, other.normals);
  32165. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32166. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32167. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32168. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32169. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32170. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32171. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32172. this.colors = this._mergeElement(this.colors, other.colors);
  32173. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32174. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32175. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32176. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32177. return this;
  32178. };
  32179. VertexData.prototype._mergeElement = function (source, other) {
  32180. if (!source) {
  32181. return other;
  32182. }
  32183. if (!other) {
  32184. return source;
  32185. }
  32186. var len = other.length + source.length;
  32187. var isSrcTypedArray = source instanceof Float32Array;
  32188. var isOthTypedArray = other instanceof Float32Array;
  32189. // use non-loop method when the source is Float32Array
  32190. if (isSrcTypedArray) {
  32191. var ret32 = new Float32Array(len);
  32192. ret32.set(source);
  32193. ret32.set(other, source.length);
  32194. return ret32;
  32195. // source is number[], when other is also use concat
  32196. }
  32197. else if (!isOthTypedArray) {
  32198. return source.concat(other);
  32199. // source is a number[], but other is a Float32Array, loop required
  32200. }
  32201. else {
  32202. var ret = source.slice(0); // copy source to a separate array
  32203. for (var i = 0, len = other.length; i < len; i++) {
  32204. ret.push(other[i]);
  32205. }
  32206. return ret;
  32207. }
  32208. };
  32209. VertexData.prototype._validate = function () {
  32210. if (!this.positions) {
  32211. throw new Error("Positions are required");
  32212. }
  32213. var getElementCount = function (kind, values) {
  32214. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32215. if ((values.length % stride) !== 0) {
  32216. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32217. }
  32218. return values.length / stride;
  32219. };
  32220. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32221. var validateElementCount = function (kind, values) {
  32222. var elementCount = getElementCount(kind, values);
  32223. if (elementCount !== positionsElementCount) {
  32224. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32225. }
  32226. };
  32227. if (this.normals)
  32228. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32229. if (this.tangents)
  32230. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32231. if (this.uvs)
  32232. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32233. if (this.uvs2)
  32234. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32235. if (this.uvs3)
  32236. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32237. if (this.uvs4)
  32238. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32239. if (this.uvs5)
  32240. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32241. if (this.uvs6)
  32242. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32243. if (this.colors)
  32244. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32245. if (this.matricesIndices)
  32246. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32247. if (this.matricesWeights)
  32248. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32249. if (this.matricesIndicesExtra)
  32250. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32251. if (this.matricesWeightsExtra)
  32252. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32253. };
  32254. /**
  32255. * Serializes the VertexData.
  32256. * Returns a serialized object.
  32257. */
  32258. VertexData.prototype.serialize = function () {
  32259. var serializationObject = this.serialize();
  32260. if (this.positions) {
  32261. serializationObject.positions = this.positions;
  32262. }
  32263. if (this.normals) {
  32264. serializationObject.normals = this.normals;
  32265. }
  32266. if (this.tangents) {
  32267. serializationObject.tangents = this.tangents;
  32268. }
  32269. if (this.uvs) {
  32270. serializationObject.uvs = this.uvs;
  32271. }
  32272. if (this.uvs2) {
  32273. serializationObject.uvs2 = this.uvs2;
  32274. }
  32275. if (this.uvs3) {
  32276. serializationObject.uvs3 = this.uvs3;
  32277. }
  32278. if (this.uvs4) {
  32279. serializationObject.uvs4 = this.uvs4;
  32280. }
  32281. if (this.uvs5) {
  32282. serializationObject.uvs5 = this.uvs5;
  32283. }
  32284. if (this.uvs6) {
  32285. serializationObject.uvs6 = this.uvs6;
  32286. }
  32287. if (this.colors) {
  32288. serializationObject.colors = this.colors;
  32289. }
  32290. if (this.matricesIndices) {
  32291. serializationObject.matricesIndices = this.matricesIndices;
  32292. serializationObject.matricesIndices._isExpanded = true;
  32293. }
  32294. if (this.matricesWeights) {
  32295. serializationObject.matricesWeights = this.matricesWeights;
  32296. }
  32297. if (this.matricesIndicesExtra) {
  32298. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32299. serializationObject.matricesIndicesExtra._isExpanded = true;
  32300. }
  32301. if (this.matricesWeightsExtra) {
  32302. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32303. }
  32304. serializationObject.indices = this.indices;
  32305. return serializationObject;
  32306. };
  32307. // Statics
  32308. /**
  32309. * Returns the object VertexData associated to the passed mesh.
  32310. */
  32311. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32312. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32313. };
  32314. /**
  32315. * Returns the object VertexData associated to the passed geometry.
  32316. */
  32317. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32318. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32319. };
  32320. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32321. var result = new VertexData();
  32322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32323. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32324. }
  32325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32326. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32327. }
  32328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32329. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32330. }
  32331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32332. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32333. }
  32334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32335. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32336. }
  32337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32338. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32339. }
  32340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32341. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32342. }
  32343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32344. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32345. }
  32346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32347. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32348. }
  32349. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32350. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32351. }
  32352. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32353. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32354. }
  32355. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32356. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32357. }
  32358. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32359. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32360. }
  32361. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32362. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32363. }
  32364. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32365. return result;
  32366. };
  32367. /**
  32368. * Creates the vertexData of the Ribbon.
  32369. */
  32370. VertexData.CreateRibbon = function (options) {
  32371. var pathArray = options.pathArray;
  32372. var closeArray = options.closeArray || false;
  32373. var closePath = options.closePath || false;
  32374. var invertUV = options.invertUV || false;
  32375. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32376. var offset = options.offset || defaultOffset;
  32377. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32378. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32379. var customUV = options.uvs;
  32380. var customColors = options.colors;
  32381. var positions = [];
  32382. var indices = [];
  32383. var normals = [];
  32384. var uvs = [];
  32385. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32386. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32387. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32388. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32389. var minlg; // minimal length among all paths from pathArray
  32390. var lg = []; // array of path lengths : nb of vertex per path
  32391. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32392. var p; // path iterator
  32393. var i; // point iterator
  32394. var j; // point iterator
  32395. // if single path in pathArray
  32396. if (pathArray.length < 2) {
  32397. var ar1 = [];
  32398. var ar2 = [];
  32399. for (i = 0; i < pathArray[0].length - offset; i++) {
  32400. ar1.push(pathArray[0][i]);
  32401. ar2.push(pathArray[0][i + offset]);
  32402. }
  32403. pathArray = [ar1, ar2];
  32404. }
  32405. // positions and horizontal distances (u)
  32406. var idc = 0;
  32407. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32408. var path;
  32409. var l;
  32410. minlg = pathArray[0].length;
  32411. var vectlg;
  32412. var dist;
  32413. for (p = 0; p < pathArray.length; p++) {
  32414. uTotalDistance[p] = 0;
  32415. us[p] = [0];
  32416. path = pathArray[p];
  32417. l = path.length;
  32418. minlg = (minlg < l) ? minlg : l;
  32419. j = 0;
  32420. while (j < l) {
  32421. positions.push(path[j].x, path[j].y, path[j].z);
  32422. if (j > 0) {
  32423. vectlg = path[j].subtract(path[j - 1]).length();
  32424. dist = vectlg + uTotalDistance[p];
  32425. us[p].push(dist);
  32426. uTotalDistance[p] = dist;
  32427. }
  32428. j++;
  32429. }
  32430. if (closePath) {
  32431. j--;
  32432. positions.push(path[0].x, path[0].y, path[0].z);
  32433. vectlg = path[j].subtract(path[0]).length();
  32434. dist = vectlg + uTotalDistance[p];
  32435. us[p].push(dist);
  32436. uTotalDistance[p] = dist;
  32437. }
  32438. lg[p] = l + closePathCorr;
  32439. idx[p] = idc;
  32440. idc += (l + closePathCorr);
  32441. }
  32442. // vertical distances (v)
  32443. var path1;
  32444. var path2;
  32445. var vertex1 = null;
  32446. var vertex2 = null;
  32447. for (i = 0; i < minlg + closePathCorr; i++) {
  32448. vTotalDistance[i] = 0;
  32449. vs[i] = [0];
  32450. for (p = 0; p < pathArray.length - 1; p++) {
  32451. path1 = pathArray[p];
  32452. path2 = pathArray[p + 1];
  32453. if (i === minlg) {
  32454. vertex1 = path1[0];
  32455. vertex2 = path2[0];
  32456. }
  32457. else {
  32458. vertex1 = path1[i];
  32459. vertex2 = path2[i];
  32460. }
  32461. vectlg = vertex2.subtract(vertex1).length();
  32462. dist = vectlg + vTotalDistance[i];
  32463. vs[i].push(dist);
  32464. vTotalDistance[i] = dist;
  32465. }
  32466. if (closeArray && vertex2 && vertex1) {
  32467. path1 = pathArray[p];
  32468. path2 = pathArray[0];
  32469. if (i === minlg) {
  32470. vertex2 = path2[0];
  32471. }
  32472. vectlg = vertex2.subtract(vertex1).length();
  32473. dist = vectlg + vTotalDistance[i];
  32474. vTotalDistance[i] = dist;
  32475. }
  32476. }
  32477. // uvs
  32478. var u;
  32479. var v;
  32480. if (customUV) {
  32481. for (p = 0; p < customUV.length; p++) {
  32482. uvs.push(customUV[p].x, customUV[p].y);
  32483. }
  32484. }
  32485. else {
  32486. for (p = 0; p < pathArray.length; p++) {
  32487. for (i = 0; i < minlg + closePathCorr; i++) {
  32488. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32489. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32490. if (invertUV) {
  32491. uvs.push(v, u);
  32492. }
  32493. else {
  32494. uvs.push(u, v);
  32495. }
  32496. }
  32497. }
  32498. }
  32499. // indices
  32500. p = 0; // path index
  32501. var pi = 0; // positions array index
  32502. var l1 = lg[p] - 1; // path1 length
  32503. var l2 = lg[p + 1] - 1; // path2 length
  32504. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32505. var shft = idx[1] - idx[0]; // shift
  32506. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32507. while (pi <= min && p < path1nb) {
  32508. // 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
  32509. indices.push(pi, pi + shft, pi + 1);
  32510. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32511. pi += 1;
  32512. if (pi === min) {
  32513. p++;
  32514. if (p === lg.length - 1) {
  32515. shft = idx[0] - idx[p];
  32516. l1 = lg[p] - 1;
  32517. l2 = lg[0] - 1;
  32518. }
  32519. else {
  32520. shft = idx[p + 1] - idx[p];
  32521. l1 = lg[p] - 1;
  32522. l2 = lg[p + 1] - 1;
  32523. }
  32524. pi = idx[p];
  32525. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32526. }
  32527. }
  32528. // normals
  32529. VertexData.ComputeNormals(positions, indices, normals);
  32530. if (closePath) {
  32531. var indexFirst = 0;
  32532. var indexLast = 0;
  32533. for (p = 0; p < pathArray.length; p++) {
  32534. indexFirst = idx[p] * 3;
  32535. if (p + 1 < pathArray.length) {
  32536. indexLast = (idx[p + 1] - 1) * 3;
  32537. }
  32538. else {
  32539. indexLast = normals.length - 3;
  32540. }
  32541. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32542. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32543. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32544. normals[indexLast] = normals[indexFirst];
  32545. normals[indexLast + 1] = normals[indexFirst + 1];
  32546. normals[indexLast + 2] = normals[indexFirst + 2];
  32547. }
  32548. }
  32549. // sides
  32550. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32551. // Colors
  32552. var colors = null;
  32553. if (customColors) {
  32554. colors = new Float32Array(customColors.length * 4);
  32555. for (var c = 0; c < customColors.length; c++) {
  32556. colors[c * 4] = customColors[c].r;
  32557. colors[c * 4 + 1] = customColors[c].g;
  32558. colors[c * 4 + 2] = customColors[c].b;
  32559. colors[c * 4 + 3] = customColors[c].a;
  32560. }
  32561. }
  32562. // Result
  32563. var vertexData = new VertexData();
  32564. var positions32 = new Float32Array(positions);
  32565. var normals32 = new Float32Array(normals);
  32566. var uvs32 = new Float32Array(uvs);
  32567. vertexData.indices = indices;
  32568. vertexData.positions = positions32;
  32569. vertexData.normals = normals32;
  32570. vertexData.uvs = uvs32;
  32571. if (colors) {
  32572. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32573. }
  32574. if (closePath) {
  32575. vertexData._idx = idx;
  32576. }
  32577. return vertexData;
  32578. };
  32579. /**
  32580. * Creates the VertexData of the Box.
  32581. */
  32582. VertexData.CreateBox = function (options) {
  32583. var normalsSource = [
  32584. new BABYLON.Vector3(0, 0, 1),
  32585. new BABYLON.Vector3(0, 0, -1),
  32586. new BABYLON.Vector3(1, 0, 0),
  32587. new BABYLON.Vector3(-1, 0, 0),
  32588. new BABYLON.Vector3(0, 1, 0),
  32589. new BABYLON.Vector3(0, -1, 0)
  32590. ];
  32591. var indices = [];
  32592. var positions = [];
  32593. var normals = [];
  32594. var uvs = [];
  32595. var width = options.width || options.size || 1;
  32596. var height = options.height || options.size || 1;
  32597. var depth = options.depth || options.size || 1;
  32598. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32599. var faceUV = options.faceUV || new Array(6);
  32600. var faceColors = options.faceColors;
  32601. var colors = [];
  32602. // default face colors and UV if undefined
  32603. for (var f = 0; f < 6; f++) {
  32604. if (faceUV[f] === undefined) {
  32605. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32606. }
  32607. if (faceColors && faceColors[f] === undefined) {
  32608. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32609. }
  32610. }
  32611. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32612. // Create each face in turn.
  32613. for (var index = 0; index < normalsSource.length; index++) {
  32614. var normal = normalsSource[index];
  32615. // Get two vectors perpendicular to the face normal and to each other.
  32616. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32617. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32618. // Six indices (two triangles) per face.
  32619. var verticesLength = positions.length / 3;
  32620. indices.push(verticesLength);
  32621. indices.push(verticesLength + 1);
  32622. indices.push(verticesLength + 2);
  32623. indices.push(verticesLength);
  32624. indices.push(verticesLength + 2);
  32625. indices.push(verticesLength + 3);
  32626. // Four vertices per face.
  32627. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32628. positions.push(vertex.x, vertex.y, vertex.z);
  32629. normals.push(normal.x, normal.y, normal.z);
  32630. uvs.push(faceUV[index].z, faceUV[index].w);
  32631. if (faceColors) {
  32632. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32633. }
  32634. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32635. positions.push(vertex.x, vertex.y, vertex.z);
  32636. normals.push(normal.x, normal.y, normal.z);
  32637. uvs.push(faceUV[index].x, faceUV[index].w);
  32638. if (faceColors) {
  32639. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32640. }
  32641. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32642. positions.push(vertex.x, vertex.y, vertex.z);
  32643. normals.push(normal.x, normal.y, normal.z);
  32644. uvs.push(faceUV[index].x, faceUV[index].y);
  32645. if (faceColors) {
  32646. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32647. }
  32648. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32649. positions.push(vertex.x, vertex.y, vertex.z);
  32650. normals.push(normal.x, normal.y, normal.z);
  32651. uvs.push(faceUV[index].z, faceUV[index].y);
  32652. if (faceColors) {
  32653. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32654. }
  32655. }
  32656. // sides
  32657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32658. // Result
  32659. var vertexData = new VertexData();
  32660. vertexData.indices = indices;
  32661. vertexData.positions = positions;
  32662. vertexData.normals = normals;
  32663. vertexData.uvs = uvs;
  32664. if (faceColors) {
  32665. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32666. vertexData.colors = totalColors;
  32667. }
  32668. return vertexData;
  32669. };
  32670. /**
  32671. * Creates the VertexData of the Sphere.
  32672. */
  32673. VertexData.CreateSphere = function (options) {
  32674. var segments = options.segments || 32;
  32675. var diameterX = options.diameterX || options.diameter || 1;
  32676. var diameterY = options.diameterY || options.diameter || 1;
  32677. var diameterZ = options.diameterZ || options.diameter || 1;
  32678. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32679. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32680. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32681. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32682. var totalZRotationSteps = 2 + segments;
  32683. var totalYRotationSteps = 2 * totalZRotationSteps;
  32684. var indices = [];
  32685. var positions = [];
  32686. var normals = [];
  32687. var uvs = [];
  32688. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32689. var normalizedZ = zRotationStep / totalZRotationSteps;
  32690. var angleZ = normalizedZ * Math.PI * slice;
  32691. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32692. var normalizedY = yRotationStep / totalYRotationSteps;
  32693. var angleY = normalizedY * Math.PI * 2 * arc;
  32694. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32695. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32696. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32697. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32698. var vertex = complete.multiply(radius);
  32699. var normal = complete.divide(radius).normalize();
  32700. positions.push(vertex.x, vertex.y, vertex.z);
  32701. normals.push(normal.x, normal.y, normal.z);
  32702. uvs.push(normalizedY, normalizedZ);
  32703. }
  32704. if (zRotationStep > 0) {
  32705. var verticesCount = positions.length / 3;
  32706. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32707. indices.push((firstIndex));
  32708. indices.push((firstIndex + 1));
  32709. indices.push(firstIndex + totalYRotationSteps + 1);
  32710. indices.push((firstIndex + totalYRotationSteps + 1));
  32711. indices.push((firstIndex + 1));
  32712. indices.push((firstIndex + totalYRotationSteps + 2));
  32713. }
  32714. }
  32715. }
  32716. // Sides
  32717. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32718. // Result
  32719. var vertexData = new VertexData();
  32720. vertexData.indices = indices;
  32721. vertexData.positions = positions;
  32722. vertexData.normals = normals;
  32723. vertexData.uvs = uvs;
  32724. return vertexData;
  32725. };
  32726. /**
  32727. * Creates the VertexData of the Cylinder or Cone.
  32728. */
  32729. VertexData.CreateCylinder = function (options) {
  32730. var height = options.height || 2;
  32731. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32732. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32733. var tessellation = options.tessellation || 24;
  32734. var subdivisions = options.subdivisions || 1;
  32735. var hasRings = options.hasRings ? true : false;
  32736. var enclose = options.enclose ? true : false;
  32737. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32738. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32739. var faceUV = options.faceUV || new Array(3);
  32740. var faceColors = options.faceColors;
  32741. // default face colors and UV if undefined
  32742. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32743. var ringNb = (hasRings) ? subdivisions : 1;
  32744. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32745. var f;
  32746. for (f = 0; f < surfaceNb; f++) {
  32747. if (faceColors && faceColors[f] === undefined) {
  32748. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32749. }
  32750. }
  32751. for (f = 0; f < surfaceNb; f++) {
  32752. if (faceUV && faceUV[f] === undefined) {
  32753. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32754. }
  32755. }
  32756. var indices = new Array();
  32757. var positions = new Array();
  32758. var normals = new Array();
  32759. var uvs = new Array();
  32760. var colors = new Array();
  32761. var angle_step = Math.PI * 2 * arc / tessellation;
  32762. var angle;
  32763. var h;
  32764. var radius;
  32765. var tan = (diameterBottom - diameterTop) / 2 / height;
  32766. var ringVertex = BABYLON.Vector3.Zero();
  32767. var ringNormal = BABYLON.Vector3.Zero();
  32768. var ringFirstVertex = BABYLON.Vector3.Zero();
  32769. var ringFirstNormal = BABYLON.Vector3.Zero();
  32770. var quadNormal = BABYLON.Vector3.Zero();
  32771. var Y = BABYLON.Axis.Y;
  32772. // positions, normals, uvs
  32773. var i;
  32774. var j;
  32775. var r;
  32776. var ringIdx = 1;
  32777. var s = 1; // surface index
  32778. var cs = 0;
  32779. var v = 0;
  32780. for (i = 0; i <= subdivisions; i++) {
  32781. h = i / subdivisions;
  32782. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32783. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32784. for (r = 0; r < ringIdx; r++) {
  32785. if (hasRings) {
  32786. s += r;
  32787. }
  32788. if (enclose) {
  32789. s += 2 * r;
  32790. }
  32791. for (j = 0; j <= tessellation; j++) {
  32792. angle = j * angle_step;
  32793. // position
  32794. ringVertex.x = Math.cos(-angle) * radius;
  32795. ringVertex.y = -height / 2 + h * height;
  32796. ringVertex.z = Math.sin(-angle) * radius;
  32797. // normal
  32798. if (diameterTop === 0 && i === subdivisions) {
  32799. // if no top cap, reuse former normals
  32800. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32801. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32802. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32803. }
  32804. else {
  32805. ringNormal.x = ringVertex.x;
  32806. ringNormal.z = ringVertex.z;
  32807. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32808. ringNormal.normalize();
  32809. }
  32810. // keep first ring vertex values for enclose
  32811. if (j === 0) {
  32812. ringFirstVertex.copyFrom(ringVertex);
  32813. ringFirstNormal.copyFrom(ringNormal);
  32814. }
  32815. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32816. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32817. if (hasRings) {
  32818. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32819. }
  32820. else {
  32821. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32822. }
  32823. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32824. if (faceColors) {
  32825. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32826. }
  32827. }
  32828. // if enclose, add four vertices and their dedicated normals
  32829. if (arc !== 1 && enclose) {
  32830. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32831. positions.push(0, ringVertex.y, 0);
  32832. positions.push(0, ringVertex.y, 0);
  32833. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32834. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32835. quadNormal.normalize();
  32836. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32837. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32838. quadNormal.normalize();
  32839. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32840. if (hasRings) {
  32841. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32842. }
  32843. else {
  32844. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32845. }
  32846. uvs.push(faceUV[s + 1].x, v);
  32847. uvs.push(faceUV[s + 1].z, v);
  32848. if (hasRings) {
  32849. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32850. }
  32851. else {
  32852. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32853. }
  32854. uvs.push(faceUV[s + 2].x, v);
  32855. uvs.push(faceUV[s + 2].z, v);
  32856. if (faceColors) {
  32857. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32858. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32859. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32860. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32861. }
  32862. }
  32863. if (cs !== s) {
  32864. cs = s;
  32865. }
  32866. }
  32867. }
  32868. // indices
  32869. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32870. var s;
  32871. i = 0;
  32872. for (s = 0; s < subdivisions; s++) {
  32873. var i0 = 0;
  32874. var i1 = 0;
  32875. var i2 = 0;
  32876. var i3 = 0;
  32877. for (j = 0; j < tessellation; j++) {
  32878. i0 = i * (e + 1) + j;
  32879. i1 = (i + 1) * (e + 1) + j;
  32880. i2 = i * (e + 1) + (j + 1);
  32881. i3 = (i + 1) * (e + 1) + (j + 1);
  32882. indices.push(i0, i1, i2);
  32883. indices.push(i3, i2, i1);
  32884. }
  32885. if (arc !== 1 && enclose) {
  32886. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32887. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32888. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32889. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32890. }
  32891. i = (hasRings) ? (i + 2) : (i + 1);
  32892. }
  32893. // Caps
  32894. var createCylinderCap = function (isTop) {
  32895. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32896. if (radius === 0) {
  32897. return;
  32898. }
  32899. // Cap positions, normals & uvs
  32900. var angle;
  32901. var circleVector;
  32902. var i;
  32903. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32904. var c = null;
  32905. if (faceColors) {
  32906. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32907. }
  32908. // cap center
  32909. var vbase = positions.length / 3;
  32910. var offset = isTop ? height / 2 : -height / 2;
  32911. var center = new BABYLON.Vector3(0, offset, 0);
  32912. positions.push(center.x, center.y, center.z);
  32913. normals.push(0, isTop ? 1 : -1, 0);
  32914. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32915. if (c) {
  32916. colors.push(c.r, c.g, c.b, c.a);
  32917. }
  32918. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32919. for (i = 0; i <= tessellation; i++) {
  32920. angle = Math.PI * 2 * i * arc / tessellation;
  32921. var cos = Math.cos(-angle);
  32922. var sin = Math.sin(-angle);
  32923. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32924. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32925. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32926. normals.push(0, isTop ? 1 : -1, 0);
  32927. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32928. if (c) {
  32929. colors.push(c.r, c.g, c.b, c.a);
  32930. }
  32931. }
  32932. // Cap indices
  32933. for (i = 0; i < tessellation; i++) {
  32934. if (!isTop) {
  32935. indices.push(vbase);
  32936. indices.push(vbase + (i + 1));
  32937. indices.push(vbase + (i + 2));
  32938. }
  32939. else {
  32940. indices.push(vbase);
  32941. indices.push(vbase + (i + 2));
  32942. indices.push(vbase + (i + 1));
  32943. }
  32944. }
  32945. };
  32946. // add caps to geometry
  32947. createCylinderCap(false);
  32948. createCylinderCap(true);
  32949. // Sides
  32950. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32951. var vertexData = new VertexData();
  32952. vertexData.indices = indices;
  32953. vertexData.positions = positions;
  32954. vertexData.normals = normals;
  32955. vertexData.uvs = uvs;
  32956. if (faceColors) {
  32957. vertexData.colors = colors;
  32958. }
  32959. return vertexData;
  32960. };
  32961. /**
  32962. * Creates the VertexData of the Torus.
  32963. */
  32964. VertexData.CreateTorus = function (options) {
  32965. var indices = [];
  32966. var positions = [];
  32967. var normals = [];
  32968. var uvs = [];
  32969. var diameter = options.diameter || 1;
  32970. var thickness = options.thickness || 0.5;
  32971. var tessellation = options.tessellation || 16;
  32972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32973. var stride = tessellation + 1;
  32974. for (var i = 0; i <= tessellation; i++) {
  32975. var u = i / tessellation;
  32976. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32977. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32978. for (var j = 0; j <= tessellation; j++) {
  32979. var v = 1 - j / tessellation;
  32980. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32981. var dx = Math.cos(innerAngle);
  32982. var dy = Math.sin(innerAngle);
  32983. // Create a vertex.
  32984. var normal = new BABYLON.Vector3(dx, dy, 0);
  32985. var position = normal.scale(thickness / 2);
  32986. var textureCoordinate = new BABYLON.Vector2(u, v);
  32987. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32988. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32989. positions.push(position.x, position.y, position.z);
  32990. normals.push(normal.x, normal.y, normal.z);
  32991. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32992. // And create indices for two triangles.
  32993. var nextI = (i + 1) % stride;
  32994. var nextJ = (j + 1) % stride;
  32995. indices.push(i * stride + j);
  32996. indices.push(i * stride + nextJ);
  32997. indices.push(nextI * stride + j);
  32998. indices.push(i * stride + nextJ);
  32999. indices.push(nextI * stride + nextJ);
  33000. indices.push(nextI * stride + j);
  33001. }
  33002. }
  33003. // Sides
  33004. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33005. // Result
  33006. var vertexData = new VertexData();
  33007. vertexData.indices = indices;
  33008. vertexData.positions = positions;
  33009. vertexData.normals = normals;
  33010. vertexData.uvs = uvs;
  33011. return vertexData;
  33012. };
  33013. /**
  33014. * Creates the VertexData of the LineSystem.
  33015. */
  33016. VertexData.CreateLineSystem = function (options) {
  33017. var indices = [];
  33018. var positions = [];
  33019. var lines = options.lines;
  33020. var colors = options.colors;
  33021. var vertexColors = [];
  33022. var idx = 0;
  33023. for (var l = 0; l < lines.length; l++) {
  33024. var points = lines[l];
  33025. for (var index = 0; index < points.length; index++) {
  33026. positions.push(points[index].x, points[index].y, points[index].z);
  33027. if (colors) {
  33028. var color = colors[l];
  33029. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33030. }
  33031. if (index > 0) {
  33032. indices.push(idx - 1);
  33033. indices.push(idx);
  33034. }
  33035. idx++;
  33036. }
  33037. }
  33038. var vertexData = new VertexData();
  33039. vertexData.indices = indices;
  33040. vertexData.positions = positions;
  33041. if (colors) {
  33042. vertexData.colors = vertexColors;
  33043. }
  33044. return vertexData;
  33045. };
  33046. /**
  33047. * Create the VertexData of the DashedLines.
  33048. */
  33049. VertexData.CreateDashedLines = function (options) {
  33050. var dashSize = options.dashSize || 3;
  33051. var gapSize = options.gapSize || 1;
  33052. var dashNb = options.dashNb || 200;
  33053. var points = options.points;
  33054. var positions = new Array();
  33055. var indices = new Array();
  33056. var curvect = BABYLON.Vector3.Zero();
  33057. var lg = 0;
  33058. var nb = 0;
  33059. var shft = 0;
  33060. var dashshft = 0;
  33061. var curshft = 0;
  33062. var idx = 0;
  33063. var i = 0;
  33064. for (i = 0; i < points.length - 1; i++) {
  33065. points[i + 1].subtractToRef(points[i], curvect);
  33066. lg += curvect.length();
  33067. }
  33068. shft = lg / dashNb;
  33069. dashshft = dashSize * shft / (dashSize + gapSize);
  33070. for (i = 0; i < points.length - 1; i++) {
  33071. points[i + 1].subtractToRef(points[i], curvect);
  33072. nb = Math.floor(curvect.length() / shft);
  33073. curvect.normalize();
  33074. for (var j = 0; j < nb; j++) {
  33075. curshft = shft * j;
  33076. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33077. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33078. indices.push(idx, idx + 1);
  33079. idx += 2;
  33080. }
  33081. }
  33082. // Result
  33083. var vertexData = new VertexData();
  33084. vertexData.positions = positions;
  33085. vertexData.indices = indices;
  33086. return vertexData;
  33087. };
  33088. /**
  33089. * Creates the VertexData of the Ground.
  33090. */
  33091. VertexData.CreateGround = function (options) {
  33092. var indices = [];
  33093. var positions = [];
  33094. var normals = [];
  33095. var uvs = [];
  33096. var row, col;
  33097. var width = options.width || 1;
  33098. var height = options.height || 1;
  33099. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33100. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33101. for (row = 0; row <= subdivisionsY; row++) {
  33102. for (col = 0; col <= subdivisionsX; col++) {
  33103. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33104. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33105. positions.push(position.x, position.y, position.z);
  33106. normals.push(normal.x, normal.y, normal.z);
  33107. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33108. }
  33109. }
  33110. for (row = 0; row < subdivisionsY; row++) {
  33111. for (col = 0; col < subdivisionsX; col++) {
  33112. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33113. indices.push(col + 1 + row * (subdivisionsX + 1));
  33114. indices.push(col + row * (subdivisionsX + 1));
  33115. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33116. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33117. indices.push(col + row * (subdivisionsX + 1));
  33118. }
  33119. }
  33120. // Result
  33121. var vertexData = new VertexData();
  33122. vertexData.indices = indices;
  33123. vertexData.positions = positions;
  33124. vertexData.normals = normals;
  33125. vertexData.uvs = uvs;
  33126. return vertexData;
  33127. };
  33128. /**
  33129. * Creates the VertexData of the TiledGround.
  33130. */
  33131. VertexData.CreateTiledGround = function (options) {
  33132. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33133. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33134. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33135. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33136. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33137. var precision = options.precision || { w: 1, h: 1 };
  33138. var indices = new Array();
  33139. var positions = new Array();
  33140. var normals = new Array();
  33141. var uvs = new Array();
  33142. var row, col, tileRow, tileCol;
  33143. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33144. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33145. precision.w = (precision.w < 1) ? 1 : precision.w;
  33146. precision.h = (precision.h < 1) ? 1 : precision.h;
  33147. var tileSize = {
  33148. 'w': (xmax - xmin) / subdivisions.w,
  33149. 'h': (zmax - zmin) / subdivisions.h
  33150. };
  33151. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33152. // Indices
  33153. var base = positions.length / 3;
  33154. var rowLength = precision.w + 1;
  33155. for (row = 0; row < precision.h; row++) {
  33156. for (col = 0; col < precision.w; col++) {
  33157. var square = [
  33158. base + col + row * rowLength,
  33159. base + (col + 1) + row * rowLength,
  33160. base + (col + 1) + (row + 1) * rowLength,
  33161. base + col + (row + 1) * rowLength
  33162. ];
  33163. indices.push(square[1]);
  33164. indices.push(square[2]);
  33165. indices.push(square[3]);
  33166. indices.push(square[0]);
  33167. indices.push(square[1]);
  33168. indices.push(square[3]);
  33169. }
  33170. }
  33171. // Position, normals and uvs
  33172. var position = BABYLON.Vector3.Zero();
  33173. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33174. for (row = 0; row <= precision.h; row++) {
  33175. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33176. for (col = 0; col <= precision.w; col++) {
  33177. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33178. position.y = 0;
  33179. positions.push(position.x, position.y, position.z);
  33180. normals.push(normal.x, normal.y, normal.z);
  33181. uvs.push(col / precision.w, row / precision.h);
  33182. }
  33183. }
  33184. }
  33185. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33186. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33187. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33188. }
  33189. }
  33190. // Result
  33191. var vertexData = new VertexData();
  33192. vertexData.indices = indices;
  33193. vertexData.positions = positions;
  33194. vertexData.normals = normals;
  33195. vertexData.uvs = uvs;
  33196. return vertexData;
  33197. };
  33198. /**
  33199. * Creates the VertexData of the Ground designed from a heightmap.
  33200. */
  33201. VertexData.CreateGroundFromHeightMap = function (options) {
  33202. var indices = [];
  33203. var positions = [];
  33204. var normals = [];
  33205. var uvs = [];
  33206. var row, col;
  33207. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33208. // Vertices
  33209. for (row = 0; row <= options.subdivisions; row++) {
  33210. for (col = 0; col <= options.subdivisions; col++) {
  33211. 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));
  33212. // Compute height
  33213. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33214. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33215. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33216. var r = options.buffer[pos] / 255.0;
  33217. var g = options.buffer[pos + 1] / 255.0;
  33218. var b = options.buffer[pos + 2] / 255.0;
  33219. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33220. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33221. // Add vertex
  33222. positions.push(position.x, position.y, position.z);
  33223. normals.push(0, 0, 0);
  33224. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33225. }
  33226. }
  33227. // Indices
  33228. for (row = 0; row < options.subdivisions; row++) {
  33229. for (col = 0; col < options.subdivisions; col++) {
  33230. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33231. indices.push(col + 1 + row * (options.subdivisions + 1));
  33232. indices.push(col + row * (options.subdivisions + 1));
  33233. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33234. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33235. indices.push(col + row * (options.subdivisions + 1));
  33236. }
  33237. }
  33238. // Normals
  33239. VertexData.ComputeNormals(positions, indices, normals);
  33240. // Result
  33241. var vertexData = new VertexData();
  33242. vertexData.indices = indices;
  33243. vertexData.positions = positions;
  33244. vertexData.normals = normals;
  33245. vertexData.uvs = uvs;
  33246. return vertexData;
  33247. };
  33248. /**
  33249. * Creates the VertexData of the Plane.
  33250. */
  33251. VertexData.CreatePlane = function (options) {
  33252. var indices = [];
  33253. var positions = [];
  33254. var normals = [];
  33255. var uvs = [];
  33256. var width = options.width || options.size || 1;
  33257. var height = options.height || options.size || 1;
  33258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33259. // Vertices
  33260. var halfWidth = width / 2.0;
  33261. var halfHeight = height / 2.0;
  33262. positions.push(-halfWidth, -halfHeight, 0);
  33263. normals.push(0, 0, -1.0);
  33264. uvs.push(0.0, 0.0);
  33265. positions.push(halfWidth, -halfHeight, 0);
  33266. normals.push(0, 0, -1.0);
  33267. uvs.push(1.0, 0.0);
  33268. positions.push(halfWidth, halfHeight, 0);
  33269. normals.push(0, 0, -1.0);
  33270. uvs.push(1.0, 1.0);
  33271. positions.push(-halfWidth, halfHeight, 0);
  33272. normals.push(0, 0, -1.0);
  33273. uvs.push(0.0, 1.0);
  33274. // Indices
  33275. indices.push(0);
  33276. indices.push(1);
  33277. indices.push(2);
  33278. indices.push(0);
  33279. indices.push(2);
  33280. indices.push(3);
  33281. // Sides
  33282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33283. // Result
  33284. var vertexData = new VertexData();
  33285. vertexData.indices = indices;
  33286. vertexData.positions = positions;
  33287. vertexData.normals = normals;
  33288. vertexData.uvs = uvs;
  33289. return vertexData;
  33290. };
  33291. /**
  33292. * Creates the VertexData of the Disc or regular Polygon.
  33293. */
  33294. VertexData.CreateDisc = function (options) {
  33295. var positions = new Array();
  33296. var indices = new Array();
  33297. var normals = new Array();
  33298. var uvs = new Array();
  33299. var radius = options.radius || 0.5;
  33300. var tessellation = options.tessellation || 64;
  33301. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33302. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33303. // positions and uvs
  33304. positions.push(0, 0, 0); // disc center first
  33305. uvs.push(0.5, 0.5);
  33306. var theta = Math.PI * 2 * arc;
  33307. var step = theta / tessellation;
  33308. for (var a = 0; a < theta; a += step) {
  33309. var x = Math.cos(a);
  33310. var y = Math.sin(a);
  33311. var u = (x + 1) / 2;
  33312. var v = (1 - y) / 2;
  33313. positions.push(radius * x, radius * y, 0);
  33314. uvs.push(u, v);
  33315. }
  33316. if (arc === 1) {
  33317. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33318. uvs.push(uvs[2], uvs[3]);
  33319. }
  33320. //indices
  33321. var vertexNb = positions.length / 3;
  33322. for (var i = 1; i < vertexNb - 1; i++) {
  33323. indices.push(i + 1, 0, i);
  33324. }
  33325. // result
  33326. VertexData.ComputeNormals(positions, indices, normals);
  33327. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33328. var vertexData = new VertexData();
  33329. vertexData.indices = indices;
  33330. vertexData.positions = positions;
  33331. vertexData.normals = normals;
  33332. vertexData.uvs = uvs;
  33333. return vertexData;
  33334. };
  33335. /**
  33336. * Re-creates the VertexData of the Polygon for sideOrientation.
  33337. */
  33338. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33339. var faceUV = fUV || new Array(3);
  33340. var faceColors = fColors;
  33341. var colors = [];
  33342. // default face colors and UV if undefined
  33343. for (var f = 0; f < 3; f++) {
  33344. if (faceUV[f] === undefined) {
  33345. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33346. }
  33347. if (faceColors && faceColors[f] === undefined) {
  33348. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33349. }
  33350. }
  33351. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33352. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33353. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33354. var indices = polygon.getIndices();
  33355. // set face colours and textures
  33356. var idx = 0;
  33357. var face = 0;
  33358. for (var index = 0; index < normals.length; index += 3) {
  33359. //Edge Face no. 1
  33360. if (Math.abs(normals[index + 1]) < 0.001) {
  33361. face = 1;
  33362. }
  33363. //Top Face no. 0
  33364. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33365. face = 0;
  33366. }
  33367. //Bottom Face no. 2
  33368. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33369. face = 2;
  33370. }
  33371. idx = index / 3;
  33372. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33373. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33374. if (faceColors) {
  33375. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33376. }
  33377. }
  33378. // sides
  33379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33380. // Result
  33381. var vertexData = new VertexData();
  33382. vertexData.indices = indices;
  33383. vertexData.positions = positions;
  33384. vertexData.normals = normals;
  33385. vertexData.uvs = uvs;
  33386. if (faceColors) {
  33387. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33388. vertexData.colors = totalColors;
  33389. }
  33390. return vertexData;
  33391. };
  33392. /**
  33393. * Creates the VertexData of the IcoSphere.
  33394. */
  33395. VertexData.CreateIcoSphere = function (options) {
  33396. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33397. var radius = options.radius || 1;
  33398. var flat = (options.flat === undefined) ? true : options.flat;
  33399. var subdivisions = options.subdivisions || 4;
  33400. var radiusX = options.radiusX || radius;
  33401. var radiusY = options.radiusY || radius;
  33402. var radiusZ = options.radiusZ || radius;
  33403. var t = (1 + Math.sqrt(5)) / 2;
  33404. // 12 vertex x,y,z
  33405. var ico_vertices = [
  33406. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33407. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33408. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33409. ];
  33410. // index of 3 vertex makes a face of icopshere
  33411. var ico_indices = [
  33412. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33413. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33414. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33415. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33416. ];
  33417. // vertex for uv have aliased position, not for UV
  33418. var vertices_unalias_id = [
  33419. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33420. // vertex alias
  33421. 0,
  33422. 2,
  33423. 3,
  33424. 3,
  33425. 3,
  33426. 4,
  33427. 7,
  33428. 8,
  33429. 9,
  33430. 9,
  33431. 10,
  33432. 11 // 23: B + 12
  33433. ];
  33434. // uv as integer step (not pixels !)
  33435. var ico_vertexuv = [
  33436. 5, 1, 3, 1, 6, 4, 0, 0,
  33437. 5, 3, 4, 2, 2, 2, 4, 0,
  33438. 2, 0, 1, 1, 6, 0, 6, 2,
  33439. // vertex alias (for same vertex on different faces)
  33440. 0, 4,
  33441. 3, 3,
  33442. 4, 4,
  33443. 3, 1,
  33444. 4, 2,
  33445. 4, 4,
  33446. 0, 2,
  33447. 1, 1,
  33448. 2, 2,
  33449. 3, 3,
  33450. 1, 3,
  33451. 2, 4 // 23: B + 12
  33452. ];
  33453. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33454. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33455. // First island of uv mapping
  33456. // v = 4h 3+ 2
  33457. // v = 3h 9+ 4
  33458. // v = 2h 9+ 5 B
  33459. // v = 1h 9 1 0
  33460. // v = 0h 3 8 7 A
  33461. // u = 0 1 2 3 4 5 6 *a
  33462. // Second island of uv mapping
  33463. // v = 4h 0+ B+ 4+
  33464. // v = 3h A+ 2+
  33465. // v = 2h 7+ 6 3+
  33466. // v = 1h 8+ 3+
  33467. // v = 0h
  33468. // u = 0 1 2 3 4 5 6 *a
  33469. // Face layout on texture UV mapping
  33470. // ============
  33471. // \ 4 /\ 16 / ======
  33472. // \ / \ / /\ 11 /
  33473. // \/ 7 \/ / \ /
  33474. // ======= / 10 \/
  33475. // /\ 17 /\ =======
  33476. // / \ / \ \ 15 /\
  33477. // / 8 \/ 12 \ \ / \
  33478. // ============ \/ 6 \
  33479. // \ 18 /\ ============
  33480. // \ / \ \ 5 /\ 0 /
  33481. // \/ 13 \ \ / \ /
  33482. // ======= \/ 1 \/
  33483. // =============
  33484. // /\ 19 /\ 2 /\
  33485. // / \ / \ / \
  33486. // / 14 \/ 9 \/ 3 \
  33487. // ===================
  33488. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33489. var ustep = 138 / 1024;
  33490. var vstep = 239 / 1024;
  33491. var uoffset = 60 / 1024;
  33492. var voffset = 26 / 1024;
  33493. // Second island should have margin, not to touch the first island
  33494. // avoid any borderline artefact in pixel rounding
  33495. var island_u_offset = -40 / 1024;
  33496. var island_v_offset = +20 / 1024;
  33497. // face is either island 0 or 1 :
  33498. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33499. var island = [
  33500. 0, 0, 0, 0, 1,
  33501. 0, 0, 1, 1, 0,
  33502. 0, 0, 1, 1, 0,
  33503. 0, 1, 1, 1, 0 // 15 - 19
  33504. ];
  33505. var indices = new Array();
  33506. var positions = new Array();
  33507. var normals = new Array();
  33508. var uvs = new Array();
  33509. var current_indice = 0;
  33510. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33511. var face_vertex_pos = new Array(3);
  33512. var face_vertex_uv = new Array(3);
  33513. var v012;
  33514. for (v012 = 0; v012 < 3; v012++) {
  33515. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33516. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33517. }
  33518. // create all with normals
  33519. for (var face = 0; face < 20; face++) {
  33520. // 3 vertex per face
  33521. for (v012 = 0; v012 < 3; v012++) {
  33522. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33523. var v_id = ico_indices[3 * face + v012];
  33524. // vertex have 3D position (x,y,z)
  33525. 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]);
  33526. // Normalize to get normal, then scale to radius
  33527. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33528. // uv Coordinates from vertex ID
  33529. 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);
  33530. }
  33531. // Subdivide the face (interpolate pos, norm, uv)
  33532. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33533. // - norm is linear interpolation of vertex corner normal
  33534. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33535. // - uv is linear interpolation
  33536. //
  33537. // Topology is as below for sub-divide by 2
  33538. // vertex shown as v0,v1,v2
  33539. // interp index is i1 to progress in range [v0,v1[
  33540. // interp index is i2 to progress in range [v0,v2[
  33541. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33542. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33543. //
  33544. //
  33545. // i2 v2
  33546. // ^ ^
  33547. // / / \
  33548. // / / \
  33549. // / / \
  33550. // / / (0,1) \
  33551. // / #---------\
  33552. // / / \ (0,0)'/ \
  33553. // / / \ / \
  33554. // / / \ / \
  33555. // / / (0,0) \ / (1,0) \
  33556. // / #---------#---------\
  33557. // v0 v1
  33558. //
  33559. // --------------------> i1
  33560. //
  33561. // interp of (i1,i2):
  33562. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33563. // along i1 : lerp(x0,x1, i1/(S-i2))
  33564. //
  33565. // centroid of triangle is needed to get help normal computation
  33566. // (c1,c2) are used for centroid location
  33567. var interp_vertex = function (i1, i2, c1, c2) {
  33568. // vertex is interpolated from
  33569. // - face_vertex_pos[0..2]
  33570. // - face_vertex_uv[0..2]
  33571. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33572. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33573. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33574. pos_interp.normalize();
  33575. var vertex_normal;
  33576. if (flat) {
  33577. // in flat mode, recalculate normal as face centroid normal
  33578. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33579. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33580. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33581. }
  33582. else {
  33583. // in smooth mode, recalculate normal from each single vertex position
  33584. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33585. }
  33586. // Vertex normal need correction due to X,Y,Z radius scaling
  33587. vertex_normal.x /= radiusX;
  33588. vertex_normal.y /= radiusY;
  33589. vertex_normal.z /= radiusZ;
  33590. vertex_normal.normalize();
  33591. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33592. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33593. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33594. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33595. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33596. uvs.push(uv_interp.x, uv_interp.y);
  33597. // push each vertex has member of a face
  33598. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33599. indices.push(current_indice);
  33600. current_indice++;
  33601. };
  33602. for (var i2 = 0; i2 < subdivisions; i2++) {
  33603. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33604. // face : (i1,i2) for /\ :
  33605. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33606. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33607. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33608. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33609. if (i1 + i2 + 1 < subdivisions) {
  33610. // face : (i1,i2)' for \/ :
  33611. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33612. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33613. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33614. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33615. }
  33616. }
  33617. }
  33618. }
  33619. // Sides
  33620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33621. // Result
  33622. var vertexData = new VertexData();
  33623. vertexData.indices = indices;
  33624. vertexData.positions = positions;
  33625. vertexData.normals = normals;
  33626. vertexData.uvs = uvs;
  33627. return vertexData;
  33628. };
  33629. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33630. /**
  33631. * Creates the VertexData of the Polyhedron.
  33632. */
  33633. VertexData.CreatePolyhedron = function (options) {
  33634. // provided polyhedron types :
  33635. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33636. // 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)
  33637. var polyhedra = [];
  33638. 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]] };
  33639. 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]] };
  33640. polyhedra[2] = {
  33641. 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]],
  33642. 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]]
  33643. };
  33644. polyhedra[3] = {
  33645. 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]],
  33646. 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]]
  33647. };
  33648. polyhedra[4] = {
  33649. 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]],
  33650. 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]]
  33651. };
  33652. 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]] };
  33653. 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]] };
  33654. 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]] };
  33655. 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]] };
  33656. 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]] };
  33657. 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]] };
  33658. 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]] };
  33659. 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]] };
  33660. 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]] };
  33661. polyhedra[14] = {
  33662. 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]],
  33663. 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]]
  33664. };
  33665. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33666. var size = options.size;
  33667. var sizeX = options.sizeX || size || 1;
  33668. var sizeY = options.sizeY || size || 1;
  33669. var sizeZ = options.sizeZ || size || 1;
  33670. var data = options.custom || polyhedra[type];
  33671. var nbfaces = data.face.length;
  33672. var faceUV = options.faceUV || new Array(nbfaces);
  33673. var faceColors = options.faceColors;
  33674. var flat = (options.flat === undefined) ? true : options.flat;
  33675. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33676. var positions = new Array();
  33677. var indices = new Array();
  33678. var normals = new Array();
  33679. var uvs = new Array();
  33680. var colors = new Array();
  33681. var index = 0;
  33682. var faceIdx = 0; // face cursor in the array "indexes"
  33683. var indexes = new Array();
  33684. var i = 0;
  33685. var f = 0;
  33686. var u, v, ang, x, y, tmp;
  33687. // default face colors and UV if undefined
  33688. if (flat) {
  33689. for (f = 0; f < nbfaces; f++) {
  33690. if (faceColors && faceColors[f] === undefined) {
  33691. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33692. }
  33693. if (faceUV && faceUV[f] === undefined) {
  33694. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33695. }
  33696. }
  33697. }
  33698. if (!flat) {
  33699. for (i = 0; i < data.vertex.length; i++) {
  33700. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33701. uvs.push(0, 0);
  33702. }
  33703. for (f = 0; f < nbfaces; f++) {
  33704. for (i = 0; i < data.face[f].length - 2; i++) {
  33705. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33706. }
  33707. }
  33708. }
  33709. else {
  33710. for (f = 0; f < nbfaces; f++) {
  33711. var fl = data.face[f].length; // number of vertices of the current face
  33712. ang = 2 * Math.PI / fl;
  33713. x = 0.5 * Math.tan(ang / 2);
  33714. y = 0.5;
  33715. // positions, uvs, colors
  33716. for (i = 0; i < fl; i++) {
  33717. // positions
  33718. 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);
  33719. indexes.push(index);
  33720. index++;
  33721. // uvs
  33722. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33723. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33724. uvs.push(u, v);
  33725. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33726. y = x * Math.sin(ang) + y * Math.cos(ang);
  33727. x = tmp;
  33728. // colors
  33729. if (faceColors) {
  33730. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33731. }
  33732. }
  33733. // indices from indexes
  33734. for (i = 0; i < fl - 2; i++) {
  33735. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33736. }
  33737. faceIdx += fl;
  33738. }
  33739. }
  33740. VertexData.ComputeNormals(positions, indices, normals);
  33741. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33742. var vertexData = new VertexData();
  33743. vertexData.positions = positions;
  33744. vertexData.indices = indices;
  33745. vertexData.normals = normals;
  33746. vertexData.uvs = uvs;
  33747. if (faceColors && flat) {
  33748. vertexData.colors = colors;
  33749. }
  33750. return vertexData;
  33751. };
  33752. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33753. /**
  33754. * Creates the VertexData of the Torus Knot.
  33755. */
  33756. VertexData.CreateTorusKnot = function (options) {
  33757. var indices = new Array();
  33758. var positions = new Array();
  33759. var normals = new Array();
  33760. var uvs = new Array();
  33761. var radius = options.radius || 2;
  33762. var tube = options.tube || 0.5;
  33763. var radialSegments = options.radialSegments || 32;
  33764. var tubularSegments = options.tubularSegments || 32;
  33765. var p = options.p || 2;
  33766. var q = options.q || 3;
  33767. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33768. // Helper
  33769. var getPos = function (angle) {
  33770. var cu = Math.cos(angle);
  33771. var su = Math.sin(angle);
  33772. var quOverP = q / p * angle;
  33773. var cs = Math.cos(quOverP);
  33774. var tx = radius * (2 + cs) * 0.5 * cu;
  33775. var ty = radius * (2 + cs) * su * 0.5;
  33776. var tz = radius * Math.sin(quOverP) * 0.5;
  33777. return new BABYLON.Vector3(tx, ty, tz);
  33778. };
  33779. // Vertices
  33780. var i;
  33781. var j;
  33782. for (i = 0; i <= radialSegments; i++) {
  33783. var modI = i % radialSegments;
  33784. var u = modI / radialSegments * 2 * p * Math.PI;
  33785. var p1 = getPos(u);
  33786. var p2 = getPos(u + 0.01);
  33787. var tang = p2.subtract(p1);
  33788. var n = p2.add(p1);
  33789. var bitan = BABYLON.Vector3.Cross(tang, n);
  33790. n = BABYLON.Vector3.Cross(bitan, tang);
  33791. bitan.normalize();
  33792. n.normalize();
  33793. for (j = 0; j < tubularSegments; j++) {
  33794. var modJ = j % tubularSegments;
  33795. var v = modJ / tubularSegments * 2 * Math.PI;
  33796. var cx = -tube * Math.cos(v);
  33797. var cy = tube * Math.sin(v);
  33798. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33799. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33800. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33801. uvs.push(i / radialSegments);
  33802. uvs.push(j / tubularSegments);
  33803. }
  33804. }
  33805. for (i = 0; i < radialSegments; i++) {
  33806. for (j = 0; j < tubularSegments; j++) {
  33807. var jNext = (j + 1) % tubularSegments;
  33808. var a = i * tubularSegments + j;
  33809. var b = (i + 1) * tubularSegments + j;
  33810. var c = (i + 1) * tubularSegments + jNext;
  33811. var d = i * tubularSegments + jNext;
  33812. indices.push(d);
  33813. indices.push(b);
  33814. indices.push(a);
  33815. indices.push(d);
  33816. indices.push(c);
  33817. indices.push(b);
  33818. }
  33819. }
  33820. // Normals
  33821. VertexData.ComputeNormals(positions, indices, normals);
  33822. // Sides
  33823. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33824. // Result
  33825. var vertexData = new VertexData();
  33826. vertexData.indices = indices;
  33827. vertexData.positions = positions;
  33828. vertexData.normals = normals;
  33829. vertexData.uvs = uvs;
  33830. return vertexData;
  33831. };
  33832. // Tools
  33833. /**
  33834. * @param {any} - positions (number[] or Float32Array)
  33835. * @param {any} - indices (number[] or Uint16Array)
  33836. * @param {any} - normals (number[] or Float32Array)
  33837. * options (optional) :
  33838. * facetPositions : optional array of facet positions (vector3)
  33839. * facetNormals : optional array of facet normals (vector3)
  33840. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33841. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33842. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33843. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33844. * bInfo : optional bounding info, required for facetPartitioning computation
  33845. * useRightHandedSystem: optional boolean to for right handed system computation
  33846. * depthSort : optional boolean to enable the facet depth sort computation
  33847. * distanceTo : optional Vector3 to compute the facet depth from this location
  33848. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33849. */
  33850. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33851. // temporary scalar variables
  33852. var index = 0; // facet index
  33853. var p1p2x = 0.0; // p1p2 vector x coordinate
  33854. var p1p2y = 0.0; // p1p2 vector y coordinate
  33855. var p1p2z = 0.0; // p1p2 vector z coordinate
  33856. var p3p2x = 0.0; // p3p2 vector x coordinate
  33857. var p3p2y = 0.0; // p3p2 vector y coordinate
  33858. var p3p2z = 0.0; // p3p2 vector z coordinate
  33859. var faceNormalx = 0.0; // facet normal x coordinate
  33860. var faceNormaly = 0.0; // facet normal y coordinate
  33861. var faceNormalz = 0.0; // facet normal z coordinate
  33862. var length = 0.0; // facet normal length before normalization
  33863. var v1x = 0; // vector1 x index in the positions array
  33864. var v1y = 0; // vector1 y index in the positions array
  33865. var v1z = 0; // vector1 z index in the positions array
  33866. var v2x = 0; // vector2 x index in the positions array
  33867. var v2y = 0; // vector2 y index in the positions array
  33868. var v2z = 0; // vector2 z index in the positions array
  33869. var v3x = 0; // vector3 x index in the positions array
  33870. var v3y = 0; // vector3 y index in the positions array
  33871. var v3z = 0; // vector3 z index in the positions array
  33872. var computeFacetNormals = false;
  33873. var computeFacetPositions = false;
  33874. var computeFacetPartitioning = false;
  33875. var computeDepthSort = false;
  33876. var faceNormalSign = 1;
  33877. var ratio = 0;
  33878. var distanceTo = null;
  33879. if (options) {
  33880. computeFacetNormals = (options.facetNormals) ? true : false;
  33881. computeFacetPositions = (options.facetPositions) ? true : false;
  33882. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33883. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33884. ratio = options.ratio || 0;
  33885. computeDepthSort = (options.depthSort) ? true : false;
  33886. distanceTo = (options.distanceTo);
  33887. if (computeDepthSort) {
  33888. if (distanceTo === undefined) {
  33889. distanceTo = BABYLON.Vector3.Zero();
  33890. }
  33891. var depthSortedFacets = options.depthSortedFacets;
  33892. }
  33893. }
  33894. // facetPartitioning reinit if needed
  33895. var xSubRatio = 0;
  33896. var ySubRatio = 0;
  33897. var zSubRatio = 0;
  33898. var subSq = 0;
  33899. if (computeFacetPartitioning && options && options.bbSize) {
  33900. var ox = 0; // X partitioning index for facet position
  33901. var oy = 0; // Y partinioning index for facet position
  33902. var oz = 0; // Z partinioning index for facet position
  33903. var b1x = 0; // X partitioning index for facet v1 vertex
  33904. var b1y = 0; // Y partitioning index for facet v1 vertex
  33905. var b1z = 0; // z partitioning index for facet v1 vertex
  33906. var b2x = 0; // X partitioning index for facet v2 vertex
  33907. var b2y = 0; // Y partitioning index for facet v2 vertex
  33908. var b2z = 0; // Z partitioning index for facet v2 vertex
  33909. var b3x = 0; // X partitioning index for facet v3 vertex
  33910. var b3y = 0; // Y partitioning index for facet v3 vertex
  33911. var b3z = 0; // Z partitioning index for facet v3 vertex
  33912. var block_idx_o = 0; // facet barycenter block index
  33913. var block_idx_v1 = 0; // v1 vertex block index
  33914. var block_idx_v2 = 0; // v2 vertex block index
  33915. var block_idx_v3 = 0; // v3 vertex block index
  33916. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33917. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33918. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33919. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33920. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33921. subSq = options.subDiv.max * options.subDiv.max;
  33922. options.facetPartitioning.length = 0;
  33923. }
  33924. // reset the normals
  33925. for (index = 0; index < positions.length; index++) {
  33926. normals[index] = 0.0;
  33927. }
  33928. // Loop : 1 indice triplet = 1 facet
  33929. var nbFaces = (indices.length / 3) | 0;
  33930. for (index = 0; index < nbFaces; index++) {
  33931. // get the indexes of the coordinates of each vertex of the facet
  33932. v1x = indices[index * 3] * 3;
  33933. v1y = v1x + 1;
  33934. v1z = v1x + 2;
  33935. v2x = indices[index * 3 + 1] * 3;
  33936. v2y = v2x + 1;
  33937. v2z = v2x + 2;
  33938. v3x = indices[index * 3 + 2] * 3;
  33939. v3y = v3x + 1;
  33940. v3z = v3x + 2;
  33941. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33942. p1p2y = positions[v1y] - positions[v2y];
  33943. p1p2z = positions[v1z] - positions[v2z];
  33944. p3p2x = positions[v3x] - positions[v2x];
  33945. p3p2y = positions[v3y] - positions[v2y];
  33946. p3p2z = positions[v3z] - positions[v2z];
  33947. // compute the face normal with the cross product
  33948. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33949. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33950. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33951. // normalize this normal and store it in the array facetData
  33952. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33953. length = (length === 0) ? 1.0 : length;
  33954. faceNormalx /= length;
  33955. faceNormaly /= length;
  33956. faceNormalz /= length;
  33957. if (computeFacetNormals && options) {
  33958. options.facetNormals[index].x = faceNormalx;
  33959. options.facetNormals[index].y = faceNormaly;
  33960. options.facetNormals[index].z = faceNormalz;
  33961. }
  33962. if (computeFacetPositions && options) {
  33963. // compute and the facet barycenter coordinates in the array facetPositions
  33964. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33965. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33966. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33967. }
  33968. if (computeFacetPartitioning && options) {
  33969. // store the facet indexes in arrays in the main facetPartitioning array :
  33970. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33971. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33972. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33973. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33974. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33975. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33976. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33977. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33978. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33979. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33980. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33981. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33982. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33983. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33984. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33985. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33986. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33987. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33988. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33989. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33990. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33991. // push each facet index in each block containing the vertex
  33992. options.facetPartitioning[block_idx_v1].push(index);
  33993. if (block_idx_v2 != block_idx_v1) {
  33994. options.facetPartitioning[block_idx_v2].push(index);
  33995. }
  33996. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33997. options.facetPartitioning[block_idx_v3].push(index);
  33998. }
  33999. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34000. options.facetPartitioning[block_idx_o].push(index);
  34001. }
  34002. }
  34003. if (computeDepthSort && options && options.facetPositions) {
  34004. var dsf = depthSortedFacets[index];
  34005. dsf.ind = index * 3;
  34006. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34007. }
  34008. // compute the normals anyway
  34009. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34010. normals[v1y] += faceNormaly;
  34011. normals[v1z] += faceNormalz;
  34012. normals[v2x] += faceNormalx;
  34013. normals[v2y] += faceNormaly;
  34014. normals[v2z] += faceNormalz;
  34015. normals[v3x] += faceNormalx;
  34016. normals[v3y] += faceNormaly;
  34017. normals[v3z] += faceNormalz;
  34018. }
  34019. // last normalization of each normal
  34020. for (index = 0; index < normals.length / 3; index++) {
  34021. faceNormalx = normals[index * 3];
  34022. faceNormaly = normals[index * 3 + 1];
  34023. faceNormalz = normals[index * 3 + 2];
  34024. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34025. length = (length === 0) ? 1.0 : length;
  34026. faceNormalx /= length;
  34027. faceNormaly /= length;
  34028. faceNormalz /= length;
  34029. normals[index * 3] = faceNormalx;
  34030. normals[index * 3 + 1] = faceNormaly;
  34031. normals[index * 3 + 2] = faceNormalz;
  34032. }
  34033. };
  34034. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34035. var li = indices.length;
  34036. var ln = normals.length;
  34037. var i;
  34038. var n;
  34039. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34040. switch (sideOrientation) {
  34041. case BABYLON.Mesh.FRONTSIDE:
  34042. // nothing changed
  34043. break;
  34044. case BABYLON.Mesh.BACKSIDE:
  34045. var tmp;
  34046. // indices
  34047. for (i = 0; i < li; i += 3) {
  34048. tmp = indices[i];
  34049. indices[i] = indices[i + 2];
  34050. indices[i + 2] = tmp;
  34051. }
  34052. // normals
  34053. for (n = 0; n < ln; n++) {
  34054. normals[n] = -normals[n];
  34055. }
  34056. break;
  34057. case BABYLON.Mesh.DOUBLESIDE:
  34058. // positions
  34059. var lp = positions.length;
  34060. var l = lp / 3;
  34061. for (var p = 0; p < lp; p++) {
  34062. positions[lp + p] = positions[p];
  34063. }
  34064. // indices
  34065. for (i = 0; i < li; i += 3) {
  34066. indices[i + li] = indices[i + 2] + l;
  34067. indices[i + 1 + li] = indices[i + 1] + l;
  34068. indices[i + 2 + li] = indices[i] + l;
  34069. }
  34070. // normals
  34071. for (n = 0; n < ln; n++) {
  34072. normals[ln + n] = -normals[n];
  34073. }
  34074. // uvs
  34075. var lu = uvs.length;
  34076. var u = 0;
  34077. for (u = 0; u < lu; u++) {
  34078. uvs[u + lu] = uvs[u];
  34079. }
  34080. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34081. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34082. u = 0;
  34083. for (i = 0; i < lu / 2; i++) {
  34084. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34085. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34086. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34087. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34088. u += 2;
  34089. }
  34090. break;
  34091. }
  34092. };
  34093. /**
  34094. * Creates a new VertexData from the imported parameters.
  34095. */
  34096. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34097. var vertexData = new VertexData();
  34098. // positions
  34099. var positions = parsedVertexData.positions;
  34100. if (positions) {
  34101. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34102. }
  34103. // normals
  34104. var normals = parsedVertexData.normals;
  34105. if (normals) {
  34106. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34107. }
  34108. // tangents
  34109. var tangents = parsedVertexData.tangents;
  34110. if (tangents) {
  34111. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34112. }
  34113. // uvs
  34114. var uvs = parsedVertexData.uvs;
  34115. if (uvs) {
  34116. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34117. }
  34118. // uv2s
  34119. var uv2s = parsedVertexData.uv2s;
  34120. if (uv2s) {
  34121. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34122. }
  34123. // uv3s
  34124. var uv3s = parsedVertexData.uv3s;
  34125. if (uv3s) {
  34126. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34127. }
  34128. // uv4s
  34129. var uv4s = parsedVertexData.uv4s;
  34130. if (uv4s) {
  34131. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34132. }
  34133. // uv5s
  34134. var uv5s = parsedVertexData.uv5s;
  34135. if (uv5s) {
  34136. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34137. }
  34138. // uv6s
  34139. var uv6s = parsedVertexData.uv6s;
  34140. if (uv6s) {
  34141. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34142. }
  34143. // colors
  34144. var colors = parsedVertexData.colors;
  34145. if (colors) {
  34146. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34147. }
  34148. // matricesIndices
  34149. var matricesIndices = parsedVertexData.matricesIndices;
  34150. if (matricesIndices) {
  34151. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34152. }
  34153. // matricesWeights
  34154. var matricesWeights = parsedVertexData.matricesWeights;
  34155. if (matricesWeights) {
  34156. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34157. }
  34158. // indices
  34159. var indices = parsedVertexData.indices;
  34160. if (indices) {
  34161. vertexData.indices = indices;
  34162. }
  34163. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34164. };
  34165. return VertexData;
  34166. }());
  34167. BABYLON.VertexData = VertexData;
  34168. })(BABYLON || (BABYLON = {}));
  34169. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34170. var BABYLON;
  34171. (function (BABYLON) {
  34172. /**
  34173. * Class used to store geometry data (vertex buffers + index buffer)
  34174. */
  34175. var Geometry = /** @class */ (function () {
  34176. /**
  34177. * Creates a new geometry
  34178. * @param id defines the unique ID
  34179. * @param scene defines the hosting scene
  34180. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34181. * @param updatable defines if geometry must be updatable (false by default)
  34182. * @param mesh defines the mesh that will be associated with the geometry
  34183. */
  34184. function Geometry(id, scene, vertexData, updatable, mesh) {
  34185. if (updatable === void 0) { updatable = false; }
  34186. if (mesh === void 0) { mesh = null; }
  34187. /**
  34188. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34189. */
  34190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34191. this._totalVertices = 0;
  34192. this._isDisposed = false;
  34193. this._indexBufferIsUpdatable = false;
  34194. this.id = id;
  34195. this._engine = scene.getEngine();
  34196. this._meshes = [];
  34197. this._scene = scene;
  34198. //Init vertex buffer cache
  34199. this._vertexBuffers = {};
  34200. this._indices = [];
  34201. this._updatable = updatable;
  34202. // vertexData
  34203. if (vertexData) {
  34204. this.setAllVerticesData(vertexData, updatable);
  34205. }
  34206. else {
  34207. this._totalVertices = 0;
  34208. this._indices = [];
  34209. }
  34210. if (this._engine.getCaps().vertexArrayObject) {
  34211. this._vertexArrayObjects = {};
  34212. }
  34213. // applyToMesh
  34214. if (mesh) {
  34215. if (mesh.getClassName() === "LinesMesh") {
  34216. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34217. this.updateExtend();
  34218. }
  34219. this.applyToMesh(mesh);
  34220. mesh.computeWorldMatrix(true);
  34221. }
  34222. }
  34223. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34224. /**
  34225. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34226. */
  34227. get: function () {
  34228. return this._boundingBias;
  34229. },
  34230. /**
  34231. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  34232. */
  34233. set: function (value) {
  34234. if (this._boundingBias && this._boundingBias.equals(value)) {
  34235. return;
  34236. }
  34237. this._boundingBias = value.clone();
  34238. this.updateBoundingInfo(true, null);
  34239. },
  34240. enumerable: true,
  34241. configurable: true
  34242. });
  34243. /**
  34244. * Static function used to attach a new empty geometry to a mesh
  34245. * @param mesh defines the mesh to attach the geometry to
  34246. * @returns the new {BABYLON.Geometry}
  34247. */
  34248. Geometry.CreateGeometryForMesh = function (mesh) {
  34249. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34250. geometry.applyToMesh(mesh);
  34251. return geometry;
  34252. };
  34253. Object.defineProperty(Geometry.prototype, "extend", {
  34254. /**
  34255. * Gets the current extend of the geometry
  34256. */
  34257. get: function () {
  34258. return this._extend;
  34259. },
  34260. enumerable: true,
  34261. configurable: true
  34262. });
  34263. /**
  34264. * Gets the hosting scene
  34265. * @returns the hosting {BABYLON.Scene}
  34266. */
  34267. Geometry.prototype.getScene = function () {
  34268. return this._scene;
  34269. };
  34270. /**
  34271. * Gets the hosting engine
  34272. * @returns the hosting {BABYLON.Engine}
  34273. */
  34274. Geometry.prototype.getEngine = function () {
  34275. return this._engine;
  34276. };
  34277. /**
  34278. * Defines if the geometry is ready to use
  34279. * @returns true if the geometry is ready to be used
  34280. */
  34281. Geometry.prototype.isReady = function () {
  34282. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34283. };
  34284. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34285. /**
  34286. * Gets a value indicating that the geometry should not be serialized
  34287. */
  34288. get: function () {
  34289. for (var index = 0; index < this._meshes.length; index++) {
  34290. if (!this._meshes[index].doNotSerialize) {
  34291. return false;
  34292. }
  34293. }
  34294. return true;
  34295. },
  34296. enumerable: true,
  34297. configurable: true
  34298. });
  34299. /** @ignore */
  34300. Geometry.prototype._rebuild = function () {
  34301. if (this._vertexArrayObjects) {
  34302. this._vertexArrayObjects = {};
  34303. }
  34304. // Index buffer
  34305. if (this._meshes.length !== 0 && this._indices) {
  34306. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34307. }
  34308. // Vertex buffers
  34309. for (var key in this._vertexBuffers) {
  34310. var vertexBuffer = this._vertexBuffers[key];
  34311. vertexBuffer._rebuild();
  34312. }
  34313. };
  34314. /**
  34315. * Affects all gemetry data in one call
  34316. * @param vertexData defines the geometry data
  34317. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34318. */
  34319. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34320. vertexData.applyToGeometry(this, updatable);
  34321. this.notifyUpdate();
  34322. };
  34323. /**
  34324. * Set specific vertex data
  34325. * @param kind defines the data kind (Position, normal, etc...)
  34326. * @param data defines the vertex data to use
  34327. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34328. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34329. */
  34330. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34331. if (updatable === void 0) { updatable = false; }
  34332. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34333. this.setVerticesBuffer(buffer);
  34334. };
  34335. /**
  34336. * Removes a specific vertex data
  34337. * @param kind defines the data kind (Position, normal, etc...)
  34338. */
  34339. Geometry.prototype.removeVerticesData = function (kind) {
  34340. if (this._vertexBuffers[kind]) {
  34341. this._vertexBuffers[kind].dispose();
  34342. delete this._vertexBuffers[kind];
  34343. }
  34344. };
  34345. /**
  34346. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34347. * @param buffer defines the vertex buffer to use
  34348. */
  34349. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34350. var kind = buffer.getKind();
  34351. if (this._vertexBuffers[kind]) {
  34352. this._vertexBuffers[kind].dispose();
  34353. }
  34354. this._vertexBuffers[kind] = buffer;
  34355. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34356. var data = buffer.getData();
  34357. var stride = buffer.getStrideSize();
  34358. this._totalVertices = data.length / stride;
  34359. this.updateExtend(data, stride);
  34360. this._resetPointsArrayCache();
  34361. var meshes = this._meshes;
  34362. var numOfMeshes = meshes.length;
  34363. for (var index = 0; index < numOfMeshes; index++) {
  34364. var mesh = meshes[index];
  34365. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34366. mesh._createGlobalSubMesh(false);
  34367. mesh.computeWorldMatrix(true);
  34368. }
  34369. }
  34370. this.notifyUpdate(kind);
  34371. if (this._vertexArrayObjects) {
  34372. this._disposeVertexArrayObjects();
  34373. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34374. }
  34375. };
  34376. /**
  34377. * Update a specific vertex buffer
  34378. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34379. * It will do nothing if the buffer is not updatable
  34380. * @param kind defines the data kind (Position, normal, etc...)
  34381. * @param data defines the data to use
  34382. * @param offset defines the offset in the target buffer where to store the data
  34383. */
  34384. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34385. var vertexBuffer = this.getVertexBuffer(kind);
  34386. if (!vertexBuffer) {
  34387. return;
  34388. }
  34389. vertexBuffer.updateDirectly(data, offset);
  34390. this.notifyUpdate(kind);
  34391. };
  34392. /**
  34393. * Update a specific vertex buffer
  34394. * This function will create a new buffer if the current one is not updatable
  34395. * @param kind defines the data kind (Position, normal, etc...)
  34396. * @param data defines the data to use
  34397. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34398. */
  34399. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34400. if (updateExtends === void 0) { updateExtends = false; }
  34401. var vertexBuffer = this.getVertexBuffer(kind);
  34402. if (!vertexBuffer) {
  34403. return;
  34404. }
  34405. vertexBuffer.update(data);
  34406. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34407. var stride = vertexBuffer.getStrideSize();
  34408. this._totalVertices = data.length / stride;
  34409. this.updateBoundingInfo(updateExtends, data);
  34410. }
  34411. this.notifyUpdate(kind);
  34412. };
  34413. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34414. if (updateExtends) {
  34415. this.updateExtend(data);
  34416. }
  34417. var meshes = this._meshes;
  34418. var numOfMeshes = meshes.length;
  34419. this._resetPointsArrayCache();
  34420. for (var index = 0; index < numOfMeshes; index++) {
  34421. var mesh = meshes[index];
  34422. if (updateExtends) {
  34423. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34424. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34425. var subMesh = mesh.subMeshes[subIndex];
  34426. subMesh.refreshBoundingInfo();
  34427. }
  34428. }
  34429. }
  34430. };
  34431. /** @ignore */
  34432. Geometry.prototype._bind = function (effect, indexToBind) {
  34433. if (!effect) {
  34434. return;
  34435. }
  34436. if (indexToBind === undefined) {
  34437. indexToBind = this._indexBuffer;
  34438. }
  34439. var vbs = this.getVertexBuffers();
  34440. if (!vbs) {
  34441. return;
  34442. }
  34443. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34444. this._engine.bindBuffers(vbs, indexToBind, effect);
  34445. return;
  34446. }
  34447. // Using VAO
  34448. if (!this._vertexArrayObjects[effect.key]) {
  34449. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34450. }
  34451. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34452. };
  34453. /**
  34454. * Gets total number of vertices
  34455. * @returns the total number of vertices
  34456. */
  34457. Geometry.prototype.getTotalVertices = function () {
  34458. if (!this.isReady()) {
  34459. return 0;
  34460. }
  34461. return this._totalVertices;
  34462. };
  34463. /**
  34464. * Gets a specific vertex data attached to this geometry
  34465. * @param kind defines the data kind (Position, normal, etc...)
  34466. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34467. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34468. * @returns a float array containing vertex data
  34469. */
  34470. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34471. var vertexBuffer = this.getVertexBuffer(kind);
  34472. if (!vertexBuffer) {
  34473. return null;
  34474. }
  34475. var orig = vertexBuffer.getData();
  34476. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34477. return orig;
  34478. }
  34479. else {
  34480. var len = orig.length;
  34481. var copy = [];
  34482. for (var i = 0; i < len; i++) {
  34483. copy.push(orig[i]);
  34484. }
  34485. return copy;
  34486. }
  34487. };
  34488. /**
  34489. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34490. * @param kind defines the data kind (Position, normal, etc...)
  34491. * @returns true if the vertex buffer with the specified kind is updatable
  34492. */
  34493. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34494. var vb = this._vertexBuffers[kind];
  34495. if (!vb) {
  34496. return false;
  34497. }
  34498. return vb.isUpdatable();
  34499. };
  34500. /**
  34501. * Gets a specific vertex buffer
  34502. * @param kind defines the data kind (Position, normal, etc...)
  34503. * @returns a {BABYLON.VertexBuffer}
  34504. */
  34505. Geometry.prototype.getVertexBuffer = function (kind) {
  34506. if (!this.isReady()) {
  34507. return null;
  34508. }
  34509. return this._vertexBuffers[kind];
  34510. };
  34511. /**
  34512. * Returns all vertex buffers
  34513. * @return an object holding all vertex buffers indexed by kind
  34514. */
  34515. Geometry.prototype.getVertexBuffers = function () {
  34516. if (!this.isReady()) {
  34517. return null;
  34518. }
  34519. return this._vertexBuffers;
  34520. };
  34521. /**
  34522. * Gets a boolean indicating if specific vertex buffer is present
  34523. * @param kind defines the data kind (Position, normal, etc...)
  34524. * @returns true if data is present
  34525. */
  34526. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34527. if (!this._vertexBuffers) {
  34528. if (this._delayInfo) {
  34529. return this._delayInfo.indexOf(kind) !== -1;
  34530. }
  34531. return false;
  34532. }
  34533. return this._vertexBuffers[kind] !== undefined;
  34534. };
  34535. /**
  34536. * Gets a list of all attached data kinds (Position, normal, etc...)
  34537. * @returns a list of string containing all kinds
  34538. */
  34539. Geometry.prototype.getVerticesDataKinds = function () {
  34540. var result = [];
  34541. var kind;
  34542. if (!this._vertexBuffers && this._delayInfo) {
  34543. for (kind in this._delayInfo) {
  34544. result.push(kind);
  34545. }
  34546. }
  34547. else {
  34548. for (kind in this._vertexBuffers) {
  34549. result.push(kind);
  34550. }
  34551. }
  34552. return result;
  34553. };
  34554. /**
  34555. * Update index buffer
  34556. * @param indices defines the indices to store in the index buffer
  34557. * @param offset defines the offset in the target buffer where to store the data
  34558. */
  34559. Geometry.prototype.updateIndices = function (indices, offset) {
  34560. if (!this._indexBuffer) {
  34561. return;
  34562. }
  34563. if (!this._indexBufferIsUpdatable) {
  34564. this.setIndices(indices, null, true);
  34565. }
  34566. else {
  34567. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34568. }
  34569. };
  34570. /**
  34571. * Creates a new index buffer
  34572. * @param indices defines the indices to store in the index buffer
  34573. * @param totalVertices defines the total number of vertices (could be null)
  34574. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34575. */
  34576. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34577. if (totalVertices === void 0) { totalVertices = null; }
  34578. if (updatable === void 0) { updatable = false; }
  34579. if (this._indexBuffer) {
  34580. this._engine._releaseBuffer(this._indexBuffer);
  34581. }
  34582. this._disposeVertexArrayObjects();
  34583. this._indices = indices;
  34584. this._indexBufferIsUpdatable = updatable;
  34585. if (this._meshes.length !== 0 && this._indices) {
  34586. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34587. }
  34588. if (totalVertices != undefined) {
  34589. this._totalVertices = totalVertices;
  34590. }
  34591. var meshes = this._meshes;
  34592. var numOfMeshes = meshes.length;
  34593. for (var index = 0; index < numOfMeshes; index++) {
  34594. meshes[index]._createGlobalSubMesh(true);
  34595. }
  34596. this.notifyUpdate();
  34597. };
  34598. /**
  34599. * Return the total number of indices
  34600. * @returns the total number of indices
  34601. */
  34602. Geometry.prototype.getTotalIndices = function () {
  34603. if (!this.isReady()) {
  34604. return 0;
  34605. }
  34606. return this._indices.length;
  34607. };
  34608. /**
  34609. * Gets the index buffer array
  34610. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34611. * @returns the index buffer array
  34612. */
  34613. Geometry.prototype.getIndices = function (copyWhenShared) {
  34614. if (!this.isReady()) {
  34615. return null;
  34616. }
  34617. var orig = this._indices;
  34618. if (!copyWhenShared || this._meshes.length === 1) {
  34619. return orig;
  34620. }
  34621. else {
  34622. var len = orig.length;
  34623. var copy = [];
  34624. for (var i = 0; i < len; i++) {
  34625. copy.push(orig[i]);
  34626. }
  34627. return copy;
  34628. }
  34629. };
  34630. /**
  34631. * Gets the index buffer
  34632. * @return the index buffer
  34633. */
  34634. Geometry.prototype.getIndexBuffer = function () {
  34635. if (!this.isReady()) {
  34636. return null;
  34637. }
  34638. return this._indexBuffer;
  34639. };
  34640. /** @ignore */
  34641. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34642. if (effect === void 0) { effect = null; }
  34643. if (!effect || !this._vertexArrayObjects) {
  34644. return;
  34645. }
  34646. if (this._vertexArrayObjects[effect.key]) {
  34647. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34648. delete this._vertexArrayObjects[effect.key];
  34649. }
  34650. };
  34651. /**
  34652. * Release the associated resources for a specific mesh
  34653. * @param mesh defines the source mesh
  34654. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34655. */
  34656. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34657. var meshes = this._meshes;
  34658. var index = meshes.indexOf(mesh);
  34659. if (index === -1) {
  34660. return;
  34661. }
  34662. meshes.splice(index, 1);
  34663. mesh._geometry = null;
  34664. if (meshes.length === 0 && shouldDispose) {
  34665. this.dispose();
  34666. }
  34667. };
  34668. /**
  34669. * Apply current geometry to a given mesh
  34670. * @param mesh defines the mesh to apply geometry to
  34671. */
  34672. Geometry.prototype.applyToMesh = function (mesh) {
  34673. if (mesh._geometry === this) {
  34674. return;
  34675. }
  34676. var previousGeometry = mesh._geometry;
  34677. if (previousGeometry) {
  34678. previousGeometry.releaseForMesh(mesh);
  34679. }
  34680. var meshes = this._meshes;
  34681. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34682. mesh._geometry = this;
  34683. this._scene.pushGeometry(this);
  34684. meshes.push(mesh);
  34685. if (this.isReady()) {
  34686. this._applyToMesh(mesh);
  34687. }
  34688. else {
  34689. mesh._boundingInfo = this._boundingInfo;
  34690. }
  34691. };
  34692. Geometry.prototype.updateExtend = function (data, stride) {
  34693. if (data === void 0) { data = null; }
  34694. if (!data) {
  34695. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34696. }
  34697. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34698. };
  34699. Geometry.prototype._applyToMesh = function (mesh) {
  34700. var numOfMeshes = this._meshes.length;
  34701. // vertexBuffers
  34702. for (var kind in this._vertexBuffers) {
  34703. if (numOfMeshes === 1) {
  34704. this._vertexBuffers[kind].create();
  34705. }
  34706. var buffer = this._vertexBuffers[kind].getBuffer();
  34707. if (buffer)
  34708. buffer.references = numOfMeshes;
  34709. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34710. if (!this._extend) {
  34711. this.updateExtend(this._vertexBuffers[kind].getData());
  34712. }
  34713. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34714. mesh._createGlobalSubMesh(false);
  34715. //bounding info was just created again, world matrix should be applied again.
  34716. mesh._updateBoundingInfo();
  34717. }
  34718. }
  34719. // indexBuffer
  34720. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34721. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34722. }
  34723. if (this._indexBuffer) {
  34724. this._indexBuffer.references = numOfMeshes;
  34725. }
  34726. };
  34727. Geometry.prototype.notifyUpdate = function (kind) {
  34728. if (this.onGeometryUpdated) {
  34729. this.onGeometryUpdated(this, kind);
  34730. }
  34731. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34732. var mesh = _a[_i];
  34733. mesh._markSubMeshesAsAttributesDirty();
  34734. }
  34735. };
  34736. /**
  34737. * Load the geometry if it was flagged as delay loaded
  34738. * @param scene defines the hosting scene
  34739. * @param onLoaded defines a callback called when the geometry is loaded
  34740. */
  34741. Geometry.prototype.load = function (scene, onLoaded) {
  34742. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34743. return;
  34744. }
  34745. if (this.isReady()) {
  34746. if (onLoaded) {
  34747. onLoaded();
  34748. }
  34749. return;
  34750. }
  34751. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34752. this._queueLoad(scene, onLoaded);
  34753. };
  34754. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34755. var _this = this;
  34756. if (!this.delayLoadingFile) {
  34757. return;
  34758. }
  34759. scene._addPendingData(this);
  34760. scene._loadFile(this.delayLoadingFile, function (data) {
  34761. if (!_this._delayLoadingFunction) {
  34762. return;
  34763. }
  34764. _this._delayLoadingFunction(JSON.parse(data), _this);
  34765. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34766. _this._delayInfo = [];
  34767. scene._removePendingData(_this);
  34768. var meshes = _this._meshes;
  34769. var numOfMeshes = meshes.length;
  34770. for (var index = 0; index < numOfMeshes; index++) {
  34771. _this._applyToMesh(meshes[index]);
  34772. }
  34773. if (onLoaded) {
  34774. onLoaded();
  34775. }
  34776. }, undefined, true);
  34777. };
  34778. /**
  34779. * Invert the geometry to move from a right handed system to a left handed one.
  34780. */
  34781. Geometry.prototype.toLeftHanded = function () {
  34782. // Flip faces
  34783. var tIndices = this.getIndices(false);
  34784. if (tIndices != null && tIndices.length > 0) {
  34785. for (var i = 0; i < tIndices.length; i += 3) {
  34786. var tTemp = tIndices[i + 0];
  34787. tIndices[i + 0] = tIndices[i + 2];
  34788. tIndices[i + 2] = tTemp;
  34789. }
  34790. this.setIndices(tIndices);
  34791. }
  34792. // Negate position.z
  34793. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34794. if (tPositions != null && tPositions.length > 0) {
  34795. for (var i = 0; i < tPositions.length; i += 3) {
  34796. tPositions[i + 2] = -tPositions[i + 2];
  34797. }
  34798. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34799. }
  34800. // Negate normal.z
  34801. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34802. if (tNormals != null && tNormals.length > 0) {
  34803. for (var i = 0; i < tNormals.length; i += 3) {
  34804. tNormals[i + 2] = -tNormals[i + 2];
  34805. }
  34806. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34807. }
  34808. };
  34809. // Cache
  34810. /** @ignore */
  34811. Geometry.prototype._resetPointsArrayCache = function () {
  34812. this._positions = null;
  34813. };
  34814. /** @ignore */
  34815. Geometry.prototype._generatePointsArray = function () {
  34816. if (this._positions)
  34817. return true;
  34818. this._positions = [];
  34819. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34820. if (!data) {
  34821. return false;
  34822. }
  34823. for (var index = 0; index < data.length; index += 3) {
  34824. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34825. }
  34826. return true;
  34827. };
  34828. /**
  34829. * Gets a value indicating if the geometry is disposed
  34830. * @returns true if the geometry was disposed
  34831. */
  34832. Geometry.prototype.isDisposed = function () {
  34833. return this._isDisposed;
  34834. };
  34835. Geometry.prototype._disposeVertexArrayObjects = function () {
  34836. if (this._vertexArrayObjects) {
  34837. for (var kind in this._vertexArrayObjects) {
  34838. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34839. }
  34840. this._vertexArrayObjects = {};
  34841. }
  34842. };
  34843. /**
  34844. * Free all associated resources
  34845. */
  34846. Geometry.prototype.dispose = function () {
  34847. var meshes = this._meshes;
  34848. var numOfMeshes = meshes.length;
  34849. var index;
  34850. for (index = 0; index < numOfMeshes; index++) {
  34851. this.releaseForMesh(meshes[index]);
  34852. }
  34853. this._meshes = [];
  34854. this._disposeVertexArrayObjects();
  34855. for (var kind in this._vertexBuffers) {
  34856. this._vertexBuffers[kind].dispose();
  34857. }
  34858. this._vertexBuffers = {};
  34859. this._totalVertices = 0;
  34860. if (this._indexBuffer) {
  34861. this._engine._releaseBuffer(this._indexBuffer);
  34862. }
  34863. this._indexBuffer = null;
  34864. this._indices = [];
  34865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34866. this.delayLoadingFile = null;
  34867. this._delayLoadingFunction = null;
  34868. this._delayInfo = [];
  34869. this._boundingInfo = null;
  34870. this._scene.removeGeometry(this);
  34871. this._isDisposed = true;
  34872. };
  34873. /**
  34874. * Clone the current geometry into a new geometry
  34875. * @param id defines the unique ID of the new geometry
  34876. * @returns a new geometry object
  34877. */
  34878. Geometry.prototype.copy = function (id) {
  34879. var vertexData = new BABYLON.VertexData();
  34880. vertexData.indices = [];
  34881. var indices = this.getIndices();
  34882. if (indices) {
  34883. for (var index = 0; index < indices.length; index++) {
  34884. vertexData.indices.push(indices[index]);
  34885. }
  34886. }
  34887. var updatable = false;
  34888. var stopChecking = false;
  34889. var kind;
  34890. for (kind in this._vertexBuffers) {
  34891. // using slice() to make a copy of the array and not just reference it
  34892. var data = this.getVerticesData(kind);
  34893. if (data instanceof Float32Array) {
  34894. vertexData.set(new Float32Array(data), kind);
  34895. }
  34896. else {
  34897. vertexData.set(data.slice(0), kind);
  34898. }
  34899. if (!stopChecking) {
  34900. var vb = this.getVertexBuffer(kind);
  34901. if (vb) {
  34902. updatable = vb.isUpdatable();
  34903. stopChecking = !updatable;
  34904. }
  34905. }
  34906. }
  34907. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34908. geometry.delayLoadState = this.delayLoadState;
  34909. geometry.delayLoadingFile = this.delayLoadingFile;
  34910. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34911. for (kind in this._delayInfo) {
  34912. geometry._delayInfo = geometry._delayInfo || [];
  34913. geometry._delayInfo.push(kind);
  34914. }
  34915. // Bounding info
  34916. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34917. return geometry;
  34918. };
  34919. /**
  34920. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34921. * @return a JSON representation of the current geometry data (without the vertices data)
  34922. */
  34923. Geometry.prototype.serialize = function () {
  34924. var serializationObject = {};
  34925. serializationObject.id = this.id;
  34926. serializationObject.updatable = this._updatable;
  34927. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34928. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34929. }
  34930. return serializationObject;
  34931. };
  34932. Geometry.prototype.toNumberArray = function (origin) {
  34933. if (Array.isArray(origin)) {
  34934. return origin;
  34935. }
  34936. else {
  34937. return Array.prototype.slice.call(origin);
  34938. }
  34939. };
  34940. /**
  34941. * Serialize all vertices data into a JSON oject
  34942. * @returns a JSON representation of the current geometry data
  34943. */
  34944. Geometry.prototype.serializeVerticeData = function () {
  34945. var serializationObject = this.serialize();
  34946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34947. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34949. serializationObject.positions._updatable = true;
  34950. }
  34951. }
  34952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34953. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34954. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34955. serializationObject.normals._updatable = true;
  34956. }
  34957. }
  34958. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34959. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34960. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34961. serializationObject.tangets._updatable = true;
  34962. }
  34963. }
  34964. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34965. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34966. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34967. serializationObject.uvs._updatable = true;
  34968. }
  34969. }
  34970. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34971. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34972. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34973. serializationObject.uv2s._updatable = true;
  34974. }
  34975. }
  34976. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34977. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34978. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34979. serializationObject.uv3s._updatable = true;
  34980. }
  34981. }
  34982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34983. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34984. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34985. serializationObject.uv4s._updatable = true;
  34986. }
  34987. }
  34988. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34989. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34990. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34991. serializationObject.uv5s._updatable = true;
  34992. }
  34993. }
  34994. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34995. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34996. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34997. serializationObject.uv6s._updatable = true;
  34998. }
  34999. }
  35000. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35001. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35002. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35003. serializationObject.colors._updatable = true;
  35004. }
  35005. }
  35006. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35007. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35008. serializationObject.matricesIndices._isExpanded = true;
  35009. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35010. serializationObject.matricesIndices._updatable = true;
  35011. }
  35012. }
  35013. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35014. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35015. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35016. serializationObject.matricesWeights._updatable = true;
  35017. }
  35018. }
  35019. serializationObject.indices = this.toNumberArray(this.getIndices());
  35020. return serializationObject;
  35021. };
  35022. // Statics
  35023. /**
  35024. * Extracts a clone of a mesh geometry
  35025. * @param mesh defines the source mesh
  35026. * @param id defines the unique ID of the new geometry object
  35027. * @returns the new geometry object
  35028. */
  35029. Geometry.ExtractFromMesh = function (mesh, id) {
  35030. var geometry = mesh._geometry;
  35031. if (!geometry) {
  35032. return null;
  35033. }
  35034. return geometry.copy(id);
  35035. };
  35036. /**
  35037. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35038. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35039. * Be aware Math.random() could cause collisions, but:
  35040. * "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"
  35041. * @returns a string containing a new GUID
  35042. */
  35043. Geometry.RandomId = function () {
  35044. return BABYLON.Tools.RandomId();
  35045. };
  35046. /** @ignore */
  35047. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35048. var scene = mesh.getScene();
  35049. // Geometry
  35050. var geometryId = parsedGeometry.geometryId;
  35051. if (geometryId) {
  35052. var geometry = scene.getGeometryByID(geometryId);
  35053. if (geometry) {
  35054. geometry.applyToMesh(mesh);
  35055. }
  35056. }
  35057. else if (parsedGeometry instanceof ArrayBuffer) {
  35058. var binaryInfo = mesh._binaryInfo;
  35059. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35060. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35061. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35062. }
  35063. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35064. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35065. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35066. }
  35067. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35068. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35069. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35070. }
  35071. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35072. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35073. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35074. }
  35075. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35076. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35077. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35078. }
  35079. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35080. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35081. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35082. }
  35083. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35084. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35085. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35086. }
  35087. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35088. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35089. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35090. }
  35091. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35092. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35093. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35094. }
  35095. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35096. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35097. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35098. }
  35099. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35100. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35101. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35102. }
  35103. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35104. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35106. }
  35107. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35108. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35109. mesh.setIndices(indicesData, null);
  35110. }
  35111. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35112. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35113. mesh.subMeshes = [];
  35114. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35115. var materialIndex = subMeshesData[(i * 5) + 0];
  35116. var verticesStart = subMeshesData[(i * 5) + 1];
  35117. var verticesCount = subMeshesData[(i * 5) + 2];
  35118. var indexStart = subMeshesData[(i * 5) + 3];
  35119. var indexCount = subMeshesData[(i * 5) + 4];
  35120. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35121. }
  35122. }
  35123. }
  35124. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35125. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35126. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35127. if (parsedGeometry.tangents) {
  35128. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35129. }
  35130. if (parsedGeometry.uvs) {
  35131. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35132. }
  35133. if (parsedGeometry.uvs2) {
  35134. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35135. }
  35136. if (parsedGeometry.uvs3) {
  35137. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35138. }
  35139. if (parsedGeometry.uvs4) {
  35140. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35141. }
  35142. if (parsedGeometry.uvs5) {
  35143. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35144. }
  35145. if (parsedGeometry.uvs6) {
  35146. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35147. }
  35148. if (parsedGeometry.colors) {
  35149. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35150. }
  35151. if (parsedGeometry.matricesIndices) {
  35152. if (!parsedGeometry.matricesIndices._isExpanded) {
  35153. var floatIndices = [];
  35154. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35155. var matricesIndex = parsedGeometry.matricesIndices[i];
  35156. floatIndices.push(matricesIndex & 0x000000FF);
  35157. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35158. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35159. floatIndices.push(matricesIndex >> 24);
  35160. }
  35161. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35162. }
  35163. else {
  35164. delete parsedGeometry.matricesIndices._isExpanded;
  35165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35166. }
  35167. }
  35168. if (parsedGeometry.matricesIndicesExtra) {
  35169. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35170. var floatIndices = [];
  35171. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35172. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35173. floatIndices.push(matricesIndex & 0x000000FF);
  35174. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35175. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35176. floatIndices.push(matricesIndex >> 24);
  35177. }
  35178. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35179. }
  35180. else {
  35181. delete parsedGeometry.matricesIndices._isExpanded;
  35182. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35183. }
  35184. }
  35185. if (parsedGeometry.matricesWeights) {
  35186. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35187. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35188. }
  35189. if (parsedGeometry.matricesWeightsExtra) {
  35190. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35191. }
  35192. mesh.setIndices(parsedGeometry.indices, null);
  35193. }
  35194. // SubMeshes
  35195. if (parsedGeometry.subMeshes) {
  35196. mesh.subMeshes = [];
  35197. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35198. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35199. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35200. }
  35201. }
  35202. // Flat shading
  35203. if (mesh._shouldGenerateFlatShading) {
  35204. mesh.convertToFlatShadedMesh();
  35205. delete mesh._shouldGenerateFlatShading;
  35206. }
  35207. // Update
  35208. mesh.computeWorldMatrix(true);
  35209. // Octree
  35210. var sceneOctree = scene.selectionOctree;
  35211. if (sceneOctree !== undefined && sceneOctree !== null) {
  35212. sceneOctree.addMesh(mesh);
  35213. }
  35214. };
  35215. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35216. var epsilon = 1e-3;
  35217. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35218. return;
  35219. }
  35220. var noInfluenceBoneIndex = 0.0;
  35221. if (parsedGeometry.skeletonId > -1) {
  35222. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35223. if (!skeleton) {
  35224. return;
  35225. }
  35226. noInfluenceBoneIndex = skeleton.bones.length;
  35227. }
  35228. else {
  35229. return;
  35230. }
  35231. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35232. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35233. var matricesWeights = parsedGeometry.matricesWeights;
  35234. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35235. var influencers = parsedGeometry.numBoneInfluencer;
  35236. var size = matricesWeights.length;
  35237. for (var i = 0; i < size; i += 4) {
  35238. var weight = 0.0;
  35239. var firstZeroWeight = -1;
  35240. for (var j = 0; j < 4; j++) {
  35241. var w = matricesWeights[i + j];
  35242. weight += w;
  35243. if (w < epsilon && firstZeroWeight < 0) {
  35244. firstZeroWeight = j;
  35245. }
  35246. }
  35247. if (matricesWeightsExtra) {
  35248. for (var j = 0; j < 4; j++) {
  35249. var w = matricesWeightsExtra[i + j];
  35250. weight += w;
  35251. if (w < epsilon && firstZeroWeight < 0) {
  35252. firstZeroWeight = j + 4;
  35253. }
  35254. }
  35255. }
  35256. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35257. firstZeroWeight = influencers - 1;
  35258. }
  35259. if (weight > epsilon) {
  35260. var mweight = 1.0 / weight;
  35261. for (var j = 0; j < 4; j++) {
  35262. matricesWeights[i + j] *= mweight;
  35263. }
  35264. if (matricesWeightsExtra) {
  35265. for (var j = 0; j < 4; j++) {
  35266. matricesWeightsExtra[i + j] *= mweight;
  35267. }
  35268. }
  35269. }
  35270. else {
  35271. if (firstZeroWeight >= 4) {
  35272. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35273. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35274. }
  35275. else {
  35276. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35277. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35278. }
  35279. }
  35280. }
  35281. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35282. if (parsedGeometry.matricesWeightsExtra) {
  35283. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35284. }
  35285. };
  35286. /**
  35287. * Create a new geometry from persisted data (Using .babylon file format)
  35288. * @param parsedVertexData defines the persisted data
  35289. * @param scene defines the hosting scene
  35290. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35291. * @returns the new geometry object
  35292. */
  35293. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35294. if (scene.getGeometryByID(parsedVertexData.id)) {
  35295. return null; // null since geometry could be something else than a box...
  35296. }
  35297. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35298. if (BABYLON.Tags) {
  35299. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35300. }
  35301. if (parsedVertexData.delayLoadingFile) {
  35302. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35303. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35304. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35305. geometry._delayInfo = [];
  35306. if (parsedVertexData.hasUVs) {
  35307. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35308. }
  35309. if (parsedVertexData.hasUVs2) {
  35310. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35311. }
  35312. if (parsedVertexData.hasUVs3) {
  35313. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35314. }
  35315. if (parsedVertexData.hasUVs4) {
  35316. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35317. }
  35318. if (parsedVertexData.hasUVs5) {
  35319. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35320. }
  35321. if (parsedVertexData.hasUVs6) {
  35322. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35323. }
  35324. if (parsedVertexData.hasColors) {
  35325. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35326. }
  35327. if (parsedVertexData.hasMatricesIndices) {
  35328. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35329. }
  35330. if (parsedVertexData.hasMatricesWeights) {
  35331. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35332. }
  35333. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35334. }
  35335. else {
  35336. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35337. }
  35338. scene.pushGeometry(geometry, true);
  35339. return geometry;
  35340. };
  35341. return Geometry;
  35342. }());
  35343. BABYLON.Geometry = Geometry;
  35344. // Primitives
  35345. /// Abstract class
  35346. /**
  35347. * Abstract class used to provide common services for all typed geometries
  35348. */
  35349. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35350. __extends(_PrimitiveGeometry, _super);
  35351. /**
  35352. * Creates a new typed geometry
  35353. * @param id defines the unique ID of the geometry
  35354. * @param scene defines the hosting scene
  35355. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35356. * @param mesh defines the hosting mesh (can be null)
  35357. */
  35358. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35359. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35360. if (mesh === void 0) { mesh = null; }
  35361. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35362. _this._canBeRegenerated = _canBeRegenerated;
  35363. _this._beingRegenerated = true;
  35364. _this.regenerate();
  35365. _this._beingRegenerated = false;
  35366. return _this;
  35367. }
  35368. /**
  35369. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35370. * @returns true if the geometry can be regenerated
  35371. */
  35372. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35373. return this._canBeRegenerated;
  35374. };
  35375. /**
  35376. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35377. */
  35378. _PrimitiveGeometry.prototype.regenerate = function () {
  35379. if (!this._canBeRegenerated) {
  35380. return;
  35381. }
  35382. this._beingRegenerated = true;
  35383. this.setAllVerticesData(this._regenerateVertexData(), false);
  35384. this._beingRegenerated = false;
  35385. };
  35386. /**
  35387. * Clone the geometry
  35388. * @param id defines the unique ID of the new geometry
  35389. * @returns the new geometry
  35390. */
  35391. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35392. return _super.prototype.copy.call(this, id);
  35393. };
  35394. // overrides
  35395. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35396. if (!this._beingRegenerated) {
  35397. return;
  35398. }
  35399. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35400. };
  35401. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35402. if (!this._beingRegenerated) {
  35403. return;
  35404. }
  35405. _super.prototype.setVerticesData.call(this, kind, data, false);
  35406. };
  35407. // to override
  35408. /** @ignore */
  35409. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35410. throw new Error("Abstract method");
  35411. };
  35412. _PrimitiveGeometry.prototype.copy = function (id) {
  35413. throw new Error("Must be overriden in sub-classes.");
  35414. };
  35415. _PrimitiveGeometry.prototype.serialize = function () {
  35416. var serializationObject = _super.prototype.serialize.call(this);
  35417. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35418. return serializationObject;
  35419. };
  35420. return _PrimitiveGeometry;
  35421. }(Geometry));
  35422. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35423. /**
  35424. * Creates a ribbon geometry
  35425. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35426. */
  35427. var RibbonGeometry = /** @class */ (function (_super) {
  35428. __extends(RibbonGeometry, _super);
  35429. /**
  35430. * Creates a ribbon geometry
  35431. * @param id defines the unique ID of the geometry
  35432. * @param scene defines the hosting scene
  35433. * @param pathArray defines the array of paths to use
  35434. * @param closeArray defines if the last path and the first path must be joined
  35435. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35436. * @param offset defines the offset between points
  35437. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35438. * @param mesh defines the hosting mesh (can be null)
  35439. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35440. */
  35441. function RibbonGeometry(id, scene,
  35442. /**
  35443. * Defines the array of paths to use
  35444. */
  35445. pathArray,
  35446. /**
  35447. * Defines if the last and first points of each path in your pathArray must be joined
  35448. */
  35449. closeArray,
  35450. /**
  35451. * Defines if the last and first points of each path in your pathArray must be joined
  35452. */
  35453. closePath,
  35454. /**
  35455. * Defines the offset between points
  35456. */
  35457. offset, canBeRegenerated, mesh,
  35458. /**
  35459. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35460. */
  35461. side) {
  35462. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35463. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35464. _this.pathArray = pathArray;
  35465. _this.closeArray = closeArray;
  35466. _this.closePath = closePath;
  35467. _this.offset = offset;
  35468. _this.side = side;
  35469. return _this;
  35470. }
  35471. /** @ignore */
  35472. RibbonGeometry.prototype._regenerateVertexData = function () {
  35473. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35474. };
  35475. RibbonGeometry.prototype.copy = function (id) {
  35476. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35477. };
  35478. return RibbonGeometry;
  35479. }(_PrimitiveGeometry));
  35480. BABYLON.RibbonGeometry = RibbonGeometry;
  35481. /**
  35482. * Creates a box geometry
  35483. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35484. */
  35485. var BoxGeometry = /** @class */ (function (_super) {
  35486. __extends(BoxGeometry, _super);
  35487. /**
  35488. * Creates a box geometry
  35489. * @param id defines the unique ID of the geometry
  35490. * @param scene defines the hosting scene
  35491. * @param size defines the zise of the box (width, height and depth are the same)
  35492. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35493. * @param mesh defines the hosting mesh (can be null)
  35494. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35495. */
  35496. function BoxGeometry(id, scene,
  35497. /**
  35498. * Defines the zise of the box (width, height and depth are the same)
  35499. */
  35500. size, canBeRegenerated, mesh,
  35501. /**
  35502. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35503. */
  35504. side) {
  35505. if (mesh === void 0) { mesh = null; }
  35506. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35507. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35508. _this.size = size;
  35509. _this.side = side;
  35510. return _this;
  35511. }
  35512. BoxGeometry.prototype._regenerateVertexData = function () {
  35513. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35514. };
  35515. BoxGeometry.prototype.copy = function (id) {
  35516. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35517. };
  35518. BoxGeometry.prototype.serialize = function () {
  35519. var serializationObject = _super.prototype.serialize.call(this);
  35520. serializationObject.size = this.size;
  35521. return serializationObject;
  35522. };
  35523. BoxGeometry.Parse = function (parsedBox, scene) {
  35524. if (scene.getGeometryByID(parsedBox.id)) {
  35525. return null; // null since geometry could be something else than a box...
  35526. }
  35527. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35528. if (BABYLON.Tags) {
  35529. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35530. }
  35531. scene.pushGeometry(box, true);
  35532. return box;
  35533. };
  35534. return BoxGeometry;
  35535. }(_PrimitiveGeometry));
  35536. BABYLON.BoxGeometry = BoxGeometry;
  35537. /**
  35538. * Creates a sphere geometry
  35539. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35540. */
  35541. var SphereGeometry = /** @class */ (function (_super) {
  35542. __extends(SphereGeometry, _super);
  35543. /**
  35544. * Create a new sphere geometry
  35545. * @param id defines the unique ID of the geometry
  35546. * @param scene defines the hosting scene
  35547. * @param segments defines the number of segments to use to create the sphere
  35548. * @param diameter defines the diameter of the sphere
  35549. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35550. * @param mesh defines the hosting mesh (can be null)
  35551. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35552. */
  35553. function SphereGeometry(id, scene,
  35554. /**
  35555. * Defines the number of segments to use to create the sphere
  35556. */
  35557. segments,
  35558. /**
  35559. * Defines the diameter of the sphere
  35560. */
  35561. diameter, canBeRegenerated, mesh,
  35562. /**
  35563. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35564. */
  35565. side) {
  35566. if (mesh === void 0) { mesh = null; }
  35567. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35568. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35569. _this.segments = segments;
  35570. _this.diameter = diameter;
  35571. _this.side = side;
  35572. return _this;
  35573. }
  35574. SphereGeometry.prototype._regenerateVertexData = function () {
  35575. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35576. };
  35577. SphereGeometry.prototype.copy = function (id) {
  35578. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35579. };
  35580. SphereGeometry.prototype.serialize = function () {
  35581. var serializationObject = _super.prototype.serialize.call(this);
  35582. serializationObject.segments = this.segments;
  35583. serializationObject.diameter = this.diameter;
  35584. return serializationObject;
  35585. };
  35586. SphereGeometry.Parse = function (parsedSphere, scene) {
  35587. if (scene.getGeometryByID(parsedSphere.id)) {
  35588. return null; // null since geometry could be something else than a sphere...
  35589. }
  35590. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35591. if (BABYLON.Tags) {
  35592. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35593. }
  35594. scene.pushGeometry(sphere, true);
  35595. return sphere;
  35596. };
  35597. return SphereGeometry;
  35598. }(_PrimitiveGeometry));
  35599. BABYLON.SphereGeometry = SphereGeometry;
  35600. /**
  35601. * Creates a disc geometry
  35602. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35603. */
  35604. var DiscGeometry = /** @class */ (function (_super) {
  35605. __extends(DiscGeometry, _super);
  35606. /**
  35607. * Creates a new disc geometry
  35608. * @param id defines the unique ID of the geometry
  35609. * @param scene defines the hosting scene
  35610. * @param radius defines the radius of the disc
  35611. * @param tessellation defines the tesselation factor to apply to the disc
  35612. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35613. * @param mesh defines the hosting mesh (can be null)
  35614. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35615. */
  35616. function DiscGeometry(id, scene,
  35617. /**
  35618. * Defines the radius of the disc
  35619. */
  35620. radius,
  35621. /**
  35622. * Defines the tesselation factor to apply to the disc
  35623. */
  35624. tessellation, canBeRegenerated, mesh,
  35625. /**
  35626. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35627. */
  35628. side) {
  35629. if (mesh === void 0) { mesh = null; }
  35630. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35631. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35632. _this.radius = radius;
  35633. _this.tessellation = tessellation;
  35634. _this.side = side;
  35635. return _this;
  35636. }
  35637. DiscGeometry.prototype._regenerateVertexData = function () {
  35638. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35639. };
  35640. DiscGeometry.prototype.copy = function (id) {
  35641. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35642. };
  35643. return DiscGeometry;
  35644. }(_PrimitiveGeometry));
  35645. BABYLON.DiscGeometry = DiscGeometry;
  35646. /**
  35647. * Creates a new cylinder geometry
  35648. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35649. */
  35650. var CylinderGeometry = /** @class */ (function (_super) {
  35651. __extends(CylinderGeometry, _super);
  35652. /**
  35653. * Creates a new cylinder geometry
  35654. * @param id defines the unique ID of the geometry
  35655. * @param scene defines the hosting scene
  35656. * @param height defines the height of the cylinder
  35657. * @param diameterTop defines the diameter of the cylinder's top cap
  35658. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35659. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35660. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35661. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35662. * @param mesh defines the hosting mesh (can be null)
  35663. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35664. */
  35665. function CylinderGeometry(id, scene,
  35666. /**
  35667. * Defines the height of the cylinder
  35668. */
  35669. height,
  35670. /**
  35671. * Defines the diameter of the cylinder's top cap
  35672. */
  35673. diameterTop,
  35674. /**
  35675. * Defines the diameter of the cylinder's bottom cap
  35676. */
  35677. diameterBottom,
  35678. /**
  35679. * Defines the tessellation factor to apply to the cylinder
  35680. */
  35681. tessellation,
  35682. /**
  35683. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35684. */
  35685. subdivisions, canBeRegenerated, mesh,
  35686. /**
  35687. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35688. */
  35689. side) {
  35690. if (subdivisions === void 0) { subdivisions = 1; }
  35691. if (mesh === void 0) { mesh = null; }
  35692. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35693. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35694. _this.height = height;
  35695. _this.diameterTop = diameterTop;
  35696. _this.diameterBottom = diameterBottom;
  35697. _this.tessellation = tessellation;
  35698. _this.subdivisions = subdivisions;
  35699. _this.side = side;
  35700. return _this;
  35701. }
  35702. CylinderGeometry.prototype._regenerateVertexData = function () {
  35703. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35704. };
  35705. CylinderGeometry.prototype.copy = function (id) {
  35706. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35707. };
  35708. CylinderGeometry.prototype.serialize = function () {
  35709. var serializationObject = _super.prototype.serialize.call(this);
  35710. serializationObject.height = this.height;
  35711. serializationObject.diameterTop = this.diameterTop;
  35712. serializationObject.diameterBottom = this.diameterBottom;
  35713. serializationObject.tessellation = this.tessellation;
  35714. return serializationObject;
  35715. };
  35716. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35717. if (scene.getGeometryByID(parsedCylinder.id)) {
  35718. return null; // null since geometry could be something else than a cylinder...
  35719. }
  35720. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35721. if (BABYLON.Tags) {
  35722. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35723. }
  35724. scene.pushGeometry(cylinder, true);
  35725. return cylinder;
  35726. };
  35727. return CylinderGeometry;
  35728. }(_PrimitiveGeometry));
  35729. BABYLON.CylinderGeometry = CylinderGeometry;
  35730. /**
  35731. * Creates a new torus geometry
  35732. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35733. */
  35734. var TorusGeometry = /** @class */ (function (_super) {
  35735. __extends(TorusGeometry, _super);
  35736. /**
  35737. * Creates a new torus geometry
  35738. * @param id defines the unique ID of the geometry
  35739. * @param scene defines the hosting scene
  35740. * @param diameter defines the diameter of the torus
  35741. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35742. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35743. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35744. * @param mesh defines the hosting mesh (can be null)
  35745. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35746. */
  35747. function TorusGeometry(id, scene,
  35748. /**
  35749. * Defines the diameter of the torus
  35750. */
  35751. diameter,
  35752. /**
  35753. * Defines the thickness of the torus (ie. internal diameter)
  35754. */
  35755. thickness,
  35756. /**
  35757. * Defines the tesselation factor to apply to the torus
  35758. */
  35759. tessellation, canBeRegenerated, mesh,
  35760. /**
  35761. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35762. */
  35763. side) {
  35764. if (mesh === void 0) { mesh = null; }
  35765. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35766. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35767. _this.diameter = diameter;
  35768. _this.thickness = thickness;
  35769. _this.tessellation = tessellation;
  35770. _this.side = side;
  35771. return _this;
  35772. }
  35773. TorusGeometry.prototype._regenerateVertexData = function () {
  35774. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35775. };
  35776. TorusGeometry.prototype.copy = function (id) {
  35777. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35778. };
  35779. TorusGeometry.prototype.serialize = function () {
  35780. var serializationObject = _super.prototype.serialize.call(this);
  35781. serializationObject.diameter = this.diameter;
  35782. serializationObject.thickness = this.thickness;
  35783. serializationObject.tessellation = this.tessellation;
  35784. return serializationObject;
  35785. };
  35786. TorusGeometry.Parse = function (parsedTorus, scene) {
  35787. if (scene.getGeometryByID(parsedTorus.id)) {
  35788. return null; // null since geometry could be something else than a torus...
  35789. }
  35790. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35791. if (BABYLON.Tags) {
  35792. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35793. }
  35794. scene.pushGeometry(torus, true);
  35795. return torus;
  35796. };
  35797. return TorusGeometry;
  35798. }(_PrimitiveGeometry));
  35799. BABYLON.TorusGeometry = TorusGeometry;
  35800. /**
  35801. * Creates a new ground geometry
  35802. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35803. */
  35804. var GroundGeometry = /** @class */ (function (_super) {
  35805. __extends(GroundGeometry, _super);
  35806. /**
  35807. * Creates a new ground geometry
  35808. * @param id defines the unique ID of the geometry
  35809. * @param scene defines the hosting scene
  35810. * @param width defines the width of the ground
  35811. * @param height defines the height of the ground
  35812. * @param subdivisions defines the subdivisions to apply to the ground
  35813. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35814. * @param mesh defines the hosting mesh (can be null)
  35815. */
  35816. function GroundGeometry(id, scene,
  35817. /**
  35818. * Defines the width of the ground
  35819. */
  35820. width,
  35821. /**
  35822. * Defines the height of the ground
  35823. */
  35824. height,
  35825. /**
  35826. * Defines the subdivisions to apply to the ground
  35827. */
  35828. subdivisions, canBeRegenerated, mesh) {
  35829. if (mesh === void 0) { mesh = null; }
  35830. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35831. _this.width = width;
  35832. _this.height = height;
  35833. _this.subdivisions = subdivisions;
  35834. return _this;
  35835. }
  35836. GroundGeometry.prototype._regenerateVertexData = function () {
  35837. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35838. };
  35839. GroundGeometry.prototype.copy = function (id) {
  35840. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35841. };
  35842. GroundGeometry.prototype.serialize = function () {
  35843. var serializationObject = _super.prototype.serialize.call(this);
  35844. serializationObject.width = this.width;
  35845. serializationObject.height = this.height;
  35846. serializationObject.subdivisions = this.subdivisions;
  35847. return serializationObject;
  35848. };
  35849. GroundGeometry.Parse = function (parsedGround, scene) {
  35850. if (scene.getGeometryByID(parsedGround.id)) {
  35851. return null; // null since geometry could be something else than a ground...
  35852. }
  35853. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35854. if (BABYLON.Tags) {
  35855. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35856. }
  35857. scene.pushGeometry(ground, true);
  35858. return ground;
  35859. };
  35860. return GroundGeometry;
  35861. }(_PrimitiveGeometry));
  35862. BABYLON.GroundGeometry = GroundGeometry;
  35863. /**
  35864. * Creates a tiled ground geometry
  35865. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35866. */
  35867. var TiledGroundGeometry = /** @class */ (function (_super) {
  35868. __extends(TiledGroundGeometry, _super);
  35869. /**
  35870. * Creates a tiled ground geometry
  35871. * @param id defines the unique ID of the geometry
  35872. * @param scene defines the hosting scene
  35873. * @param xmin defines the minimum value on X axis
  35874. * @param zmin defines the minimum value on Z axis
  35875. * @param xmax defines the maximum value on X axis
  35876. * @param zmax defines the maximum value on Z axis
  35877. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35878. * @param precision defines the precision to use when computing the tiles
  35879. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35880. * @param mesh defines the hosting mesh (can be null)
  35881. */
  35882. function TiledGroundGeometry(id, scene,
  35883. /**
  35884. * Defines the minimum value on X axis
  35885. */
  35886. xmin,
  35887. /**
  35888. * Defines the minimum value on Z axis
  35889. */
  35890. zmin,
  35891. /**
  35892. * Defines the maximum value on X axis
  35893. */
  35894. xmax,
  35895. /**
  35896. * Defines the maximum value on Z axis
  35897. */
  35898. zmax,
  35899. /**
  35900. * Defines the subdivisions to apply to the ground
  35901. */
  35902. subdivisions,
  35903. /**
  35904. * Defines the precision to use when computing the tiles
  35905. */
  35906. precision, canBeRegenerated, mesh) {
  35907. if (mesh === void 0) { mesh = null; }
  35908. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35909. _this.xmin = xmin;
  35910. _this.zmin = zmin;
  35911. _this.xmax = xmax;
  35912. _this.zmax = zmax;
  35913. _this.subdivisions = subdivisions;
  35914. _this.precision = precision;
  35915. return _this;
  35916. }
  35917. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35918. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35919. };
  35920. TiledGroundGeometry.prototype.copy = function (id) {
  35921. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35922. };
  35923. return TiledGroundGeometry;
  35924. }(_PrimitiveGeometry));
  35925. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35926. /**
  35927. * Creates a plane geometry
  35928. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35929. */
  35930. var PlaneGeometry = /** @class */ (function (_super) {
  35931. __extends(PlaneGeometry, _super);
  35932. /**
  35933. * Creates a plane geometry
  35934. * @param id defines the unique ID of the geometry
  35935. * @param scene defines the hosting scene
  35936. * @param size defines the size of the plane (width === height)
  35937. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35938. * @param mesh defines the hosting mesh (can be null)
  35939. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35940. */
  35941. function PlaneGeometry(id, scene,
  35942. /**
  35943. * Defines the size of the plane (width === height)
  35944. */
  35945. size, canBeRegenerated, mesh,
  35946. /**
  35947. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35948. */
  35949. side) {
  35950. if (mesh === void 0) { mesh = null; }
  35951. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35952. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35953. _this.size = size;
  35954. _this.side = side;
  35955. return _this;
  35956. }
  35957. PlaneGeometry.prototype._regenerateVertexData = function () {
  35958. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35959. };
  35960. PlaneGeometry.prototype.copy = function (id) {
  35961. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35962. };
  35963. PlaneGeometry.prototype.serialize = function () {
  35964. var serializationObject = _super.prototype.serialize.call(this);
  35965. serializationObject.size = this.size;
  35966. return serializationObject;
  35967. };
  35968. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35969. if (scene.getGeometryByID(parsedPlane.id)) {
  35970. return null; // null since geometry could be something else than a ground...
  35971. }
  35972. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35973. if (BABYLON.Tags) {
  35974. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35975. }
  35976. scene.pushGeometry(plane, true);
  35977. return plane;
  35978. };
  35979. return PlaneGeometry;
  35980. }(_PrimitiveGeometry));
  35981. BABYLON.PlaneGeometry = PlaneGeometry;
  35982. /**
  35983. * Creates a torus knot geometry
  35984. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35985. */
  35986. var TorusKnotGeometry = /** @class */ (function (_super) {
  35987. __extends(TorusKnotGeometry, _super);
  35988. /**
  35989. * Creates a torus knot geometry
  35990. * @param id defines the unique ID of the geometry
  35991. * @param scene defines the hosting scene
  35992. * @param radius defines the radius of the torus knot
  35993. * @param tube defines the thickness of the torus knot tube
  35994. * @param radialSegments defines the number of radial segments
  35995. * @param tubularSegments defines the number of tubular segments
  35996. * @param p defines the first number of windings
  35997. * @param q defines the second number of windings
  35998. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35999. * @param mesh defines the hosting mesh (can be null)
  36000. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36001. */
  36002. function TorusKnotGeometry(id, scene,
  36003. /**
  36004. * Defines the radius of the torus knot
  36005. */
  36006. radius,
  36007. /**
  36008. * Defines the thickness of the torus knot tube
  36009. */
  36010. tube,
  36011. /**
  36012. * Defines the number of radial segments
  36013. */
  36014. radialSegments,
  36015. /**
  36016. * Defines the number of tubular segments
  36017. */
  36018. tubularSegments,
  36019. /**
  36020. * Defines the first number of windings
  36021. */
  36022. p,
  36023. /**
  36024. * Defines the second number of windings
  36025. */
  36026. q, canBeRegenerated, mesh,
  36027. /**
  36028. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36029. */
  36030. side) {
  36031. if (mesh === void 0) { mesh = null; }
  36032. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36033. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36034. _this.radius = radius;
  36035. _this.tube = tube;
  36036. _this.radialSegments = radialSegments;
  36037. _this.tubularSegments = tubularSegments;
  36038. _this.p = p;
  36039. _this.q = q;
  36040. _this.side = side;
  36041. return _this;
  36042. }
  36043. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36044. 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 });
  36045. };
  36046. TorusKnotGeometry.prototype.copy = function (id) {
  36047. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36048. };
  36049. TorusKnotGeometry.prototype.serialize = function () {
  36050. var serializationObject = _super.prototype.serialize.call(this);
  36051. serializationObject.radius = this.radius;
  36052. serializationObject.tube = this.tube;
  36053. serializationObject.radialSegments = this.radialSegments;
  36054. serializationObject.tubularSegments = this.tubularSegments;
  36055. serializationObject.p = this.p;
  36056. serializationObject.q = this.q;
  36057. return serializationObject;
  36058. };
  36059. ;
  36060. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36061. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36062. return null; // null since geometry could be something else than a ground...
  36063. }
  36064. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36065. if (BABYLON.Tags) {
  36066. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36067. }
  36068. scene.pushGeometry(torusKnot, true);
  36069. return torusKnot;
  36070. };
  36071. return TorusKnotGeometry;
  36072. }(_PrimitiveGeometry));
  36073. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36074. //}
  36075. })(BABYLON || (BABYLON = {}));
  36076. //# sourceMappingURL=babylon.geometry.js.map
  36077. var BABYLON;
  36078. (function (BABYLON) {
  36079. /**
  36080. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36081. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36082. */
  36083. var PostProcessManager = /** @class */ (function () {
  36084. /**
  36085. * Creates a new instance of @see PostProcess
  36086. * @param scene The scene that the post process is associated with.
  36087. */
  36088. function PostProcessManager(scene) {
  36089. this._vertexBuffers = {};
  36090. this._scene = scene;
  36091. }
  36092. PostProcessManager.prototype._prepareBuffers = function () {
  36093. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36094. return;
  36095. }
  36096. // VBO
  36097. var vertices = [];
  36098. vertices.push(1, 1);
  36099. vertices.push(-1, 1);
  36100. vertices.push(-1, -1);
  36101. vertices.push(1, -1);
  36102. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36103. this._buildIndexBuffer();
  36104. };
  36105. PostProcessManager.prototype._buildIndexBuffer = function () {
  36106. // Indices
  36107. var indices = [];
  36108. indices.push(0);
  36109. indices.push(1);
  36110. indices.push(2);
  36111. indices.push(0);
  36112. indices.push(2);
  36113. indices.push(3);
  36114. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36115. };
  36116. /**
  36117. * Rebuilds the vertex buffers of the manager.
  36118. */
  36119. PostProcessManager.prototype._rebuild = function () {
  36120. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36121. if (!vb) {
  36122. return;
  36123. }
  36124. vb._rebuild();
  36125. this._buildIndexBuffer();
  36126. };
  36127. // Methods
  36128. /**
  36129. * Prepares a frame to be run through a post process.
  36130. * @param sourceTexture The input texture to the post procesess. (default: null)
  36131. * @param postProcesses An array of post processes to be run. (default: null)
  36132. * @returns True if the post processes were able to be run.
  36133. */
  36134. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36135. if (sourceTexture === void 0) { sourceTexture = null; }
  36136. if (postProcesses === void 0) { postProcesses = null; }
  36137. var camera = this._scene.activeCamera;
  36138. if (!camera) {
  36139. return false;
  36140. }
  36141. var postProcesses = postProcesses || camera._postProcesses;
  36142. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36143. return false;
  36144. }
  36145. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36146. return true;
  36147. };
  36148. /**
  36149. * Manually render a set of post processes to a texture.
  36150. * @param postProcesses An array of post processes to be run.
  36151. * @param targetTexture The target texture to render to.
  36152. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36153. */
  36154. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36155. if (targetTexture === void 0) { targetTexture = null; }
  36156. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36157. var engine = this._scene.getEngine();
  36158. for (var index = 0; index < postProcesses.length; index++) {
  36159. if (index < postProcesses.length - 1) {
  36160. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36161. }
  36162. else {
  36163. if (targetTexture) {
  36164. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36165. }
  36166. else {
  36167. engine.restoreDefaultFramebuffer();
  36168. }
  36169. }
  36170. var pp = postProcesses[index];
  36171. var effect = pp.apply();
  36172. if (effect) {
  36173. pp.onBeforeRenderObservable.notifyObservers(effect);
  36174. // VBOs
  36175. this._prepareBuffers();
  36176. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36177. // Draw order
  36178. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36179. pp.onAfterRenderObservable.notifyObservers(effect);
  36180. }
  36181. }
  36182. // Restore depth buffer
  36183. engine.setDepthBuffer(true);
  36184. engine.setDepthWrite(true);
  36185. };
  36186. /**
  36187. * Finalize the result of the output of the postprocesses.
  36188. * @param doNotPresent If true the result will not be displayed to the screen.
  36189. * @param targetTexture The target texture to render to.
  36190. * @param faceIndex The index of the face to bind the target texture to.
  36191. * @param postProcesses The array of post processes to render.
  36192. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36193. */
  36194. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36195. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36196. var camera = this._scene.activeCamera;
  36197. if (!camera) {
  36198. return;
  36199. }
  36200. postProcesses = postProcesses || camera._postProcesses;
  36201. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36202. return;
  36203. }
  36204. var engine = this._scene.getEngine();
  36205. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36206. if (index < len - 1) {
  36207. postProcesses[index + 1].activate(camera, targetTexture);
  36208. }
  36209. else {
  36210. if (targetTexture) {
  36211. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36212. }
  36213. else {
  36214. engine.restoreDefaultFramebuffer();
  36215. }
  36216. }
  36217. if (doNotPresent) {
  36218. break;
  36219. }
  36220. var pp = postProcesses[index];
  36221. var effect = pp.apply();
  36222. if (effect) {
  36223. pp.onBeforeRenderObservable.notifyObservers(effect);
  36224. // VBOs
  36225. this._prepareBuffers();
  36226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36227. // Draw order
  36228. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36229. pp.onAfterRenderObservable.notifyObservers(effect);
  36230. }
  36231. }
  36232. // Restore states
  36233. engine.setDepthBuffer(true);
  36234. engine.setDepthWrite(true);
  36235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36236. };
  36237. /**
  36238. * Disposes of the post process manager.
  36239. */
  36240. PostProcessManager.prototype.dispose = function () {
  36241. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36242. if (buffer) {
  36243. buffer.dispose();
  36244. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36245. }
  36246. if (this._indexBuffer) {
  36247. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36248. this._indexBuffer = null;
  36249. }
  36250. };
  36251. return PostProcessManager;
  36252. }());
  36253. BABYLON.PostProcessManager = PostProcessManager;
  36254. })(BABYLON || (BABYLON = {}));
  36255. //# sourceMappingURL=babylon.postProcessManager.js.map
  36256. var BABYLON;
  36257. (function (BABYLON) {
  36258. /**
  36259. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36260. */
  36261. var PerformanceMonitor = /** @class */ (function () {
  36262. /**
  36263. * constructor
  36264. * @param frameSampleSize The number of samples required to saturate the sliding window
  36265. */
  36266. function PerformanceMonitor(frameSampleSize) {
  36267. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36268. this._enabled = true;
  36269. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36270. }
  36271. /**
  36272. * Samples current frame
  36273. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36274. */
  36275. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36276. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36277. if (!this._enabled)
  36278. return;
  36279. if (this._lastFrameTimeMs != null) {
  36280. var dt = timeMs - this._lastFrameTimeMs;
  36281. this._rollingFrameTime.add(dt);
  36282. }
  36283. this._lastFrameTimeMs = timeMs;
  36284. };
  36285. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36286. /**
  36287. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36288. * @return Average frame time in milliseconds
  36289. */
  36290. get: function () {
  36291. return this._rollingFrameTime.average;
  36292. },
  36293. enumerable: true,
  36294. configurable: true
  36295. });
  36296. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36297. /**
  36298. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36299. * @return Frame time variance in milliseconds squared
  36300. */
  36301. get: function () {
  36302. return this._rollingFrameTime.variance;
  36303. },
  36304. enumerable: true,
  36305. configurable: true
  36306. });
  36307. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36308. /**
  36309. * Returns the frame time of the most recent frame
  36310. * @return Frame time in milliseconds
  36311. */
  36312. get: function () {
  36313. return this._rollingFrameTime.history(0);
  36314. },
  36315. enumerable: true,
  36316. configurable: true
  36317. });
  36318. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36319. /**
  36320. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36321. * @return Framerate in frames per second
  36322. */
  36323. get: function () {
  36324. return 1000.0 / this._rollingFrameTime.average;
  36325. },
  36326. enumerable: true,
  36327. configurable: true
  36328. });
  36329. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36330. /**
  36331. * Returns the average framerate in frames per second using the most recent frame time
  36332. * @return Framerate in frames per second
  36333. */
  36334. get: function () {
  36335. var history = this._rollingFrameTime.history(0);
  36336. if (history === 0) {
  36337. return 0;
  36338. }
  36339. return 1000.0 / history;
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36345. /**
  36346. * Returns true if enough samples have been taken to completely fill the sliding window
  36347. * @return true if saturated
  36348. */
  36349. get: function () {
  36350. return this._rollingFrameTime.isSaturated();
  36351. },
  36352. enumerable: true,
  36353. configurable: true
  36354. });
  36355. /**
  36356. * Enables contributions to the sliding window sample set
  36357. */
  36358. PerformanceMonitor.prototype.enable = function () {
  36359. this._enabled = true;
  36360. };
  36361. /**
  36362. * Disables contributions to the sliding window sample set
  36363. * Samples will not be interpolated over the disabled period
  36364. */
  36365. PerformanceMonitor.prototype.disable = function () {
  36366. this._enabled = false;
  36367. //clear last sample to avoid interpolating over the disabled period when next enabled
  36368. this._lastFrameTimeMs = null;
  36369. };
  36370. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36371. /**
  36372. * Returns true if sampling is enabled
  36373. * @return true if enabled
  36374. */
  36375. get: function () {
  36376. return this._enabled;
  36377. },
  36378. enumerable: true,
  36379. configurable: true
  36380. });
  36381. /**
  36382. * Resets performance monitor
  36383. */
  36384. PerformanceMonitor.prototype.reset = function () {
  36385. //clear last sample to avoid interpolating over the disabled period when next enabled
  36386. this._lastFrameTimeMs = null;
  36387. //wipe record
  36388. this._rollingFrameTime.reset();
  36389. };
  36390. return PerformanceMonitor;
  36391. }());
  36392. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36393. /**
  36394. * RollingAverage
  36395. *
  36396. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36397. */
  36398. var RollingAverage = /** @class */ (function () {
  36399. /**
  36400. * constructor
  36401. * @param length The number of samples required to saturate the sliding window
  36402. */
  36403. function RollingAverage(length) {
  36404. this._samples = new Array(length);
  36405. this.reset();
  36406. }
  36407. /**
  36408. * Adds a sample to the sample set
  36409. * @param v The sample value
  36410. */
  36411. RollingAverage.prototype.add = function (v) {
  36412. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36413. var delta;
  36414. //we need to check if we've already wrapped round
  36415. if (this.isSaturated()) {
  36416. //remove bottom of stack from mean
  36417. var bottomValue = this._samples[this._pos];
  36418. delta = bottomValue - this.average;
  36419. this.average -= delta / (this._sampleCount - 1);
  36420. this._m2 -= delta * (bottomValue - this.average);
  36421. }
  36422. else {
  36423. this._sampleCount++;
  36424. }
  36425. //add new value to mean
  36426. delta = v - this.average;
  36427. this.average += delta / (this._sampleCount);
  36428. this._m2 += delta * (v - this.average);
  36429. //set the new variance
  36430. this.variance = this._m2 / (this._sampleCount - 1);
  36431. this._samples[this._pos] = v;
  36432. this._pos++;
  36433. this._pos %= this._samples.length; //positive wrap around
  36434. };
  36435. /**
  36436. * Returns previously added values or null if outside of history or outside the sliding window domain
  36437. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36438. * @return Value previously recorded with add() or null if outside of range
  36439. */
  36440. RollingAverage.prototype.history = function (i) {
  36441. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36442. return 0;
  36443. }
  36444. var i0 = this._wrapPosition(this._pos - 1.0);
  36445. return this._samples[this._wrapPosition(i0 - i)];
  36446. };
  36447. /**
  36448. * Returns true if enough samples have been taken to completely fill the sliding window
  36449. * @return true if sample-set saturated
  36450. */
  36451. RollingAverage.prototype.isSaturated = function () {
  36452. return this._sampleCount >= this._samples.length;
  36453. };
  36454. /**
  36455. * Resets the rolling average (equivalent to 0 samples taken so far)
  36456. */
  36457. RollingAverage.prototype.reset = function () {
  36458. this.average = 0;
  36459. this.variance = 0;
  36460. this._sampleCount = 0;
  36461. this._pos = 0;
  36462. this._m2 = 0;
  36463. };
  36464. /**
  36465. * Wraps a value around the sample range boundaries
  36466. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36467. * @return Wrapped position in sample range
  36468. */
  36469. RollingAverage.prototype._wrapPosition = function (i) {
  36470. var max = this._samples.length;
  36471. return ((i % max) + max) % max;
  36472. };
  36473. return RollingAverage;
  36474. }());
  36475. BABYLON.RollingAverage = RollingAverage;
  36476. })(BABYLON || (BABYLON = {}));
  36477. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36478. var BABYLON;
  36479. (function (BABYLON) {
  36480. /**
  36481. * This groups together the common properties used for image processing either in direct forward pass
  36482. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36483. * or not.
  36484. */
  36485. var ImageProcessingConfiguration = /** @class */ (function () {
  36486. function ImageProcessingConfiguration() {
  36487. /**
  36488. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36489. */
  36490. this.colorCurves = new BABYLON.ColorCurves();
  36491. this._colorCurvesEnabled = false;
  36492. this._colorGradingEnabled = false;
  36493. this._colorGradingWithGreenDepth = true;
  36494. this._colorGradingBGR = true;
  36495. this._exposure = 1.0;
  36496. this._toneMappingEnabled = false;
  36497. this._contrast = 1.0;
  36498. /**
  36499. * Vignette stretch size.
  36500. */
  36501. this.vignetteStretch = 0;
  36502. /**
  36503. * Vignette centre X Offset.
  36504. */
  36505. this.vignetteCentreX = 0;
  36506. /**
  36507. * Vignette centre Y Offset.
  36508. */
  36509. this.vignetteCentreY = 0;
  36510. /**
  36511. * Vignette weight or intensity of the vignette effect.
  36512. */
  36513. this.vignetteWeight = 1.5;
  36514. /**
  36515. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36516. * if vignetteEnabled is set to true.
  36517. */
  36518. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36519. /**
  36520. * Camera field of view used by the Vignette effect.
  36521. */
  36522. this.vignetteCameraFov = 0.5;
  36523. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36524. this._vignetteEnabled = false;
  36525. this._applyByPostProcess = false;
  36526. this._isEnabled = true;
  36527. /**
  36528. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36529. * @type {BABYLON.Observable}
  36530. */
  36531. this.onUpdateParameters = new BABYLON.Observable();
  36532. }
  36533. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36534. /**
  36535. * Gets wether the color curves effect is enabled.
  36536. */
  36537. get: function () {
  36538. return this._colorCurvesEnabled;
  36539. },
  36540. /**
  36541. * Sets wether the color curves effect is enabled.
  36542. */
  36543. set: function (value) {
  36544. if (this._colorCurvesEnabled === value) {
  36545. return;
  36546. }
  36547. this._colorCurvesEnabled = value;
  36548. this._updateParameters();
  36549. },
  36550. enumerable: true,
  36551. configurable: true
  36552. });
  36553. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36554. /**
  36555. * Gets wether the color grading effect is enabled.
  36556. */
  36557. get: function () {
  36558. return this._colorGradingEnabled;
  36559. },
  36560. /**
  36561. * Sets wether the color grading effect is enabled.
  36562. */
  36563. set: function (value) {
  36564. if (this._colorGradingEnabled === value) {
  36565. return;
  36566. }
  36567. this._colorGradingEnabled = value;
  36568. this._updateParameters();
  36569. },
  36570. enumerable: true,
  36571. configurable: true
  36572. });
  36573. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36574. /**
  36575. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36576. */
  36577. get: function () {
  36578. return this._colorGradingWithGreenDepth;
  36579. },
  36580. /**
  36581. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36582. */
  36583. set: function (value) {
  36584. if (this._colorGradingWithGreenDepth === value) {
  36585. return;
  36586. }
  36587. this._colorGradingWithGreenDepth = value;
  36588. this._updateParameters();
  36589. },
  36590. enumerable: true,
  36591. configurable: true
  36592. });
  36593. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36594. /**
  36595. * Gets wether the color grading texture contains BGR values.
  36596. */
  36597. get: function () {
  36598. return this._colorGradingBGR;
  36599. },
  36600. /**
  36601. * Sets wether the color grading texture contains BGR values.
  36602. */
  36603. set: function (value) {
  36604. if (this._colorGradingBGR === value) {
  36605. return;
  36606. }
  36607. this._colorGradingBGR = value;
  36608. this._updateParameters();
  36609. },
  36610. enumerable: true,
  36611. configurable: true
  36612. });
  36613. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36614. /**
  36615. * Gets the Exposure used in the effect.
  36616. */
  36617. get: function () {
  36618. return this._exposure;
  36619. },
  36620. /**
  36621. * Sets the Exposure used in the effect.
  36622. */
  36623. set: function (value) {
  36624. if (this._exposure === value) {
  36625. return;
  36626. }
  36627. this._exposure = value;
  36628. this._updateParameters();
  36629. },
  36630. enumerable: true,
  36631. configurable: true
  36632. });
  36633. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36634. /**
  36635. * Gets wether the tone mapping effect is enabled.
  36636. */
  36637. get: function () {
  36638. return this._toneMappingEnabled;
  36639. },
  36640. /**
  36641. * Sets wether the tone mapping effect is enabled.
  36642. */
  36643. set: function (value) {
  36644. if (this._toneMappingEnabled === value) {
  36645. return;
  36646. }
  36647. this._toneMappingEnabled = value;
  36648. this._updateParameters();
  36649. },
  36650. enumerable: true,
  36651. configurable: true
  36652. });
  36653. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36654. /**
  36655. * Gets the contrast used in the effect.
  36656. */
  36657. get: function () {
  36658. return this._contrast;
  36659. },
  36660. /**
  36661. * Sets the contrast used in the effect.
  36662. */
  36663. set: function (value) {
  36664. if (this._contrast === value) {
  36665. return;
  36666. }
  36667. this._contrast = value;
  36668. this._updateParameters();
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36674. /**
  36675. * Gets the vignette blend mode allowing different kind of effect.
  36676. */
  36677. get: function () {
  36678. return this._vignetteBlendMode;
  36679. },
  36680. /**
  36681. * Sets the vignette blend mode allowing different kind of effect.
  36682. */
  36683. set: function (value) {
  36684. if (this._vignetteBlendMode === value) {
  36685. return;
  36686. }
  36687. this._vignetteBlendMode = value;
  36688. this._updateParameters();
  36689. },
  36690. enumerable: true,
  36691. configurable: true
  36692. });
  36693. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36694. /**
  36695. * Gets wether the vignette effect is enabled.
  36696. */
  36697. get: function () {
  36698. return this._vignetteEnabled;
  36699. },
  36700. /**
  36701. * Sets wether the vignette effect is enabled.
  36702. */
  36703. set: function (value) {
  36704. if (this._vignetteEnabled === value) {
  36705. return;
  36706. }
  36707. this._vignetteEnabled = value;
  36708. this._updateParameters();
  36709. },
  36710. enumerable: true,
  36711. configurable: true
  36712. });
  36713. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36714. /**
  36715. * Gets wether the image processing is applied through a post process or not.
  36716. */
  36717. get: function () {
  36718. return this._applyByPostProcess;
  36719. },
  36720. /**
  36721. * Sets wether the image processing is applied through a post process or not.
  36722. */
  36723. set: function (value) {
  36724. if (this._applyByPostProcess === value) {
  36725. return;
  36726. }
  36727. this._applyByPostProcess = value;
  36728. this._updateParameters();
  36729. },
  36730. enumerable: true,
  36731. configurable: true
  36732. });
  36733. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36734. /**
  36735. * Gets wether the image processing is enabled or not.
  36736. */
  36737. get: function () {
  36738. return this._isEnabled;
  36739. },
  36740. /**
  36741. * Sets wether the image processing is enabled or not.
  36742. */
  36743. set: function (value) {
  36744. if (this._isEnabled === value) {
  36745. return;
  36746. }
  36747. this._isEnabled = value;
  36748. this._updateParameters();
  36749. },
  36750. enumerable: true,
  36751. configurable: true
  36752. });
  36753. /**
  36754. * Method called each time the image processing information changes requires to recompile the effect.
  36755. */
  36756. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36757. this.onUpdateParameters.notifyObservers(this);
  36758. };
  36759. ImageProcessingConfiguration.prototype.getClassName = function () {
  36760. return "ImageProcessingConfiguration";
  36761. };
  36762. /**
  36763. * Prepare the list of uniforms associated with the Image Processing effects.
  36764. * @param uniformsList The list of uniforms used in the effect
  36765. * @param defines the list of defines currently in use
  36766. */
  36767. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36768. if (defines.EXPOSURE) {
  36769. uniforms.push("exposureLinear");
  36770. }
  36771. if (defines.CONTRAST) {
  36772. uniforms.push("contrast");
  36773. }
  36774. if (defines.COLORGRADING) {
  36775. uniforms.push("colorTransformSettings");
  36776. }
  36777. if (defines.VIGNETTE) {
  36778. uniforms.push("vInverseScreenSize");
  36779. uniforms.push("vignetteSettings1");
  36780. uniforms.push("vignetteSettings2");
  36781. }
  36782. if (defines.COLORCURVES) {
  36783. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36784. }
  36785. };
  36786. /**
  36787. * Prepare the list of samplers associated with the Image Processing effects.
  36788. * @param uniformsList The list of uniforms used in the effect
  36789. * @param defines the list of defines currently in use
  36790. */
  36791. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36792. if (defines.COLORGRADING) {
  36793. samplersList.push("txColorTransform");
  36794. }
  36795. };
  36796. /**
  36797. * Prepare the list of defines associated to the shader.
  36798. * @param defines the list of defines to complete
  36799. */
  36800. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36801. if (forPostProcess === void 0) { forPostProcess = false; }
  36802. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36803. defines.VIGNETTE = false;
  36804. defines.TONEMAPPING = false;
  36805. defines.CONTRAST = false;
  36806. defines.EXPOSURE = false;
  36807. defines.COLORCURVES = false;
  36808. defines.COLORGRADING = false;
  36809. defines.COLORGRADING3D = false;
  36810. defines.IMAGEPROCESSING = false;
  36811. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36812. return;
  36813. }
  36814. defines.VIGNETTE = this.vignetteEnabled;
  36815. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36816. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36817. defines.TONEMAPPING = this.toneMappingEnabled;
  36818. defines.CONTRAST = (this.contrast !== 1.0);
  36819. defines.EXPOSURE = (this.exposure !== 1.0);
  36820. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36821. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36822. if (defines.COLORGRADING) {
  36823. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36824. }
  36825. else {
  36826. defines.COLORGRADING3D = false;
  36827. }
  36828. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36829. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36830. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36831. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36832. };
  36833. /**
  36834. * Returns true if all the image processing information are ready.
  36835. */
  36836. ImageProcessingConfiguration.prototype.isReady = function () {
  36837. // Color Grading texure can not be none blocking.
  36838. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36839. };
  36840. /**
  36841. * Binds the image processing to the shader.
  36842. * @param effect The effect to bind to
  36843. */
  36844. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36845. if (aspectRatio === void 0) { aspectRatio = 1; }
  36846. // Color Curves
  36847. if (this._colorCurvesEnabled && this.colorCurves) {
  36848. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36849. }
  36850. // Vignette
  36851. if (this._vignetteEnabled) {
  36852. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36853. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36854. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36855. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36856. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36857. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36858. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36859. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36860. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36861. var vignettePower = -2.0 * this.vignetteWeight;
  36862. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36863. }
  36864. // Exposure
  36865. effect.setFloat("exposureLinear", this.exposure);
  36866. // Contrast
  36867. effect.setFloat("contrast", this.contrast);
  36868. // Color transform settings
  36869. if (this.colorGradingTexture) {
  36870. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36871. var textureSize = this.colorGradingTexture.getSize().height;
  36872. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36873. 0.5 / textureSize, // textureOffset
  36874. textureSize, // textureSize
  36875. this.colorGradingTexture.level // weight
  36876. );
  36877. }
  36878. };
  36879. /**
  36880. * Clones the current image processing instance.
  36881. * @return The cloned image processing
  36882. */
  36883. ImageProcessingConfiguration.prototype.clone = function () {
  36884. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36885. };
  36886. /**
  36887. * Serializes the current image processing instance to a json representation.
  36888. * @return a JSON representation
  36889. */
  36890. ImageProcessingConfiguration.prototype.serialize = function () {
  36891. return BABYLON.SerializationHelper.Serialize(this);
  36892. };
  36893. /**
  36894. * Parses the image processing from a json representation.
  36895. * @param source the JSON source to parse
  36896. * @return The parsed image processing
  36897. */
  36898. ImageProcessingConfiguration.Parse = function (source) {
  36899. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36900. };
  36901. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36902. /**
  36903. * Used to apply the vignette as a mix with the pixel color.
  36904. */
  36905. get: function () {
  36906. return this._VIGNETTEMODE_MULTIPLY;
  36907. },
  36908. enumerable: true,
  36909. configurable: true
  36910. });
  36911. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36912. /**
  36913. * Used to apply the vignette as a replacement of the pixel color.
  36914. */
  36915. get: function () {
  36916. return this._VIGNETTEMODE_OPAQUE;
  36917. },
  36918. enumerable: true,
  36919. configurable: true
  36920. });
  36921. // Static constants associated to the image processing.
  36922. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36923. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36924. __decorate([
  36925. BABYLON.serializeAsColorCurves()
  36926. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36927. __decorate([
  36928. BABYLON.serialize()
  36929. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36930. __decorate([
  36931. BABYLON.serializeAsTexture()
  36932. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36933. __decorate([
  36934. BABYLON.serialize()
  36935. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36936. __decorate([
  36937. BABYLON.serialize()
  36938. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36939. __decorate([
  36940. BABYLON.serialize()
  36941. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36942. __decorate([
  36943. BABYLON.serialize()
  36944. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36945. __decorate([
  36946. BABYLON.serialize()
  36947. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36948. __decorate([
  36949. BABYLON.serialize()
  36950. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36951. __decorate([
  36952. BABYLON.serialize()
  36953. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36954. __decorate([
  36955. BABYLON.serialize()
  36956. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36957. __decorate([
  36958. BABYLON.serialize()
  36959. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36960. __decorate([
  36961. BABYLON.serialize()
  36962. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36963. __decorate([
  36964. BABYLON.serializeAsColor4()
  36965. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36966. __decorate([
  36967. BABYLON.serialize()
  36968. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36969. __decorate([
  36970. BABYLON.serialize()
  36971. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36972. __decorate([
  36973. BABYLON.serialize()
  36974. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36975. __decorate([
  36976. BABYLON.serialize()
  36977. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36978. __decorate([
  36979. BABYLON.serialize()
  36980. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36981. return ImageProcessingConfiguration;
  36982. }());
  36983. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36984. })(BABYLON || (BABYLON = {}));
  36985. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36986. var BABYLON;
  36987. (function (BABYLON) {
  36988. /**
  36989. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36990. * It can help converting any input color in a desired output one. This can then be used to create effects
  36991. * from sepia, black and white to sixties or futuristic rendering...
  36992. *
  36993. * The only supported format is currently 3dl.
  36994. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36995. */
  36996. var ColorGradingTexture = /** @class */ (function (_super) {
  36997. __extends(ColorGradingTexture, _super);
  36998. /**
  36999. * Instantiates a ColorGradingTexture from the following parameters.
  37000. *
  37001. * @param url The location of the color gradind data (currently only supporting 3dl)
  37002. * @param scene The scene the texture will be used in
  37003. */
  37004. function ColorGradingTexture(url, scene) {
  37005. var _this = _super.call(this, scene) || this;
  37006. if (!url) {
  37007. return _this;
  37008. }
  37009. _this._engine = scene.getEngine();
  37010. _this._textureMatrix = BABYLON.Matrix.Identity();
  37011. _this.name = url;
  37012. _this.url = url;
  37013. _this.hasAlpha = false;
  37014. _this.isCube = false;
  37015. _this.is3D = _this._engine.webGLVersion > 1;
  37016. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37017. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37018. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37019. _this.anisotropicFilteringLevel = 1;
  37020. _this._texture = _this._getFromCache(url, true);
  37021. if (!_this._texture) {
  37022. if (!scene.useDelayedTextureLoading) {
  37023. _this.loadTexture();
  37024. }
  37025. else {
  37026. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37027. }
  37028. }
  37029. return _this;
  37030. }
  37031. /**
  37032. * Returns the texture matrix used in most of the material.
  37033. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37034. */
  37035. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37036. return this._textureMatrix;
  37037. };
  37038. /**
  37039. * Occurs when the file being loaded is a .3dl LUT file.
  37040. */
  37041. ColorGradingTexture.prototype.load3dlTexture = function () {
  37042. var engine = this._engine;
  37043. var texture;
  37044. if (engine.webGLVersion === 1) {
  37045. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37046. }
  37047. else {
  37048. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37049. }
  37050. this._texture = texture;
  37051. var callback = function (text) {
  37052. if (typeof text !== "string") {
  37053. return;
  37054. }
  37055. var data = null;
  37056. var tempData = null;
  37057. var line;
  37058. var lines = text.split('\n');
  37059. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37060. var maxColor = 0;
  37061. for (var i = 0; i < lines.length; i++) {
  37062. line = lines[i];
  37063. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37064. continue;
  37065. if (line.indexOf('#') === 0)
  37066. continue;
  37067. var words = line.split(" ");
  37068. if (size === 0) {
  37069. // Number of space + one
  37070. size = words.length;
  37071. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37072. tempData = new Float32Array(size * size * size * 4);
  37073. continue;
  37074. }
  37075. if (size != 0) {
  37076. var r = Math.max(parseInt(words[0]), 0);
  37077. var g = Math.max(parseInt(words[1]), 0);
  37078. var b = Math.max(parseInt(words[2]), 0);
  37079. maxColor = Math.max(r, maxColor);
  37080. maxColor = Math.max(g, maxColor);
  37081. maxColor = Math.max(b, maxColor);
  37082. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37083. if (tempData) {
  37084. tempData[pixelStorageIndex + 0] = r;
  37085. tempData[pixelStorageIndex + 1] = g;
  37086. tempData[pixelStorageIndex + 2] = b;
  37087. }
  37088. pixelIndexSlice++;
  37089. if (pixelIndexSlice % size == 0) {
  37090. pixelIndexH++;
  37091. pixelIndexSlice = 0;
  37092. if (pixelIndexH % size == 0) {
  37093. pixelIndexW++;
  37094. pixelIndexH = 0;
  37095. }
  37096. }
  37097. }
  37098. }
  37099. if (tempData && data) {
  37100. for (var i = 0; i < tempData.length; i++) {
  37101. if (i > 0 && (i + 1) % 4 === 0) {
  37102. data[i] = 255;
  37103. }
  37104. else {
  37105. var value = tempData[i];
  37106. data[i] = (value / maxColor * 255);
  37107. }
  37108. }
  37109. }
  37110. if (texture.is3D) {
  37111. texture.updateSize(size, size, size);
  37112. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37113. }
  37114. else {
  37115. texture.updateSize(size * size, size);
  37116. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37117. }
  37118. };
  37119. var scene = this.getScene();
  37120. if (scene) {
  37121. scene._loadFile(this.url, callback);
  37122. }
  37123. else {
  37124. this._engine._loadFile(this.url, callback);
  37125. }
  37126. return this._texture;
  37127. };
  37128. /**
  37129. * Starts the loading process of the texture.
  37130. */
  37131. ColorGradingTexture.prototype.loadTexture = function () {
  37132. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37133. this.load3dlTexture();
  37134. }
  37135. };
  37136. /**
  37137. * Clones the color gradind texture.
  37138. */
  37139. ColorGradingTexture.prototype.clone = function () {
  37140. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37141. // Base texture
  37142. newTexture.level = this.level;
  37143. return newTexture;
  37144. };
  37145. /**
  37146. * Called during delayed load for textures.
  37147. */
  37148. ColorGradingTexture.prototype.delayLoad = function () {
  37149. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37150. return;
  37151. }
  37152. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37153. this._texture = this._getFromCache(this.url, true);
  37154. if (!this._texture) {
  37155. this.loadTexture();
  37156. }
  37157. };
  37158. /**
  37159. * Parses a color grading texture serialized by Babylon.
  37160. * @param parsedTexture The texture information being parsedTexture
  37161. * @param scene The scene to load the texture in
  37162. * @param rootUrl The root url of the data assets to load
  37163. * @return A color gradind texture
  37164. */
  37165. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37166. var texture = null;
  37167. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37168. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37169. texture.name = parsedTexture.name;
  37170. texture.level = parsedTexture.level;
  37171. }
  37172. return texture;
  37173. };
  37174. /**
  37175. * Serializes the LUT texture to json format.
  37176. */
  37177. ColorGradingTexture.prototype.serialize = function () {
  37178. if (!this.name) {
  37179. return null;
  37180. }
  37181. var serializationObject = {};
  37182. serializationObject.name = this.name;
  37183. serializationObject.level = this.level;
  37184. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37185. return serializationObject;
  37186. };
  37187. /**
  37188. * Empty line regex stored for GC.
  37189. */
  37190. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37191. return ColorGradingTexture;
  37192. }(BABYLON.BaseTexture));
  37193. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37194. })(BABYLON || (BABYLON = {}));
  37195. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37196. var BABYLON;
  37197. (function (BABYLON) {
  37198. /**
  37199. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37200. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37201. * 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;
  37202. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37203. */
  37204. var ColorCurves = /** @class */ (function () {
  37205. function ColorCurves() {
  37206. this._dirty = true;
  37207. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37208. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37209. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37210. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37211. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37212. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37213. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37214. this._globalHue = 30;
  37215. this._globalDensity = 0;
  37216. this._globalSaturation = 0;
  37217. this._globalExposure = 0;
  37218. this._highlightsHue = 30;
  37219. this._highlightsDensity = 0;
  37220. this._highlightsSaturation = 0;
  37221. this._highlightsExposure = 0;
  37222. this._midtonesHue = 30;
  37223. this._midtonesDensity = 0;
  37224. this._midtonesSaturation = 0;
  37225. this._midtonesExposure = 0;
  37226. this._shadowsHue = 30;
  37227. this._shadowsDensity = 0;
  37228. this._shadowsSaturation = 0;
  37229. this._shadowsExposure = 0;
  37230. }
  37231. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37232. /**
  37233. * Gets the global Hue value.
  37234. * 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).
  37235. */
  37236. get: function () {
  37237. return this._globalHue;
  37238. },
  37239. /**
  37240. * Sets the global Hue value.
  37241. * 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).
  37242. */
  37243. set: function (value) {
  37244. this._globalHue = value;
  37245. this._dirty = true;
  37246. },
  37247. enumerable: true,
  37248. configurable: true
  37249. });
  37250. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37251. /**
  37252. * Gets the global Density value.
  37253. * 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.
  37254. * Values less than zero provide a filter of opposite hue.
  37255. */
  37256. get: function () {
  37257. return this._globalDensity;
  37258. },
  37259. /**
  37260. * Sets the global Density value.
  37261. * 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.
  37262. * Values less than zero provide a filter of opposite hue.
  37263. */
  37264. set: function (value) {
  37265. this._globalDensity = value;
  37266. this._dirty = true;
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37272. /**
  37273. * Gets the global Saturation value.
  37274. * 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.
  37275. */
  37276. get: function () {
  37277. return this._globalSaturation;
  37278. },
  37279. /**
  37280. * Sets the global Saturation value.
  37281. * 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.
  37282. */
  37283. set: function (value) {
  37284. this._globalSaturation = value;
  37285. this._dirty = true;
  37286. },
  37287. enumerable: true,
  37288. configurable: true
  37289. });
  37290. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37291. /**
  37292. * Gets the highlights Hue value.
  37293. * 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).
  37294. */
  37295. get: function () {
  37296. return this._highlightsHue;
  37297. },
  37298. /**
  37299. * Sets the highlights Hue value.
  37300. * 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).
  37301. */
  37302. set: function (value) {
  37303. this._highlightsHue = value;
  37304. this._dirty = true;
  37305. },
  37306. enumerable: true,
  37307. configurable: true
  37308. });
  37309. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37310. /**
  37311. * Gets the highlights Density value.
  37312. * 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.
  37313. * Values less than zero provide a filter of opposite hue.
  37314. */
  37315. get: function () {
  37316. return this._highlightsDensity;
  37317. },
  37318. /**
  37319. * Sets the highlights Density value.
  37320. * 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.
  37321. * Values less than zero provide a filter of opposite hue.
  37322. */
  37323. set: function (value) {
  37324. this._highlightsDensity = value;
  37325. this._dirty = true;
  37326. },
  37327. enumerable: true,
  37328. configurable: true
  37329. });
  37330. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37331. /**
  37332. * Gets the highlights Saturation value.
  37333. * 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.
  37334. */
  37335. get: function () {
  37336. return this._highlightsSaturation;
  37337. },
  37338. /**
  37339. * Sets the highlights Saturation value.
  37340. * 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.
  37341. */
  37342. set: function (value) {
  37343. this._highlightsSaturation = value;
  37344. this._dirty = true;
  37345. },
  37346. enumerable: true,
  37347. configurable: true
  37348. });
  37349. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37350. /**
  37351. * Gets the highlights Exposure value.
  37352. * 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.
  37353. */
  37354. get: function () {
  37355. return this._highlightsExposure;
  37356. },
  37357. /**
  37358. * Sets the highlights Exposure value.
  37359. * 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.
  37360. */
  37361. set: function (value) {
  37362. this._highlightsExposure = value;
  37363. this._dirty = true;
  37364. },
  37365. enumerable: true,
  37366. configurable: true
  37367. });
  37368. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37369. /**
  37370. * Gets the midtones Hue value.
  37371. * 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).
  37372. */
  37373. get: function () {
  37374. return this._midtonesHue;
  37375. },
  37376. /**
  37377. * Sets the midtones Hue value.
  37378. * 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).
  37379. */
  37380. set: function (value) {
  37381. this._midtonesHue = value;
  37382. this._dirty = true;
  37383. },
  37384. enumerable: true,
  37385. configurable: true
  37386. });
  37387. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37388. /**
  37389. * Gets the midtones Density value.
  37390. * 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.
  37391. * Values less than zero provide a filter of opposite hue.
  37392. */
  37393. get: function () {
  37394. return this._midtonesDensity;
  37395. },
  37396. /**
  37397. * Sets the midtones Density value.
  37398. * 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.
  37399. * Values less than zero provide a filter of opposite hue.
  37400. */
  37401. set: function (value) {
  37402. this._midtonesDensity = value;
  37403. this._dirty = true;
  37404. },
  37405. enumerable: true,
  37406. configurable: true
  37407. });
  37408. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37409. /**
  37410. * Gets the midtones Saturation value.
  37411. * 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.
  37412. */
  37413. get: function () {
  37414. return this._midtonesSaturation;
  37415. },
  37416. /**
  37417. * Sets the midtones Saturation value.
  37418. * 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.
  37419. */
  37420. set: function (value) {
  37421. this._midtonesSaturation = value;
  37422. this._dirty = true;
  37423. },
  37424. enumerable: true,
  37425. configurable: true
  37426. });
  37427. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37428. /**
  37429. * Gets the midtones Exposure value.
  37430. * 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.
  37431. */
  37432. get: function () {
  37433. return this._midtonesExposure;
  37434. },
  37435. /**
  37436. * Sets the midtones Exposure value.
  37437. * 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.
  37438. */
  37439. set: function (value) {
  37440. this._midtonesExposure = value;
  37441. this._dirty = true;
  37442. },
  37443. enumerable: true,
  37444. configurable: true
  37445. });
  37446. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37447. /**
  37448. * Gets the shadows Hue value.
  37449. * 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).
  37450. */
  37451. get: function () {
  37452. return this._shadowsHue;
  37453. },
  37454. /**
  37455. * Sets the shadows Hue value.
  37456. * 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).
  37457. */
  37458. set: function (value) {
  37459. this._shadowsHue = value;
  37460. this._dirty = true;
  37461. },
  37462. enumerable: true,
  37463. configurable: true
  37464. });
  37465. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37466. /**
  37467. * Gets the shadows Density value.
  37468. * 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.
  37469. * Values less than zero provide a filter of opposite hue.
  37470. */
  37471. get: function () {
  37472. return this._shadowsDensity;
  37473. },
  37474. /**
  37475. * Sets the shadows Density value.
  37476. * 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.
  37477. * Values less than zero provide a filter of opposite hue.
  37478. */
  37479. set: function (value) {
  37480. this._shadowsDensity = value;
  37481. this._dirty = true;
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37487. /**
  37488. * Gets the shadows Saturation value.
  37489. * 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.
  37490. */
  37491. get: function () {
  37492. return this._shadowsSaturation;
  37493. },
  37494. /**
  37495. * Sets the shadows Saturation value.
  37496. * 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.
  37497. */
  37498. set: function (value) {
  37499. this._shadowsSaturation = value;
  37500. this._dirty = true;
  37501. },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37506. /**
  37507. * Gets the shadows Exposure value.
  37508. * 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.
  37509. */
  37510. get: function () {
  37511. return this._shadowsExposure;
  37512. },
  37513. /**
  37514. * Sets the shadows Exposure value.
  37515. * 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.
  37516. */
  37517. set: function (value) {
  37518. this._shadowsExposure = value;
  37519. this._dirty = true;
  37520. },
  37521. enumerable: true,
  37522. configurable: true
  37523. });
  37524. ColorCurves.prototype.getClassName = function () {
  37525. return "ColorCurves";
  37526. };
  37527. /**
  37528. * Binds the color curves to the shader.
  37529. * @param colorCurves The color curve to bind
  37530. * @param effect The effect to bind to
  37531. */
  37532. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37533. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37534. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37535. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37536. if (colorCurves._dirty) {
  37537. colorCurves._dirty = false;
  37538. // Fill in global info.
  37539. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37540. // Compute highlights info.
  37541. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37542. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37543. // Compute midtones info.
  37544. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37545. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37546. // Compute shadows info.
  37547. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37548. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37549. // Compute deltas (neutral is midtones).
  37550. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37551. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37552. }
  37553. if (effect) {
  37554. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37555. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37556. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37557. }
  37558. };
  37559. /**
  37560. * Prepare the list of uniforms associated with the ColorCurves effects.
  37561. * @param uniformsList The list of uniforms used in the effect
  37562. */
  37563. ColorCurves.PrepareUniforms = function (uniformsList) {
  37564. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37565. };
  37566. /**
  37567. * Returns color grading data based on a hue, density, saturation and exposure value.
  37568. * @param filterHue The hue of the color filter.
  37569. * @param filterDensity The density of the color filter.
  37570. * @param saturation The saturation.
  37571. * @param exposure The exposure.
  37572. * @param result The result data container.
  37573. */
  37574. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37575. if (hue == null) {
  37576. return;
  37577. }
  37578. hue = ColorCurves.clamp(hue, 0, 360);
  37579. density = ColorCurves.clamp(density, -100, 100);
  37580. saturation = ColorCurves.clamp(saturation, -100, 100);
  37581. exposure = ColorCurves.clamp(exposure, -100, 100);
  37582. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37583. // so that the maximum filter density is only 50% control. This provides fine control
  37584. // for small values and reasonable range.
  37585. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37586. density *= 0.5;
  37587. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37588. if (density < 0) {
  37589. density *= -1;
  37590. hue = (hue + 180) % 360;
  37591. }
  37592. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37593. result.scaleToRef(2, result);
  37594. result.a = 1 + 0.01 * saturation;
  37595. };
  37596. /**
  37597. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37598. * @param value The input slider value in range [-100,100].
  37599. * @returns Adjusted value.
  37600. */
  37601. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37602. value /= 100;
  37603. var x = Math.abs(value);
  37604. x = Math.pow(x, 2);
  37605. if (value < 0) {
  37606. x *= -1;
  37607. }
  37608. x *= 100;
  37609. return x;
  37610. };
  37611. /**
  37612. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37613. * @param hue The hue (H) input.
  37614. * @param saturation The saturation (S) input.
  37615. * @param brightness The brightness (B) input.
  37616. * @result An RGBA color represented as Vector4.
  37617. */
  37618. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37619. var h = ColorCurves.clamp(hue, 0, 360);
  37620. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37621. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37622. if (s === 0) {
  37623. result.r = v;
  37624. result.g = v;
  37625. result.b = v;
  37626. }
  37627. else {
  37628. // sector 0 to 5
  37629. h /= 60;
  37630. var i = Math.floor(h);
  37631. // fractional part of h
  37632. var f = h - i;
  37633. var p = v * (1 - s);
  37634. var q = v * (1 - s * f);
  37635. var t = v * (1 - s * (1 - f));
  37636. switch (i) {
  37637. case 0:
  37638. result.r = v;
  37639. result.g = t;
  37640. result.b = p;
  37641. break;
  37642. case 1:
  37643. result.r = q;
  37644. result.g = v;
  37645. result.b = p;
  37646. break;
  37647. case 2:
  37648. result.r = p;
  37649. result.g = v;
  37650. result.b = t;
  37651. break;
  37652. case 3:
  37653. result.r = p;
  37654. result.g = q;
  37655. result.b = v;
  37656. break;
  37657. case 4:
  37658. result.r = t;
  37659. result.g = p;
  37660. result.b = v;
  37661. break;
  37662. default:// case 5:
  37663. result.r = v;
  37664. result.g = p;
  37665. result.b = q;
  37666. break;
  37667. }
  37668. }
  37669. result.a = 1;
  37670. };
  37671. /**
  37672. * Returns a value clamped between min and max
  37673. * @param value The value to clamp
  37674. * @param min The minimum of value
  37675. * @param max The maximum of value
  37676. * @returns The clamped value.
  37677. */
  37678. ColorCurves.clamp = function (value, min, max) {
  37679. return Math.min(Math.max(value, min), max);
  37680. };
  37681. /**
  37682. * Clones the current color curve instance.
  37683. * @return The cloned curves
  37684. */
  37685. ColorCurves.prototype.clone = function () {
  37686. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37687. };
  37688. /**
  37689. * Serializes the current color curve instance to a json representation.
  37690. * @return a JSON representation
  37691. */
  37692. ColorCurves.prototype.serialize = function () {
  37693. return BABYLON.SerializationHelper.Serialize(this);
  37694. };
  37695. /**
  37696. * Parses the color curve from a json representation.
  37697. * @param source the JSON source to parse
  37698. * @return The parsed curves
  37699. */
  37700. ColorCurves.Parse = function (source) {
  37701. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37702. };
  37703. __decorate([
  37704. BABYLON.serialize()
  37705. ], ColorCurves.prototype, "_globalHue", void 0);
  37706. __decorate([
  37707. BABYLON.serialize()
  37708. ], ColorCurves.prototype, "_globalDensity", void 0);
  37709. __decorate([
  37710. BABYLON.serialize()
  37711. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37712. __decorate([
  37713. BABYLON.serialize()
  37714. ], ColorCurves.prototype, "_globalExposure", void 0);
  37715. __decorate([
  37716. BABYLON.serialize()
  37717. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37718. __decorate([
  37719. BABYLON.serialize()
  37720. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37721. __decorate([
  37722. BABYLON.serialize()
  37723. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37724. __decorate([
  37725. BABYLON.serialize()
  37726. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37727. __decorate([
  37728. BABYLON.serialize()
  37729. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37730. __decorate([
  37731. BABYLON.serialize()
  37732. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37733. __decorate([
  37734. BABYLON.serialize()
  37735. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37736. __decorate([
  37737. BABYLON.serialize()
  37738. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37739. return ColorCurves;
  37740. }());
  37741. BABYLON.ColorCurves = ColorCurves;
  37742. })(BABYLON || (BABYLON = {}));
  37743. //# sourceMappingURL=babylon.colorCurves.js.map
  37744. //# sourceMappingURL=babylon.behavior.js.map
  37745. var BABYLON;
  37746. (function (BABYLON) {
  37747. /**
  37748. * "Static Class" containing the most commonly used helper while dealing with material for
  37749. * rendering purpose.
  37750. *
  37751. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37752. *
  37753. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37754. */
  37755. var MaterialHelper = /** @class */ (function () {
  37756. function MaterialHelper() {
  37757. }
  37758. /**
  37759. * Bind the current view position to an effect.
  37760. * @param effect The effect to be bound
  37761. * @param scene The scene the eyes position is used from
  37762. */
  37763. MaterialHelper.BindEyePosition = function (effect, scene) {
  37764. if (scene._forcedViewPosition) {
  37765. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37766. return;
  37767. }
  37768. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37769. };
  37770. /**
  37771. * Helps preparing the defines values about the UVs in used in the effect.
  37772. * UVs are shared as much as we can accross chanels in the shaders.
  37773. * @param texture The texture we are preparing the UVs for
  37774. * @param defines The defines to update
  37775. * @param key The chanel key "diffuse", "specular"... used in the shader
  37776. */
  37777. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37778. defines._needUVs = true;
  37779. defines[key] = true;
  37780. if (texture.getTextureMatrix().isIdentity(true)) {
  37781. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37782. if (texture.coordinatesIndex === 0) {
  37783. defines["MAINUV1"] = true;
  37784. }
  37785. else {
  37786. defines["MAINUV2"] = true;
  37787. }
  37788. }
  37789. else {
  37790. defines[key + "DIRECTUV"] = 0;
  37791. }
  37792. };
  37793. /**
  37794. * Binds a texture matrix value to its corrsponding uniform
  37795. * @param texture The texture to bind the matrix for
  37796. * @param uniformBuffer The uniform buffer receivin the data
  37797. * @param key The chanel key "diffuse", "specular"... used in the shader
  37798. */
  37799. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37800. var matrix = texture.getTextureMatrix();
  37801. if (!matrix.isIdentity(true)) {
  37802. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37803. }
  37804. };
  37805. /**
  37806. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37807. * @param mesh defines the current mesh
  37808. * @param scene defines the current scene
  37809. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37810. * @param pointsCloud defines if point cloud rendering has to be turned on
  37811. * @param fogEnabled defines if fog has to be turned on
  37812. * @param alphaTest defines if alpha testing has to be turned on
  37813. * @param defines defines the current list of defines
  37814. */
  37815. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37816. if (defines._areMiscDirty) {
  37817. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37818. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37819. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37820. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37821. defines["ALPHATEST"] = alphaTest;
  37822. }
  37823. };
  37824. /**
  37825. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37826. * @param scene defines the current scene
  37827. * @param engine defines the current engine
  37828. * @param defines specifies the list of active defines
  37829. * @param useInstances defines if instances have to be turned on
  37830. * @param useClipPlane defines if clip plane have to be turned on
  37831. */
  37832. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37833. if (useClipPlane === void 0) { useClipPlane = null; }
  37834. var changed = false;
  37835. if (useClipPlane == null) {
  37836. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37837. }
  37838. if (defines["CLIPPLANE"] !== useClipPlane) {
  37839. defines["CLIPPLANE"] = useClipPlane;
  37840. changed = true;
  37841. }
  37842. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37843. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37844. changed = true;
  37845. }
  37846. if (defines["INSTANCES"] !== useInstances) {
  37847. defines["INSTANCES"] = useInstances;
  37848. changed = true;
  37849. }
  37850. if (changed) {
  37851. defines.markAsUnprocessed();
  37852. }
  37853. };
  37854. /**
  37855. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37856. * @param mesh The mesh containing the geometry data we will draw
  37857. * @param defines The defines to update
  37858. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37859. * @param useBones Precise whether bones should be used or not (override mesh info)
  37860. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37861. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37862. * @returns false if defines are considered not dirty and have not been checked
  37863. */
  37864. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37865. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37866. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37867. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37868. return false;
  37869. }
  37870. defines._normals = defines._needNormals;
  37871. defines._uvs = defines._needUVs;
  37872. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37873. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37874. defines["TANGENT"] = true;
  37875. }
  37876. if (defines._needUVs) {
  37877. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37878. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37879. }
  37880. else {
  37881. defines["UV1"] = false;
  37882. defines["UV2"] = false;
  37883. }
  37884. if (useVertexColor) {
  37885. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37886. defines["VERTEXCOLOR"] = hasVertexColors;
  37887. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37888. }
  37889. if (useBones) {
  37890. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37891. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37892. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37893. }
  37894. else {
  37895. defines["NUM_BONE_INFLUENCERS"] = 0;
  37896. defines["BonesPerMesh"] = 0;
  37897. }
  37898. }
  37899. if (useMorphTargets) {
  37900. var manager = mesh.morphTargetManager;
  37901. if (manager) {
  37902. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37903. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37904. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37905. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37906. }
  37907. else {
  37908. defines["MORPHTARGETS_TANGENT"] = false;
  37909. defines["MORPHTARGETS_NORMAL"] = false;
  37910. defines["MORPHTARGETS"] = false;
  37911. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37912. }
  37913. }
  37914. return true;
  37915. };
  37916. /**
  37917. * Prepares the defines related to the light information passed in parameter
  37918. * @param scene The scene we are intending to draw
  37919. * @param mesh The mesh the effect is compiling for
  37920. * @param defines The defines to update
  37921. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37922. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37923. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37924. * @returns true if normals will be required for the rest of the effect
  37925. */
  37926. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37927. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37928. if (disableLighting === void 0) { disableLighting = false; }
  37929. if (!defines._areLightsDirty) {
  37930. return defines._needNormals;
  37931. }
  37932. var lightIndex = 0;
  37933. var needNormals = false;
  37934. var needRebuild = false;
  37935. var lightmapMode = false;
  37936. var shadowEnabled = false;
  37937. var specularEnabled = false;
  37938. if (scene.lightsEnabled && !disableLighting) {
  37939. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37940. var light = _a[_i];
  37941. needNormals = true;
  37942. if (defines["LIGHT" + lightIndex] === undefined) {
  37943. needRebuild = true;
  37944. }
  37945. defines["LIGHT" + lightIndex] = true;
  37946. defines["SPOTLIGHT" + lightIndex] = false;
  37947. defines["HEMILIGHT" + lightIndex] = false;
  37948. defines["POINTLIGHT" + lightIndex] = false;
  37949. defines["DIRLIGHT" + lightIndex] = false;
  37950. var type;
  37951. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37952. type = "SPOTLIGHT" + lightIndex;
  37953. var spotLight = light;
  37954. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37955. }
  37956. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37957. type = "HEMILIGHT" + lightIndex;
  37958. }
  37959. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37960. type = "POINTLIGHT" + lightIndex;
  37961. }
  37962. else {
  37963. type = "DIRLIGHT" + lightIndex;
  37964. }
  37965. defines[type] = true;
  37966. // Specular
  37967. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37968. specularEnabled = true;
  37969. }
  37970. // Shadows
  37971. defines["SHADOW" + lightIndex] = false;
  37972. defines["SHADOWPCF" + lightIndex] = false;
  37973. defines["SHADOWESM" + lightIndex] = false;
  37974. defines["SHADOWCUBE" + lightIndex] = false;
  37975. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37976. var shadowGenerator = light.getShadowGenerator();
  37977. if (shadowGenerator) {
  37978. shadowEnabled = true;
  37979. shadowGenerator.prepareDefines(defines, lightIndex);
  37980. }
  37981. }
  37982. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37983. lightmapMode = true;
  37984. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37985. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37986. }
  37987. else {
  37988. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37989. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37990. }
  37991. lightIndex++;
  37992. if (lightIndex === maxSimultaneousLights)
  37993. break;
  37994. }
  37995. }
  37996. defines["SPECULARTERM"] = specularEnabled;
  37997. defines["SHADOWS"] = shadowEnabled;
  37998. // Resetting all other lights if any
  37999. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38000. if (defines["LIGHT" + index] !== undefined) {
  38001. defines["LIGHT" + index] = false;
  38002. defines["HEMILIGHT" + lightIndex] = false;
  38003. defines["POINTLIGHT" + lightIndex] = false;
  38004. defines["DIRLIGHT" + lightIndex] = false;
  38005. defines["SPOTLIGHT" + lightIndex] = false;
  38006. defines["SHADOW" + lightIndex] = false;
  38007. }
  38008. }
  38009. var caps = scene.getEngine().getCaps();
  38010. if (defines["SHADOWFLOAT"] === undefined) {
  38011. needRebuild = true;
  38012. }
  38013. defines["SHADOWFLOAT"] = shadowEnabled &&
  38014. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38015. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38016. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38017. if (needRebuild) {
  38018. defines.rebuild();
  38019. }
  38020. return needNormals;
  38021. };
  38022. /**
  38023. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38024. * that won t be acctive due to defines being turned off.
  38025. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38026. * @param samplersList The samplers list
  38027. * @param defines The defines helping in the list generation
  38028. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38029. */
  38030. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38031. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38032. var uniformsList;
  38033. var uniformBuffersList = null;
  38034. if (uniformsListOrOptions.uniformsNames) {
  38035. var options = uniformsListOrOptions;
  38036. uniformsList = options.uniformsNames;
  38037. uniformBuffersList = options.uniformBuffersNames;
  38038. samplersList = options.samplers;
  38039. defines = options.defines;
  38040. maxSimultaneousLights = options.maxSimultaneousLights;
  38041. }
  38042. else {
  38043. uniformsList = uniformsListOrOptions;
  38044. if (!samplersList) {
  38045. samplersList = [];
  38046. }
  38047. }
  38048. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38049. if (!defines["LIGHT" + lightIndex]) {
  38050. break;
  38051. }
  38052. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38053. if (uniformBuffersList) {
  38054. uniformBuffersList.push("Light" + lightIndex);
  38055. }
  38056. samplersList.push("shadowSampler" + lightIndex);
  38057. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38058. samplersList.push("projectionLightSampler" + lightIndex);
  38059. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38060. }
  38061. }
  38062. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38063. uniformsList.push("morphTargetInfluences");
  38064. }
  38065. };
  38066. /**
  38067. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38068. * @param defines The defines to update while falling back
  38069. * @param fallbacks The authorized effect fallbacks
  38070. * @param maxSimultaneousLights The maximum number of lights allowed
  38071. * @param rank the current rank of the Effect
  38072. * @returns The newly affected rank
  38073. */
  38074. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38075. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38076. if (rank === void 0) { rank = 0; }
  38077. var lightFallbackRank = 0;
  38078. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38079. if (!defines["LIGHT" + lightIndex]) {
  38080. break;
  38081. }
  38082. if (lightIndex > 0) {
  38083. lightFallbackRank = rank + lightIndex;
  38084. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38085. }
  38086. if (!defines["SHADOWS"]) {
  38087. if (defines["SHADOW" + lightIndex]) {
  38088. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38089. }
  38090. if (defines["SHADOWPCF" + lightIndex]) {
  38091. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38092. }
  38093. if (defines["SHADOWESM" + lightIndex]) {
  38094. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38095. }
  38096. }
  38097. }
  38098. return lightFallbackRank++;
  38099. };
  38100. /**
  38101. * Prepares the list of attributes required for morph targets according to the effect defines.
  38102. * @param attribs The current list of supported attribs
  38103. * @param mesh The mesh to prepare the morph targets attributes for
  38104. * @param defines The current Defines of the effect
  38105. */
  38106. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38107. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38108. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38109. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38110. var manager = mesh.morphTargetManager;
  38111. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38112. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38113. for (var index = 0; index < influencers; index++) {
  38114. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38115. if (normal) {
  38116. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38117. }
  38118. if (tangent) {
  38119. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38120. }
  38121. if (attribs.length > maxAttributesCount) {
  38122. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38123. }
  38124. }
  38125. }
  38126. };
  38127. /**
  38128. * Prepares the list of attributes required for bones according to the effect defines.
  38129. * @param attribs The current list of supported attribs
  38130. * @param mesh The mesh to prepare the bones attributes for
  38131. * @param defines The current Defines of the effect
  38132. * @param fallbacks The current efffect fallback strategy
  38133. */
  38134. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38135. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38136. fallbacks.addCPUSkinningFallback(0, mesh);
  38137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38139. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38142. }
  38143. }
  38144. };
  38145. /**
  38146. * Prepares the list of attributes required for instances according to the effect defines.
  38147. * @param attribs The current list of supported attribs
  38148. * @param defines The current Defines of the effect
  38149. */
  38150. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38151. if (defines["INSTANCES"]) {
  38152. attribs.push("world0");
  38153. attribs.push("world1");
  38154. attribs.push("world2");
  38155. attribs.push("world3");
  38156. }
  38157. };
  38158. /**
  38159. * Binds the light shadow information to the effect for the given mesh.
  38160. * @param light The light containing the generator
  38161. * @param scene The scene the lights belongs to
  38162. * @param mesh The mesh we are binding the information to render
  38163. * @param lightIndex The light index in the effect used to render the mesh
  38164. * @param effect The effect we are binding the data to
  38165. */
  38166. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38167. if (light.shadowEnabled && mesh.receiveShadows) {
  38168. var shadowGenerator = light.getShadowGenerator();
  38169. if (shadowGenerator) {
  38170. shadowGenerator.bindShadowLight(lightIndex, effect);
  38171. }
  38172. }
  38173. };
  38174. /**
  38175. * Binds the light information to the effect.
  38176. * @param light The light containing the generator
  38177. * @param effect The effect we are binding the data to
  38178. * @param lightIndex The light index in the effect used to render
  38179. */
  38180. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38181. light.transferToEffect(effect, lightIndex + "");
  38182. };
  38183. /**
  38184. * Binds the lights information from the scene to the effect for the given mesh.
  38185. * @param scene The scene the lights belongs to
  38186. * @param mesh The mesh we are binding the information to render
  38187. * @param effect The effect we are binding the data to
  38188. * @param defines The generated defines for the effect
  38189. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38190. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38191. */
  38192. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38193. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38194. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38195. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38196. for (var i = 0; i < len; i++) {
  38197. var light = mesh._lightSources[i];
  38198. var iAsString = i.toString();
  38199. var scaledIntensity = light.getScaledIntensity();
  38200. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38201. MaterialHelper.BindLightProperties(light, effect, i);
  38202. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38203. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38204. if (defines["SPECULARTERM"]) {
  38205. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38206. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38207. }
  38208. // Shadows
  38209. if (scene.shadowsEnabled) {
  38210. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38211. }
  38212. light._uniformBuffer.update();
  38213. }
  38214. };
  38215. /**
  38216. * Binds the fog information from the scene to the effect for the given mesh.
  38217. * @param scene The scene the lights belongs to
  38218. * @param mesh The mesh we are binding the information to render
  38219. * @param effect The effect we are binding the data to
  38220. */
  38221. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38222. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38223. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38224. effect.setColor3("vFogColor", scene.fogColor);
  38225. }
  38226. };
  38227. /**
  38228. * Binds the bones information from the mesh to the effect.
  38229. * @param mesh The mesh we are binding the information to render
  38230. * @param effect The effect we are binding the data to
  38231. */
  38232. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38233. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38234. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38235. if (matrices && effect) {
  38236. effect.setMatrices("mBones", matrices);
  38237. }
  38238. }
  38239. };
  38240. /**
  38241. * Binds the morph targets information from the mesh to the effect.
  38242. * @param abstractMesh The mesh we are binding the information to render
  38243. * @param effect The effect we are binding the data to
  38244. */
  38245. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38246. var manager = abstractMesh.morphTargetManager;
  38247. if (!abstractMesh || !manager) {
  38248. return;
  38249. }
  38250. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38251. };
  38252. /**
  38253. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38254. * @param defines The generated defines used in the effect
  38255. * @param effect The effect we are binding the data to
  38256. * @param scene The scene we are willing to render with logarithmic scale for
  38257. */
  38258. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38259. if (defines["LOGARITHMICDEPTH"]) {
  38260. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38261. }
  38262. };
  38263. /**
  38264. * Binds the clip plane information from the scene to the effect.
  38265. * @param scene The scene the clip plane information are extracted from
  38266. * @param effect The effect we are binding the data to
  38267. */
  38268. MaterialHelper.BindClipPlane = function (effect, scene) {
  38269. if (scene.clipPlane) {
  38270. var clipPlane = scene.clipPlane;
  38271. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38272. }
  38273. };
  38274. return MaterialHelper;
  38275. }());
  38276. BABYLON.MaterialHelper = MaterialHelper;
  38277. })(BABYLON || (BABYLON = {}));
  38278. //# sourceMappingURL=babylon.materialHelper.js.map
  38279. var BABYLON;
  38280. (function (BABYLON) {
  38281. var PushMaterial = /** @class */ (function (_super) {
  38282. __extends(PushMaterial, _super);
  38283. function PushMaterial(name, scene) {
  38284. var _this = _super.call(this, name, scene) || this;
  38285. _this._normalMatrix = new BABYLON.Matrix();
  38286. _this.storeEffectOnSubMeshes = true;
  38287. return _this;
  38288. }
  38289. PushMaterial.prototype.getEffect = function () {
  38290. return this._activeEffect;
  38291. };
  38292. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38293. if (!mesh) {
  38294. return false;
  38295. }
  38296. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38297. return true;
  38298. }
  38299. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38300. };
  38301. /**
  38302. * Binds the given world matrix to the active effect
  38303. *
  38304. * @param world the matrix to bind
  38305. */
  38306. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38307. this._activeEffect.setMatrix("world", world);
  38308. };
  38309. /**
  38310. * Binds the given normal matrix to the active effect
  38311. *
  38312. * @param normalMatrix the matrix to bind
  38313. */
  38314. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38315. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38316. };
  38317. PushMaterial.prototype.bind = function (world, mesh) {
  38318. if (!mesh) {
  38319. return;
  38320. }
  38321. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38322. };
  38323. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38324. if (effect === void 0) { effect = null; }
  38325. _super.prototype._afterBind.call(this, mesh);
  38326. this.getScene()._cachedEffect = effect;
  38327. };
  38328. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38329. if (visibility === void 0) { visibility = 1; }
  38330. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38331. };
  38332. return PushMaterial;
  38333. }(BABYLON.Material));
  38334. BABYLON.PushMaterial = PushMaterial;
  38335. })(BABYLON || (BABYLON = {}));
  38336. //# sourceMappingURL=babylon.pushMaterial.js.map
  38337. var BABYLON;
  38338. (function (BABYLON) {
  38339. /** @ignore */
  38340. var StandardMaterialDefines = /** @class */ (function (_super) {
  38341. __extends(StandardMaterialDefines, _super);
  38342. function StandardMaterialDefines() {
  38343. var _this = _super.call(this) || this;
  38344. _this.MAINUV1 = false;
  38345. _this.MAINUV2 = false;
  38346. _this.DIFFUSE = false;
  38347. _this.DIFFUSEDIRECTUV = 0;
  38348. _this.AMBIENT = false;
  38349. _this.AMBIENTDIRECTUV = 0;
  38350. _this.OPACITY = false;
  38351. _this.OPACITYDIRECTUV = 0;
  38352. _this.OPACITYRGB = false;
  38353. _this.REFLECTION = false;
  38354. _this.EMISSIVE = false;
  38355. _this.EMISSIVEDIRECTUV = 0;
  38356. _this.SPECULAR = false;
  38357. _this.SPECULARDIRECTUV = 0;
  38358. _this.BUMP = false;
  38359. _this.BUMPDIRECTUV = 0;
  38360. _this.PARALLAX = false;
  38361. _this.PARALLAXOCCLUSION = false;
  38362. _this.SPECULAROVERALPHA = false;
  38363. _this.CLIPPLANE = false;
  38364. _this.ALPHATEST = false;
  38365. _this.DEPTHPREPASS = false;
  38366. _this.ALPHAFROMDIFFUSE = false;
  38367. _this.POINTSIZE = false;
  38368. _this.FOG = false;
  38369. _this.SPECULARTERM = false;
  38370. _this.DIFFUSEFRESNEL = false;
  38371. _this.OPACITYFRESNEL = false;
  38372. _this.REFLECTIONFRESNEL = false;
  38373. _this.REFRACTIONFRESNEL = false;
  38374. _this.EMISSIVEFRESNEL = false;
  38375. _this.FRESNEL = false;
  38376. _this.NORMAL = false;
  38377. _this.UV1 = false;
  38378. _this.UV2 = false;
  38379. _this.VERTEXCOLOR = false;
  38380. _this.VERTEXALPHA = false;
  38381. _this.NUM_BONE_INFLUENCERS = 0;
  38382. _this.BonesPerMesh = 0;
  38383. _this.INSTANCES = false;
  38384. _this.GLOSSINESS = false;
  38385. _this.ROUGHNESS = false;
  38386. _this.EMISSIVEASILLUMINATION = false;
  38387. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38388. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38389. _this.LIGHTMAP = false;
  38390. _this.LIGHTMAPDIRECTUV = 0;
  38391. _this.OBJECTSPACE_NORMALMAP = false;
  38392. _this.USELIGHTMAPASSHADOWMAP = false;
  38393. _this.REFLECTIONMAP_3D = false;
  38394. _this.REFLECTIONMAP_SPHERICAL = false;
  38395. _this.REFLECTIONMAP_PLANAR = false;
  38396. _this.REFLECTIONMAP_CUBIC = false;
  38397. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38398. _this.REFLECTIONMAP_PROJECTION = false;
  38399. _this.REFLECTIONMAP_SKYBOX = false;
  38400. _this.REFLECTIONMAP_EXPLICIT = false;
  38401. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38402. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38403. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38404. _this.INVERTCUBICMAP = false;
  38405. _this.LOGARITHMICDEPTH = false;
  38406. _this.REFRACTION = false;
  38407. _this.REFRACTIONMAP_3D = false;
  38408. _this.REFLECTIONOVERALPHA = false;
  38409. _this.TWOSIDEDLIGHTING = false;
  38410. _this.SHADOWFLOAT = false;
  38411. _this.MORPHTARGETS = false;
  38412. _this.MORPHTARGETS_NORMAL = false;
  38413. _this.MORPHTARGETS_TANGENT = false;
  38414. _this.NUM_MORPH_INFLUENCERS = 0;
  38415. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38416. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38417. _this.IMAGEPROCESSING = false;
  38418. _this.VIGNETTE = false;
  38419. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38420. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38421. _this.TONEMAPPING = false;
  38422. _this.CONTRAST = false;
  38423. _this.COLORCURVES = false;
  38424. _this.COLORGRADING = false;
  38425. _this.COLORGRADING3D = false;
  38426. _this.SAMPLER3DGREENDEPTH = false;
  38427. _this.SAMPLER3DBGRMAP = false;
  38428. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38429. _this.EXPOSURE = false;
  38430. _this.rebuild();
  38431. return _this;
  38432. }
  38433. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38434. var modes = [
  38435. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38436. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38437. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38438. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38439. ];
  38440. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38441. var mode = modes_1[_i];
  38442. this[mode] = (mode === modeToEnable);
  38443. }
  38444. };
  38445. return StandardMaterialDefines;
  38446. }(BABYLON.MaterialDefines));
  38447. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38448. var StandardMaterial = /** @class */ (function (_super) {
  38449. __extends(StandardMaterial, _super);
  38450. function StandardMaterial(name, scene) {
  38451. var _this = _super.call(this, name, scene) || this;
  38452. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38453. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38454. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38455. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38456. _this.specularPower = 64;
  38457. _this._useAlphaFromDiffuseTexture = false;
  38458. _this._useEmissiveAsIllumination = false;
  38459. _this._linkEmissiveWithDiffuse = false;
  38460. _this._useSpecularOverAlpha = false;
  38461. _this._useReflectionOverAlpha = false;
  38462. _this._disableLighting = false;
  38463. _this._useObjectSpaceNormalMap = false;
  38464. _this._useParallax = false;
  38465. _this._useParallaxOcclusion = false;
  38466. _this.parallaxScaleBias = 0.05;
  38467. _this._roughness = 0;
  38468. _this.indexOfRefraction = 0.98;
  38469. _this.invertRefractionY = true;
  38470. _this._useLightmapAsShadowmap = false;
  38471. _this._useReflectionFresnelFromSpecular = false;
  38472. _this._useGlossinessFromSpecularMapAlpha = false;
  38473. _this._maxSimultaneousLights = 4;
  38474. /**
  38475. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38476. */
  38477. _this._invertNormalMapX = false;
  38478. /**
  38479. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38480. */
  38481. _this._invertNormalMapY = false;
  38482. /**
  38483. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38484. */
  38485. _this._twoSidedLighting = false;
  38486. _this._renderTargets = new BABYLON.SmartArray(16);
  38487. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38488. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38489. // Setup the default processing configuration to the scene.
  38490. _this._attachImageProcessingConfiguration(null);
  38491. _this.getRenderTargetTextures = function () {
  38492. _this._renderTargets.reset();
  38493. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38494. _this._renderTargets.push(_this._reflectionTexture);
  38495. }
  38496. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38497. _this._renderTargets.push(_this._refractionTexture);
  38498. }
  38499. return _this._renderTargets;
  38500. };
  38501. return _this;
  38502. }
  38503. ;
  38504. ;
  38505. ;
  38506. ;
  38507. ;
  38508. ;
  38509. ;
  38510. ;
  38511. ;
  38512. ;
  38513. ;
  38514. ;
  38515. ;
  38516. ;
  38517. ;
  38518. ;
  38519. ;
  38520. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38521. /**
  38522. * Gets the image processing configuration used either in this material.
  38523. */
  38524. get: function () {
  38525. return this._imageProcessingConfiguration;
  38526. },
  38527. /**
  38528. * Sets the Default image processing configuration used either in the this material.
  38529. *
  38530. * If sets to null, the scene one is in use.
  38531. */
  38532. set: function (value) {
  38533. this._attachImageProcessingConfiguration(value);
  38534. // Ensure the effect will be rebuilt.
  38535. this._markAllSubMeshesAsTexturesDirty();
  38536. },
  38537. enumerable: true,
  38538. configurable: true
  38539. });
  38540. /**
  38541. * Attaches a new image processing configuration to the Standard Material.
  38542. * @param configuration
  38543. */
  38544. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38545. var _this = this;
  38546. if (configuration === this._imageProcessingConfiguration) {
  38547. return;
  38548. }
  38549. // Detaches observer.
  38550. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38551. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38552. }
  38553. // Pick the scene configuration if needed.
  38554. if (!configuration) {
  38555. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38556. }
  38557. else {
  38558. this._imageProcessingConfiguration = configuration;
  38559. }
  38560. // Attaches observer.
  38561. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38562. _this._markAllSubMeshesAsImageProcessingDirty();
  38563. });
  38564. };
  38565. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38566. /**
  38567. * Gets wether the color curves effect is enabled.
  38568. */
  38569. get: function () {
  38570. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38571. },
  38572. /**
  38573. * Sets wether the color curves effect is enabled.
  38574. */
  38575. set: function (value) {
  38576. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38577. },
  38578. enumerable: true,
  38579. configurable: true
  38580. });
  38581. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38582. /**
  38583. * Gets wether the color grading effect is enabled.
  38584. */
  38585. get: function () {
  38586. return this.imageProcessingConfiguration.colorGradingEnabled;
  38587. },
  38588. /**
  38589. * Gets wether the color grading effect is enabled.
  38590. */
  38591. set: function (value) {
  38592. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38598. /**
  38599. * Gets wether tonemapping is enabled or not.
  38600. */
  38601. get: function () {
  38602. return this._imageProcessingConfiguration.toneMappingEnabled;
  38603. },
  38604. /**
  38605. * Sets wether tonemapping is enabled or not
  38606. */
  38607. set: function (value) {
  38608. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. ;
  38614. ;
  38615. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38616. /**
  38617. * The camera exposure used on this material.
  38618. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38619. * This corresponds to a photographic exposure.
  38620. */
  38621. get: function () {
  38622. return this._imageProcessingConfiguration.exposure;
  38623. },
  38624. /**
  38625. * The camera exposure used on this material.
  38626. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38627. * This corresponds to a photographic exposure.
  38628. */
  38629. set: function (value) {
  38630. this._imageProcessingConfiguration.exposure = value;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. ;
  38636. ;
  38637. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38638. /**
  38639. * Gets The camera contrast used on this material.
  38640. */
  38641. get: function () {
  38642. return this._imageProcessingConfiguration.contrast;
  38643. },
  38644. /**
  38645. * Sets The camera contrast used on this material.
  38646. */
  38647. set: function (value) {
  38648. this._imageProcessingConfiguration.contrast = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38654. /**
  38655. * Gets the Color Grading 2D Lookup Texture.
  38656. */
  38657. get: function () {
  38658. return this._imageProcessingConfiguration.colorGradingTexture;
  38659. },
  38660. /**
  38661. * Sets the Color Grading 2D Lookup Texture.
  38662. */
  38663. set: function (value) {
  38664. this._imageProcessingConfiguration.colorGradingTexture = value;
  38665. },
  38666. enumerable: true,
  38667. configurable: true
  38668. });
  38669. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38670. /**
  38671. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38672. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38673. * 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;
  38674. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38675. */
  38676. get: function () {
  38677. return this._imageProcessingConfiguration.colorCurves;
  38678. },
  38679. /**
  38680. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38681. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38682. * 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;
  38683. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38684. */
  38685. set: function (value) {
  38686. this._imageProcessingConfiguration.colorCurves = value;
  38687. },
  38688. enumerable: true,
  38689. configurable: true
  38690. });
  38691. StandardMaterial.prototype.getClassName = function () {
  38692. return "StandardMaterial";
  38693. };
  38694. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38695. get: function () {
  38696. return this._useLogarithmicDepth;
  38697. },
  38698. set: function (value) {
  38699. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38700. this._markAllSubMeshesAsMiscDirty();
  38701. },
  38702. enumerable: true,
  38703. configurable: true
  38704. });
  38705. StandardMaterial.prototype.needAlphaBlending = function () {
  38706. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38707. };
  38708. StandardMaterial.prototype.needAlphaTesting = function () {
  38709. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38710. };
  38711. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38712. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38713. };
  38714. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38715. return this._diffuseTexture;
  38716. };
  38717. /**
  38718. * Child classes can use it to update shaders
  38719. */
  38720. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38721. if (useInstances === void 0) { useInstances = false; }
  38722. if (subMesh.effect && this.isFrozen) {
  38723. if (this._wasPreviouslyReady && subMesh.effect) {
  38724. return true;
  38725. }
  38726. }
  38727. if (!subMesh._materialDefines) {
  38728. subMesh._materialDefines = new StandardMaterialDefines();
  38729. }
  38730. var scene = this.getScene();
  38731. var defines = subMesh._materialDefines;
  38732. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38733. if (defines._renderId === scene.getRenderId()) {
  38734. return true;
  38735. }
  38736. }
  38737. var engine = scene.getEngine();
  38738. // Lights
  38739. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38740. // Textures
  38741. if (defines._areTexturesDirty) {
  38742. defines._needUVs = false;
  38743. defines.MAINUV1 = false;
  38744. defines.MAINUV2 = false;
  38745. if (scene.texturesEnabled) {
  38746. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38747. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38748. return false;
  38749. }
  38750. else {
  38751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38752. }
  38753. }
  38754. else {
  38755. defines.DIFFUSE = false;
  38756. }
  38757. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38758. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38759. return false;
  38760. }
  38761. else {
  38762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38763. }
  38764. }
  38765. else {
  38766. defines.AMBIENT = false;
  38767. }
  38768. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38769. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38770. return false;
  38771. }
  38772. else {
  38773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38774. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38775. }
  38776. }
  38777. else {
  38778. defines.OPACITY = false;
  38779. }
  38780. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38781. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38782. return false;
  38783. }
  38784. else {
  38785. defines._needNormals = true;
  38786. defines.REFLECTION = true;
  38787. defines.ROUGHNESS = (this._roughness > 0);
  38788. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38789. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38790. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38791. switch (this._reflectionTexture.coordinatesMode) {
  38792. case BABYLON.Texture.CUBIC_MODE:
  38793. case BABYLON.Texture.INVCUBIC_MODE:
  38794. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38795. break;
  38796. case BABYLON.Texture.EXPLICIT_MODE:
  38797. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38798. break;
  38799. case BABYLON.Texture.PLANAR_MODE:
  38800. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38801. break;
  38802. case BABYLON.Texture.PROJECTION_MODE:
  38803. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38804. break;
  38805. case BABYLON.Texture.SKYBOX_MODE:
  38806. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38807. break;
  38808. case BABYLON.Texture.SPHERICAL_MODE:
  38809. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38810. break;
  38811. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38812. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38813. break;
  38814. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38815. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38816. break;
  38817. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38818. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38819. break;
  38820. }
  38821. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38822. }
  38823. }
  38824. else {
  38825. defines.REFLECTION = false;
  38826. }
  38827. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38828. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38829. return false;
  38830. }
  38831. else {
  38832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38833. }
  38834. }
  38835. else {
  38836. defines.EMISSIVE = false;
  38837. }
  38838. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38839. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38840. return false;
  38841. }
  38842. else {
  38843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38844. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38845. }
  38846. }
  38847. else {
  38848. defines.LIGHTMAP = false;
  38849. }
  38850. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38851. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38852. return false;
  38853. }
  38854. else {
  38855. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38856. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38857. }
  38858. }
  38859. else {
  38860. defines.SPECULAR = false;
  38861. }
  38862. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38863. // Bump texure can not be not blocking.
  38864. if (!this._bumpTexture.isReady()) {
  38865. return false;
  38866. }
  38867. else {
  38868. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38869. defines.PARALLAX = this._useParallax;
  38870. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38871. }
  38872. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38873. }
  38874. else {
  38875. defines.BUMP = false;
  38876. }
  38877. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38878. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38879. return false;
  38880. }
  38881. else {
  38882. defines._needUVs = true;
  38883. defines.REFRACTION = true;
  38884. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38885. }
  38886. }
  38887. else {
  38888. defines.REFRACTION = false;
  38889. }
  38890. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38891. }
  38892. else {
  38893. defines.DIFFUSE = false;
  38894. defines.AMBIENT = false;
  38895. defines.OPACITY = false;
  38896. defines.REFLECTION = false;
  38897. defines.EMISSIVE = false;
  38898. defines.LIGHTMAP = false;
  38899. defines.BUMP = false;
  38900. defines.REFRACTION = false;
  38901. }
  38902. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38903. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38904. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38905. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38906. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38907. }
  38908. if (defines._areImageProcessingDirty) {
  38909. if (!this._imageProcessingConfiguration.isReady()) {
  38910. return false;
  38911. }
  38912. this._imageProcessingConfiguration.prepareDefines(defines);
  38913. }
  38914. if (defines._areFresnelDirty) {
  38915. if (StandardMaterial.FresnelEnabled) {
  38916. // Fresnel
  38917. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38918. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38919. this._reflectionFresnelParameters) {
  38920. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38921. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38922. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38923. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38924. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38925. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38926. defines._needNormals = true;
  38927. defines.FRESNEL = true;
  38928. }
  38929. }
  38930. else {
  38931. defines.FRESNEL = false;
  38932. }
  38933. }
  38934. // Misc.
  38935. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38936. // Attribs
  38937. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38938. // Values that need to be evaluated on every frame
  38939. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38940. // Get correct effect
  38941. if (defines.isDirty) {
  38942. defines.markAsProcessed();
  38943. scene.resetCachedMaterial();
  38944. // Fallbacks
  38945. var fallbacks = new BABYLON.EffectFallbacks();
  38946. if (defines.REFLECTION) {
  38947. fallbacks.addFallback(0, "REFLECTION");
  38948. }
  38949. if (defines.SPECULAR) {
  38950. fallbacks.addFallback(0, "SPECULAR");
  38951. }
  38952. if (defines.BUMP) {
  38953. fallbacks.addFallback(0, "BUMP");
  38954. }
  38955. if (defines.PARALLAX) {
  38956. fallbacks.addFallback(1, "PARALLAX");
  38957. }
  38958. if (defines.PARALLAXOCCLUSION) {
  38959. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38960. }
  38961. if (defines.SPECULAROVERALPHA) {
  38962. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38963. }
  38964. if (defines.FOG) {
  38965. fallbacks.addFallback(1, "FOG");
  38966. }
  38967. if (defines.POINTSIZE) {
  38968. fallbacks.addFallback(0, "POINTSIZE");
  38969. }
  38970. if (defines.LOGARITHMICDEPTH) {
  38971. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38972. }
  38973. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38974. if (defines.SPECULARTERM) {
  38975. fallbacks.addFallback(0, "SPECULARTERM");
  38976. }
  38977. if (defines.DIFFUSEFRESNEL) {
  38978. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38979. }
  38980. if (defines.OPACITYFRESNEL) {
  38981. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38982. }
  38983. if (defines.REFLECTIONFRESNEL) {
  38984. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38985. }
  38986. if (defines.EMISSIVEFRESNEL) {
  38987. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38988. }
  38989. if (defines.FRESNEL) {
  38990. fallbacks.addFallback(4, "FRESNEL");
  38991. }
  38992. //Attributes
  38993. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38994. if (defines.NORMAL) {
  38995. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38996. }
  38997. if (defines.UV1) {
  38998. attribs.push(BABYLON.VertexBuffer.UVKind);
  38999. }
  39000. if (defines.UV2) {
  39001. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39002. }
  39003. if (defines.VERTEXCOLOR) {
  39004. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39005. }
  39006. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39007. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39008. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39009. var shaderName = "default";
  39010. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39011. "vFogInfos", "vFogColor", "pointSize",
  39012. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39013. "mBones",
  39014. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39015. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39016. "vReflectionPosition", "vReflectionSize",
  39017. "logarithmicDepthConstant", "vTangentSpaceParams"
  39018. ];
  39019. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39020. var uniformBuffers = ["Material", "Scene"];
  39021. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39023. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39024. uniformsNames: uniforms,
  39025. uniformBuffersNames: uniformBuffers,
  39026. samplers: samplers,
  39027. defines: defines,
  39028. maxSimultaneousLights: this._maxSimultaneousLights
  39029. });
  39030. if (this.customShaderNameResolve) {
  39031. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39032. }
  39033. var join = defines.toString();
  39034. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39035. attributes: attribs,
  39036. uniformsNames: uniforms,
  39037. uniformBuffersNames: uniformBuffers,
  39038. samplers: samplers,
  39039. defines: join,
  39040. fallbacks: fallbacks,
  39041. onCompiled: this.onCompiled,
  39042. onError: this.onError,
  39043. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39044. }, engine), defines);
  39045. this.buildUniformLayout();
  39046. }
  39047. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39048. return false;
  39049. }
  39050. defines._renderId = scene.getRenderId();
  39051. this._wasPreviouslyReady = true;
  39052. return true;
  39053. };
  39054. StandardMaterial.prototype.buildUniformLayout = function () {
  39055. // Order is important !
  39056. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39057. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39058. this._uniformBuffer.addUniform("opacityParts", 4);
  39059. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39060. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39061. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39062. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39063. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39064. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39065. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39066. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39067. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39068. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39069. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39070. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39071. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39072. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39073. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39074. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39075. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39076. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39077. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39078. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39079. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39080. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39081. this._uniformBuffer.addUniform("specularMatrix", 16);
  39082. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39083. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39084. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39085. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39086. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39087. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39088. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39089. this._uniformBuffer.addUniform("pointSize", 1);
  39090. this._uniformBuffer.create();
  39091. };
  39092. StandardMaterial.prototype.unbind = function () {
  39093. if (this._activeEffect) {
  39094. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39095. this._activeEffect.setTexture("reflection2DSampler", null);
  39096. }
  39097. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39098. this._activeEffect.setTexture("refraction2DSampler", null);
  39099. }
  39100. }
  39101. _super.prototype.unbind.call(this);
  39102. };
  39103. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39104. var scene = this.getScene();
  39105. var defines = subMesh._materialDefines;
  39106. if (!defines) {
  39107. return;
  39108. }
  39109. var effect = subMesh.effect;
  39110. if (!effect) {
  39111. return;
  39112. }
  39113. this._activeEffect = effect;
  39114. // Matrices
  39115. this.bindOnlyWorldMatrix(world);
  39116. // Normal Matrix
  39117. if (defines.OBJECTSPACE_NORMALMAP) {
  39118. world.toNormalMatrix(this._normalMatrix);
  39119. this.bindOnlyNormalMatrix(this._normalMatrix);
  39120. }
  39121. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39122. // Bones
  39123. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39124. if (mustRebind) {
  39125. this._uniformBuffer.bindToEffect(effect, "Material");
  39126. this.bindViewProjection(effect);
  39127. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39128. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39129. // Fresnel
  39130. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39131. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39132. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39133. }
  39134. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39135. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39136. }
  39137. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39138. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39139. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39140. }
  39141. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39142. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39143. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39144. }
  39145. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39146. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39147. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39148. }
  39149. }
  39150. // Textures
  39151. if (scene.texturesEnabled) {
  39152. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39153. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39154. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39155. }
  39156. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39157. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39158. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39159. }
  39160. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39161. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39162. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39163. }
  39164. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39165. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39166. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39167. if (this._reflectionTexture.boundingBoxSize) {
  39168. var cubeTexture = this._reflectionTexture;
  39169. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39170. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39171. }
  39172. }
  39173. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39174. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39175. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39176. }
  39177. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39178. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39179. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39180. }
  39181. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39182. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39183. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39184. }
  39185. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39186. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39187. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39188. if (scene._mirroredCameraPosition) {
  39189. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39190. }
  39191. else {
  39192. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39193. }
  39194. }
  39195. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39196. var depth = 1.0;
  39197. if (!this._refractionTexture.isCube) {
  39198. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39199. if (this._refractionTexture.depth) {
  39200. depth = this._refractionTexture.depth;
  39201. }
  39202. }
  39203. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39204. }
  39205. }
  39206. // Point size
  39207. if (this.pointsCloud) {
  39208. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39209. }
  39210. if (defines.SPECULARTERM) {
  39211. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39212. }
  39213. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39214. // Diffuse
  39215. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39216. }
  39217. // Textures
  39218. if (scene.texturesEnabled) {
  39219. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39220. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39221. }
  39222. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39223. effect.setTexture("ambientSampler", this._ambientTexture);
  39224. }
  39225. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39226. effect.setTexture("opacitySampler", this._opacityTexture);
  39227. }
  39228. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39229. if (this._reflectionTexture.isCube) {
  39230. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39231. }
  39232. else {
  39233. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39234. }
  39235. }
  39236. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39237. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39238. }
  39239. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39240. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39241. }
  39242. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39243. effect.setTexture("specularSampler", this._specularTexture);
  39244. }
  39245. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39246. effect.setTexture("bumpSampler", this._bumpTexture);
  39247. }
  39248. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39249. var depth = 1.0;
  39250. if (this._refractionTexture.isCube) {
  39251. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39252. }
  39253. else {
  39254. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39255. }
  39256. }
  39257. }
  39258. // Clip plane
  39259. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39260. // Colors
  39261. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39262. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39263. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39264. }
  39265. if (mustRebind || !this.isFrozen) {
  39266. // Lights
  39267. if (scene.lightsEnabled && !this._disableLighting) {
  39268. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39269. }
  39270. // View
  39271. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39272. this.bindView(effect);
  39273. }
  39274. // Fog
  39275. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39276. // Morph targets
  39277. if (defines.NUM_MORPH_INFLUENCERS) {
  39278. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39279. }
  39280. // Log. depth
  39281. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39282. // image processing
  39283. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39284. this._imageProcessingConfiguration.bind(this._activeEffect);
  39285. }
  39286. }
  39287. this._uniformBuffer.update();
  39288. this._afterBind(mesh, this._activeEffect);
  39289. };
  39290. StandardMaterial.prototype.getAnimatables = function () {
  39291. var results = [];
  39292. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39293. results.push(this._diffuseTexture);
  39294. }
  39295. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39296. results.push(this._ambientTexture);
  39297. }
  39298. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39299. results.push(this._opacityTexture);
  39300. }
  39301. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39302. results.push(this._reflectionTexture);
  39303. }
  39304. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39305. results.push(this._emissiveTexture);
  39306. }
  39307. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39308. results.push(this._specularTexture);
  39309. }
  39310. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39311. results.push(this._bumpTexture);
  39312. }
  39313. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39314. results.push(this._lightmapTexture);
  39315. }
  39316. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39317. results.push(this._refractionTexture);
  39318. }
  39319. return results;
  39320. };
  39321. StandardMaterial.prototype.getActiveTextures = function () {
  39322. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39323. if (this._diffuseTexture) {
  39324. activeTextures.push(this._diffuseTexture);
  39325. }
  39326. if (this._ambientTexture) {
  39327. activeTextures.push(this._ambientTexture);
  39328. }
  39329. if (this._opacityTexture) {
  39330. activeTextures.push(this._opacityTexture);
  39331. }
  39332. if (this._reflectionTexture) {
  39333. activeTextures.push(this._reflectionTexture);
  39334. }
  39335. if (this._emissiveTexture) {
  39336. activeTextures.push(this._emissiveTexture);
  39337. }
  39338. if (this._specularTexture) {
  39339. activeTextures.push(this._specularTexture);
  39340. }
  39341. if (this._bumpTexture) {
  39342. activeTextures.push(this._bumpTexture);
  39343. }
  39344. if (this._lightmapTexture) {
  39345. activeTextures.push(this._lightmapTexture);
  39346. }
  39347. if (this._refractionTexture) {
  39348. activeTextures.push(this._refractionTexture);
  39349. }
  39350. return activeTextures;
  39351. };
  39352. StandardMaterial.prototype.hasTexture = function (texture) {
  39353. if (_super.prototype.hasTexture.call(this, texture)) {
  39354. return true;
  39355. }
  39356. if (this._diffuseTexture === texture) {
  39357. return true;
  39358. }
  39359. if (this._ambientTexture === texture) {
  39360. return true;
  39361. }
  39362. if (this._opacityTexture === texture) {
  39363. return true;
  39364. }
  39365. if (this._reflectionTexture === texture) {
  39366. return true;
  39367. }
  39368. if (this._emissiveTexture === texture) {
  39369. return true;
  39370. }
  39371. if (this._specularTexture === texture) {
  39372. return true;
  39373. }
  39374. if (this._bumpTexture === texture) {
  39375. return true;
  39376. }
  39377. if (this._lightmapTexture === texture) {
  39378. return true;
  39379. }
  39380. if (this._refractionTexture === texture) {
  39381. return true;
  39382. }
  39383. return false;
  39384. };
  39385. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39386. if (forceDisposeTextures) {
  39387. if (this._diffuseTexture) {
  39388. this._diffuseTexture.dispose();
  39389. }
  39390. if (this._ambientTexture) {
  39391. this._ambientTexture.dispose();
  39392. }
  39393. if (this._opacityTexture) {
  39394. this._opacityTexture.dispose();
  39395. }
  39396. if (this._reflectionTexture) {
  39397. this._reflectionTexture.dispose();
  39398. }
  39399. if (this._emissiveTexture) {
  39400. this._emissiveTexture.dispose();
  39401. }
  39402. if (this._specularTexture) {
  39403. this._specularTexture.dispose();
  39404. }
  39405. if (this._bumpTexture) {
  39406. this._bumpTexture.dispose();
  39407. }
  39408. if (this._lightmapTexture) {
  39409. this._lightmapTexture.dispose();
  39410. }
  39411. if (this._refractionTexture) {
  39412. this._refractionTexture.dispose();
  39413. }
  39414. }
  39415. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39416. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39417. }
  39418. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39419. };
  39420. StandardMaterial.prototype.clone = function (name) {
  39421. var _this = this;
  39422. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39423. result.name = name;
  39424. result.id = name;
  39425. return result;
  39426. };
  39427. StandardMaterial.prototype.serialize = function () {
  39428. return BABYLON.SerializationHelper.Serialize(this);
  39429. };
  39430. // Statics
  39431. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39432. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39433. };
  39434. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39435. get: function () {
  39436. return StandardMaterial._DiffuseTextureEnabled;
  39437. },
  39438. set: function (value) {
  39439. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39440. return;
  39441. }
  39442. StandardMaterial._DiffuseTextureEnabled = value;
  39443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39444. },
  39445. enumerable: true,
  39446. configurable: true
  39447. });
  39448. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39449. get: function () {
  39450. return StandardMaterial._AmbientTextureEnabled;
  39451. },
  39452. set: function (value) {
  39453. if (StandardMaterial._AmbientTextureEnabled === value) {
  39454. return;
  39455. }
  39456. StandardMaterial._AmbientTextureEnabled = value;
  39457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39458. },
  39459. enumerable: true,
  39460. configurable: true
  39461. });
  39462. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39463. get: function () {
  39464. return StandardMaterial._OpacityTextureEnabled;
  39465. },
  39466. set: function (value) {
  39467. if (StandardMaterial._OpacityTextureEnabled === value) {
  39468. return;
  39469. }
  39470. StandardMaterial._OpacityTextureEnabled = value;
  39471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39472. },
  39473. enumerable: true,
  39474. configurable: true
  39475. });
  39476. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39477. get: function () {
  39478. return StandardMaterial._ReflectionTextureEnabled;
  39479. },
  39480. set: function (value) {
  39481. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39482. return;
  39483. }
  39484. StandardMaterial._ReflectionTextureEnabled = value;
  39485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39486. },
  39487. enumerable: true,
  39488. configurable: true
  39489. });
  39490. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39491. get: function () {
  39492. return StandardMaterial._EmissiveTextureEnabled;
  39493. },
  39494. set: function (value) {
  39495. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39496. return;
  39497. }
  39498. StandardMaterial._EmissiveTextureEnabled = value;
  39499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39500. },
  39501. enumerable: true,
  39502. configurable: true
  39503. });
  39504. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39505. get: function () {
  39506. return StandardMaterial._SpecularTextureEnabled;
  39507. },
  39508. set: function (value) {
  39509. if (StandardMaterial._SpecularTextureEnabled === value) {
  39510. return;
  39511. }
  39512. StandardMaterial._SpecularTextureEnabled = value;
  39513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39519. get: function () {
  39520. return StandardMaterial._BumpTextureEnabled;
  39521. },
  39522. set: function (value) {
  39523. if (StandardMaterial._BumpTextureEnabled === value) {
  39524. return;
  39525. }
  39526. StandardMaterial._BumpTextureEnabled = value;
  39527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39533. get: function () {
  39534. return StandardMaterial._LightmapTextureEnabled;
  39535. },
  39536. set: function (value) {
  39537. if (StandardMaterial._LightmapTextureEnabled === value) {
  39538. return;
  39539. }
  39540. StandardMaterial._LightmapTextureEnabled = value;
  39541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39547. get: function () {
  39548. return StandardMaterial._RefractionTextureEnabled;
  39549. },
  39550. set: function (value) {
  39551. if (StandardMaterial._RefractionTextureEnabled === value) {
  39552. return;
  39553. }
  39554. StandardMaterial._RefractionTextureEnabled = value;
  39555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39556. },
  39557. enumerable: true,
  39558. configurable: true
  39559. });
  39560. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39561. get: function () {
  39562. return StandardMaterial._ColorGradingTextureEnabled;
  39563. },
  39564. set: function (value) {
  39565. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39566. return;
  39567. }
  39568. StandardMaterial._ColorGradingTextureEnabled = value;
  39569. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39570. },
  39571. enumerable: true,
  39572. configurable: true
  39573. });
  39574. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39575. get: function () {
  39576. return StandardMaterial._FresnelEnabled;
  39577. },
  39578. set: function (value) {
  39579. if (StandardMaterial._FresnelEnabled === value) {
  39580. return;
  39581. }
  39582. StandardMaterial._FresnelEnabled = value;
  39583. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39584. },
  39585. enumerable: true,
  39586. configurable: true
  39587. });
  39588. // Flags used to enable or disable a type of texture for all Standard Materials
  39589. StandardMaterial._DiffuseTextureEnabled = true;
  39590. StandardMaterial._AmbientTextureEnabled = true;
  39591. StandardMaterial._OpacityTextureEnabled = true;
  39592. StandardMaterial._ReflectionTextureEnabled = true;
  39593. StandardMaterial._EmissiveTextureEnabled = true;
  39594. StandardMaterial._SpecularTextureEnabled = true;
  39595. StandardMaterial._BumpTextureEnabled = true;
  39596. StandardMaterial._LightmapTextureEnabled = true;
  39597. StandardMaterial._RefractionTextureEnabled = true;
  39598. StandardMaterial._ColorGradingTextureEnabled = true;
  39599. StandardMaterial._FresnelEnabled = true;
  39600. __decorate([
  39601. BABYLON.serializeAsTexture("diffuseTexture")
  39602. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39603. __decorate([
  39604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39605. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39606. __decorate([
  39607. BABYLON.serializeAsTexture("ambientTexture")
  39608. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39609. __decorate([
  39610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39611. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39612. __decorate([
  39613. BABYLON.serializeAsTexture("opacityTexture")
  39614. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39615. __decorate([
  39616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39617. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39618. __decorate([
  39619. BABYLON.serializeAsTexture("reflectionTexture")
  39620. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39621. __decorate([
  39622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39623. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39624. __decorate([
  39625. BABYLON.serializeAsTexture("emissiveTexture")
  39626. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39627. __decorate([
  39628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39629. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39630. __decorate([
  39631. BABYLON.serializeAsTexture("specularTexture")
  39632. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39633. __decorate([
  39634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39635. ], StandardMaterial.prototype, "specularTexture", void 0);
  39636. __decorate([
  39637. BABYLON.serializeAsTexture("bumpTexture")
  39638. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39639. __decorate([
  39640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39641. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39642. __decorate([
  39643. BABYLON.serializeAsTexture("lightmapTexture")
  39644. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39645. __decorate([
  39646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39647. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39648. __decorate([
  39649. BABYLON.serializeAsTexture("refractionTexture")
  39650. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39651. __decorate([
  39652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39653. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39654. __decorate([
  39655. BABYLON.serializeAsColor3("ambient")
  39656. ], StandardMaterial.prototype, "ambientColor", void 0);
  39657. __decorate([
  39658. BABYLON.serializeAsColor3("diffuse")
  39659. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39660. __decorate([
  39661. BABYLON.serializeAsColor3("specular")
  39662. ], StandardMaterial.prototype, "specularColor", void 0);
  39663. __decorate([
  39664. BABYLON.serializeAsColor3("emissive")
  39665. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39666. __decorate([
  39667. BABYLON.serialize()
  39668. ], StandardMaterial.prototype, "specularPower", void 0);
  39669. __decorate([
  39670. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39671. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39672. __decorate([
  39673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39674. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39675. __decorate([
  39676. BABYLON.serialize("useEmissiveAsIllumination")
  39677. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39678. __decorate([
  39679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39680. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39681. __decorate([
  39682. BABYLON.serialize("linkEmissiveWithDiffuse")
  39683. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39684. __decorate([
  39685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39686. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39687. __decorate([
  39688. BABYLON.serialize("useSpecularOverAlpha")
  39689. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39690. __decorate([
  39691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39692. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39693. __decorate([
  39694. BABYLON.serialize("useReflectionOverAlpha")
  39695. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39696. __decorate([
  39697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39698. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39699. __decorate([
  39700. BABYLON.serialize("disableLighting")
  39701. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39702. __decorate([
  39703. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39704. ], StandardMaterial.prototype, "disableLighting", void 0);
  39705. __decorate([
  39706. BABYLON.serialize("useObjectSpaceNormalMap")
  39707. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39708. __decorate([
  39709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39710. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39711. __decorate([
  39712. BABYLON.serialize("useParallax")
  39713. ], StandardMaterial.prototype, "_useParallax", void 0);
  39714. __decorate([
  39715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39716. ], StandardMaterial.prototype, "useParallax", void 0);
  39717. __decorate([
  39718. BABYLON.serialize("useParallaxOcclusion")
  39719. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39720. __decorate([
  39721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39722. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39723. __decorate([
  39724. BABYLON.serialize()
  39725. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39726. __decorate([
  39727. BABYLON.serialize("roughness")
  39728. ], StandardMaterial.prototype, "_roughness", void 0);
  39729. __decorate([
  39730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39731. ], StandardMaterial.prototype, "roughness", void 0);
  39732. __decorate([
  39733. BABYLON.serialize()
  39734. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39735. __decorate([
  39736. BABYLON.serialize()
  39737. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39738. __decorate([
  39739. BABYLON.serialize("useLightmapAsShadowmap")
  39740. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39741. __decorate([
  39742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39743. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39744. __decorate([
  39745. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39746. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39747. __decorate([
  39748. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39749. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39750. __decorate([
  39751. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39752. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39753. __decorate([
  39754. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39755. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39756. __decorate([
  39757. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39758. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39759. __decorate([
  39760. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39761. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39762. __decorate([
  39763. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39764. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39765. __decorate([
  39766. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39767. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39768. __decorate([
  39769. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39770. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39771. __decorate([
  39772. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39773. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39774. __decorate([
  39775. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39776. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39777. __decorate([
  39778. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39779. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39780. __decorate([
  39781. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39782. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39783. __decorate([
  39784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39785. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39786. __decorate([
  39787. BABYLON.serialize("maxSimultaneousLights")
  39788. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39789. __decorate([
  39790. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39791. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39792. __decorate([
  39793. BABYLON.serialize("invertNormalMapX")
  39794. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39795. __decorate([
  39796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39797. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39798. __decorate([
  39799. BABYLON.serialize("invertNormalMapY")
  39800. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39801. __decorate([
  39802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39803. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39804. __decorate([
  39805. BABYLON.serialize("twoSidedLighting")
  39806. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39807. __decorate([
  39808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39809. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39810. __decorate([
  39811. BABYLON.serialize()
  39812. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39813. return StandardMaterial;
  39814. }(BABYLON.PushMaterial));
  39815. BABYLON.StandardMaterial = StandardMaterial;
  39816. })(BABYLON || (BABYLON = {}));
  39817. //# sourceMappingURL=babylon.standardMaterial.js.map
  39818. var BABYLON;
  39819. (function (BABYLON) {
  39820. /**
  39821. * Manages the defines for the PBR Material.
  39822. */
  39823. var PBRMaterialDefines = /** @class */ (function (_super) {
  39824. __extends(PBRMaterialDefines, _super);
  39825. /**
  39826. * Initializes the PBR Material defines.
  39827. */
  39828. function PBRMaterialDefines() {
  39829. var _this = _super.call(this) || this;
  39830. _this.PBR = true;
  39831. _this.MAINUV1 = false;
  39832. _this.MAINUV2 = false;
  39833. _this.UV1 = false;
  39834. _this.UV2 = false;
  39835. _this.ALBEDO = false;
  39836. _this.ALBEDODIRECTUV = 0;
  39837. _this.VERTEXCOLOR = false;
  39838. _this.AMBIENT = false;
  39839. _this.AMBIENTDIRECTUV = 0;
  39840. _this.AMBIENTINGRAYSCALE = false;
  39841. _this.OPACITY = false;
  39842. _this.VERTEXALPHA = false;
  39843. _this.OPACITYDIRECTUV = 0;
  39844. _this.OPACITYRGB = false;
  39845. _this.ALPHATEST = false;
  39846. _this.DEPTHPREPASS = false;
  39847. _this.ALPHABLEND = false;
  39848. _this.ALPHAFROMALBEDO = false;
  39849. _this.ALPHATESTVALUE = 0.5;
  39850. _this.SPECULAROVERALPHA = false;
  39851. _this.RADIANCEOVERALPHA = false;
  39852. _this.ALPHAFRESNEL = false;
  39853. _this.LINEARALPHAFRESNEL = false;
  39854. _this.PREMULTIPLYALPHA = false;
  39855. _this.EMISSIVE = false;
  39856. _this.EMISSIVEDIRECTUV = 0;
  39857. _this.REFLECTIVITY = false;
  39858. _this.REFLECTIVITYDIRECTUV = 0;
  39859. _this.SPECULARTERM = false;
  39860. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39861. _this.MICROSURFACEAUTOMATIC = false;
  39862. _this.LODBASEDMICROSFURACE = false;
  39863. _this.MICROSURFACEMAP = false;
  39864. _this.MICROSURFACEMAPDIRECTUV = 0;
  39865. _this.METALLICWORKFLOW = false;
  39866. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39867. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39868. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39869. _this.AOSTOREINMETALMAPRED = false;
  39870. _this.ENVIRONMENTBRDF = false;
  39871. _this.NORMAL = false;
  39872. _this.TANGENT = false;
  39873. _this.BUMP = false;
  39874. _this.BUMPDIRECTUV = 0;
  39875. _this.OBJECTSPACE_NORMALMAP = false;
  39876. _this.PARALLAX = false;
  39877. _this.PARALLAXOCCLUSION = false;
  39878. _this.NORMALXYSCALE = true;
  39879. _this.LIGHTMAP = false;
  39880. _this.LIGHTMAPDIRECTUV = 0;
  39881. _this.USELIGHTMAPASSHADOWMAP = false;
  39882. _this.REFLECTION = false;
  39883. _this.REFLECTIONMAP_3D = false;
  39884. _this.REFLECTIONMAP_SPHERICAL = false;
  39885. _this.REFLECTIONMAP_PLANAR = false;
  39886. _this.REFLECTIONMAP_CUBIC = false;
  39887. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39888. _this.REFLECTIONMAP_PROJECTION = false;
  39889. _this.REFLECTIONMAP_SKYBOX = false;
  39890. _this.REFLECTIONMAP_EXPLICIT = false;
  39891. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39892. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39893. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39894. _this.INVERTCUBICMAP = false;
  39895. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39896. _this.USESPHERICALINVERTEX = false;
  39897. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39898. _this.LODINREFLECTIONALPHA = false;
  39899. _this.GAMMAREFLECTION = false;
  39900. _this.RADIANCEOCCLUSION = false;
  39901. _this.HORIZONOCCLUSION = false;
  39902. _this.REFRACTION = false;
  39903. _this.REFRACTIONMAP_3D = false;
  39904. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39905. _this.LODINREFRACTIONALPHA = false;
  39906. _this.GAMMAREFRACTION = false;
  39907. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39908. _this.INSTANCES = false;
  39909. _this.NUM_BONE_INFLUENCERS = 0;
  39910. _this.BonesPerMesh = 0;
  39911. _this.NONUNIFORMSCALING = false;
  39912. _this.MORPHTARGETS = false;
  39913. _this.MORPHTARGETS_NORMAL = false;
  39914. _this.MORPHTARGETS_TANGENT = false;
  39915. _this.NUM_MORPH_INFLUENCERS = 0;
  39916. _this.IMAGEPROCESSING = false;
  39917. _this.VIGNETTE = false;
  39918. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39919. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39920. _this.TONEMAPPING = false;
  39921. _this.CONTRAST = false;
  39922. _this.COLORCURVES = false;
  39923. _this.COLORGRADING = false;
  39924. _this.COLORGRADING3D = false;
  39925. _this.SAMPLER3DGREENDEPTH = false;
  39926. _this.SAMPLER3DBGRMAP = false;
  39927. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39928. _this.EXPOSURE = false;
  39929. _this.USEPHYSICALLIGHTFALLOFF = false;
  39930. _this.TWOSIDEDLIGHTING = false;
  39931. _this.SHADOWFLOAT = false;
  39932. _this.CLIPPLANE = false;
  39933. _this.POINTSIZE = false;
  39934. _this.FOG = false;
  39935. _this.LOGARITHMICDEPTH = false;
  39936. _this.FORCENORMALFORWARD = false;
  39937. _this.rebuild();
  39938. return _this;
  39939. }
  39940. /**
  39941. * Resets the PBR Material defines.
  39942. */
  39943. PBRMaterialDefines.prototype.reset = function () {
  39944. _super.prototype.reset.call(this);
  39945. this.ALPHATESTVALUE = 0.5;
  39946. this.PBR = true;
  39947. };
  39948. return PBRMaterialDefines;
  39949. }(BABYLON.MaterialDefines));
  39950. /**
  39951. * The Physically based material base class of BJS.
  39952. *
  39953. * This offers the main features of a standard PBR material.
  39954. * For more information, please refer to the documentation :
  39955. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39956. */
  39957. var PBRBaseMaterial = /** @class */ (function (_super) {
  39958. __extends(PBRBaseMaterial, _super);
  39959. /**
  39960. * Instantiates a new PBRMaterial instance.
  39961. *
  39962. * @param name The material name
  39963. * @param scene The scene the material will be use in.
  39964. */
  39965. function PBRBaseMaterial(name, scene) {
  39966. var _this = _super.call(this, name, scene) || this;
  39967. /**
  39968. * Intensity of the direct lights e.g. the four lights available in your scene.
  39969. * This impacts both the direct diffuse and specular highlights.
  39970. */
  39971. _this._directIntensity = 1.0;
  39972. /**
  39973. * Intensity of the emissive part of the material.
  39974. * This helps controlling the emissive effect without modifying the emissive color.
  39975. */
  39976. _this._emissiveIntensity = 1.0;
  39977. /**
  39978. * Intensity of the environment e.g. how much the environment will light the object
  39979. * either through harmonics for rough material or through the refelction for shiny ones.
  39980. */
  39981. _this._environmentIntensity = 1.0;
  39982. /**
  39983. * This is a special control allowing the reduction of the specular highlights coming from the
  39984. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39985. */
  39986. _this._specularIntensity = 1.0;
  39987. /**
  39988. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39989. */
  39990. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39991. /**
  39992. * Debug Control allowing disabling the bump map on this material.
  39993. */
  39994. _this._disableBumpMap = false;
  39995. /**
  39996. * AKA Occlusion Texture Intensity in other nomenclature.
  39997. */
  39998. _this._ambientTextureStrength = 1.0;
  39999. /**
  40000. * The color of a material in ambient lighting.
  40001. */
  40002. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40003. /**
  40004. * AKA Diffuse Color in other nomenclature.
  40005. */
  40006. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40007. /**
  40008. * AKA Specular Color in other nomenclature.
  40009. */
  40010. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40011. /**
  40012. * The color applied when light is reflected from a material.
  40013. */
  40014. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40015. /**
  40016. * The color applied when light is emitted from a material.
  40017. */
  40018. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40019. /**
  40020. * AKA Glossiness in other nomenclature.
  40021. */
  40022. _this._microSurface = 0.9;
  40023. /**
  40024. * source material index of refraction (IOR)' / 'destination material IOR.
  40025. */
  40026. _this._indexOfRefraction = 0.66;
  40027. /**
  40028. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40029. */
  40030. _this._invertRefractionY = false;
  40031. /**
  40032. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40033. * Materials half opaque for instance using refraction could benefit from this control.
  40034. */
  40035. _this._linkRefractionWithTransparency = false;
  40036. /**
  40037. * Specifies that the material will use the light map as a show map.
  40038. */
  40039. _this._useLightmapAsShadowmap = false;
  40040. /**
  40041. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40042. * makes the reflect vector face the model (under horizon).
  40043. */
  40044. _this._useHorizonOcclusion = true;
  40045. /**
  40046. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40047. * too much the area relying on ambient texture to define their ambient occlusion.
  40048. */
  40049. _this._useRadianceOcclusion = true;
  40050. /**
  40051. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40052. */
  40053. _this._useAlphaFromAlbedoTexture = false;
  40054. /**
  40055. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40056. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40057. */
  40058. _this._useSpecularOverAlpha = true;
  40059. /**
  40060. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40061. */
  40062. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40063. /**
  40064. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40065. */
  40066. _this._useRoughnessFromMetallicTextureAlpha = true;
  40067. /**
  40068. * Specifies if the metallic texture contains the roughness information in its green channel.
  40069. */
  40070. _this._useRoughnessFromMetallicTextureGreen = false;
  40071. /**
  40072. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40073. */
  40074. _this._useMetallnessFromMetallicTextureBlue = false;
  40075. /**
  40076. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40077. */
  40078. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40079. /**
  40080. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40081. */
  40082. _this._useAmbientInGrayScale = false;
  40083. /**
  40084. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40085. * The material will try to infer what glossiness each pixel should be.
  40086. */
  40087. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40088. /**
  40089. * BJS is using an harcoded light falloff based on a manually sets up range.
  40090. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40091. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40092. */
  40093. _this._usePhysicalLightFalloff = true;
  40094. /**
  40095. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40096. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40097. */
  40098. _this._useRadianceOverAlpha = true;
  40099. /**
  40100. * Allows using an object space normal map (instead of tangent space).
  40101. */
  40102. _this._useObjectSpaceNormalMap = false;
  40103. /**
  40104. * Allows using the bump map in parallax mode.
  40105. */
  40106. _this._useParallax = false;
  40107. /**
  40108. * Allows using the bump map in parallax occlusion mode.
  40109. */
  40110. _this._useParallaxOcclusion = false;
  40111. /**
  40112. * Controls the scale bias of the parallax mode.
  40113. */
  40114. _this._parallaxScaleBias = 0.05;
  40115. /**
  40116. * If sets to true, disables all the lights affecting the material.
  40117. */
  40118. _this._disableLighting = false;
  40119. /**
  40120. * Number of Simultaneous lights allowed on the material.
  40121. */
  40122. _this._maxSimultaneousLights = 4;
  40123. /**
  40124. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40125. */
  40126. _this._invertNormalMapX = false;
  40127. /**
  40128. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40129. */
  40130. _this._invertNormalMapY = false;
  40131. /**
  40132. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40133. */
  40134. _this._twoSidedLighting = false;
  40135. /**
  40136. * Defines the alpha limits in alpha test mode.
  40137. */
  40138. _this._alphaCutOff = 0.4;
  40139. /**
  40140. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40141. */
  40142. _this._forceAlphaTest = false;
  40143. /**
  40144. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40145. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40146. */
  40147. _this._useAlphaFresnel = false;
  40148. /**
  40149. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40150. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40151. */
  40152. _this._useLinearAlphaFresnel = false;
  40153. /**
  40154. * The transparency mode of the material.
  40155. */
  40156. _this._transparencyMode = null;
  40157. /**
  40158. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40159. * from cos thetav and roughness:
  40160. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40161. */
  40162. _this._environmentBRDFTexture = null;
  40163. /**
  40164. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40165. */
  40166. _this._forceIrradianceInFragment = false;
  40167. /**
  40168. * Force normal to face away from face.
  40169. */
  40170. _this._forceNormalForward = false;
  40171. /**
  40172. * Force metallic workflow.
  40173. */
  40174. _this._forceMetallicWorkflow = false;
  40175. /**
  40176. * Stores the available render targets.
  40177. */
  40178. _this._renderTargets = new BABYLON.SmartArray(16);
  40179. /**
  40180. * Sets the global ambient color for the material used in lighting calculations.
  40181. */
  40182. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40183. // Setup the default processing configuration to the scene.
  40184. _this._attachImageProcessingConfiguration(null);
  40185. _this.getRenderTargetTextures = function () {
  40186. _this._renderTargets.reset();
  40187. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40188. _this._renderTargets.push(_this._reflectionTexture);
  40189. }
  40190. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40191. _this._renderTargets.push(_this._refractionTexture);
  40192. }
  40193. return _this._renderTargets;
  40194. };
  40195. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40196. return _this;
  40197. }
  40198. /**
  40199. * Attaches a new image processing configuration to the PBR Material.
  40200. * @param configuration
  40201. */
  40202. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40203. var _this = this;
  40204. if (configuration === this._imageProcessingConfiguration) {
  40205. return;
  40206. }
  40207. // Detaches observer.
  40208. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40209. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40210. }
  40211. // Pick the scene configuration if needed.
  40212. if (!configuration) {
  40213. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40214. }
  40215. else {
  40216. this._imageProcessingConfiguration = configuration;
  40217. }
  40218. // Attaches observer.
  40219. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40220. _this._markAllSubMeshesAsImageProcessingDirty();
  40221. });
  40222. };
  40223. /**
  40224. * Gets the name of the material class.
  40225. */
  40226. PBRBaseMaterial.prototype.getClassName = function () {
  40227. return "PBRBaseMaterial";
  40228. };
  40229. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40230. /**
  40231. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40232. */
  40233. get: function () {
  40234. return this._useLogarithmicDepth;
  40235. },
  40236. /**
  40237. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40238. */
  40239. set: function (value) {
  40240. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40241. },
  40242. enumerable: true,
  40243. configurable: true
  40244. });
  40245. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40246. /**
  40247. * Gets the current transparency mode.
  40248. */
  40249. get: function () {
  40250. return this._transparencyMode;
  40251. },
  40252. /**
  40253. * Sets the transparency mode of the material.
  40254. */
  40255. set: function (value) {
  40256. if (this._transparencyMode === value) {
  40257. return;
  40258. }
  40259. this._transparencyMode = value;
  40260. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40261. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40262. },
  40263. enumerable: true,
  40264. configurable: true
  40265. });
  40266. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40267. /**
  40268. * Returns true if alpha blending should be disabled.
  40269. */
  40270. get: function () {
  40271. return (this._linkRefractionWithTransparency ||
  40272. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40273. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40274. },
  40275. enumerable: true,
  40276. configurable: true
  40277. });
  40278. /**
  40279. * Specifies whether or not this material should be rendered in alpha blend mode.
  40280. */
  40281. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40282. if (this._disableAlphaBlending) {
  40283. return false;
  40284. }
  40285. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40286. };
  40287. /**
  40288. * Specifies if the mesh will require alpha blending.
  40289. * @param mesh - BJS mesh.
  40290. */
  40291. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40292. if (this._disableAlphaBlending) {
  40293. return false;
  40294. }
  40295. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40296. };
  40297. /**
  40298. * Specifies whether or not this material should be rendered in alpha test mode.
  40299. */
  40300. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40301. if (this._forceAlphaTest) {
  40302. return true;
  40303. }
  40304. if (this._linkRefractionWithTransparency) {
  40305. return false;
  40306. }
  40307. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40308. };
  40309. /**
  40310. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40311. */
  40312. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40313. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40314. };
  40315. /**
  40316. * Gets the texture used for the alpha test.
  40317. */
  40318. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40319. return this._albedoTexture;
  40320. };
  40321. /**
  40322. * Specifies that the submesh is ready to be used.
  40323. * @param mesh - BJS mesh.
  40324. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40325. * @param useInstances - Specifies that instances should be used.
  40326. * @returns - boolean indicating that the submesh is ready or not.
  40327. */
  40328. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40329. if (subMesh.effect && this.isFrozen) {
  40330. if (this._wasPreviouslyReady) {
  40331. return true;
  40332. }
  40333. }
  40334. if (!subMesh._materialDefines) {
  40335. subMesh._materialDefines = new PBRMaterialDefines();
  40336. }
  40337. var defines = subMesh._materialDefines;
  40338. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40339. if (defines._renderId === this.getScene().getRenderId()) {
  40340. return true;
  40341. }
  40342. }
  40343. var scene = this.getScene();
  40344. var engine = scene.getEngine();
  40345. if (defines._areTexturesDirty) {
  40346. if (scene.texturesEnabled) {
  40347. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40348. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40349. return false;
  40350. }
  40351. }
  40352. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40353. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40354. return false;
  40355. }
  40356. }
  40357. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40358. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40359. return false;
  40360. }
  40361. }
  40362. var reflectionTexture = this._getReflectionTexture();
  40363. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40364. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40365. return false;
  40366. }
  40367. }
  40368. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40369. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40370. return false;
  40371. }
  40372. }
  40373. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40374. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40375. return false;
  40376. }
  40377. }
  40378. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40379. if (this._metallicTexture) {
  40380. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40381. return false;
  40382. }
  40383. }
  40384. else if (this._reflectivityTexture) {
  40385. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40386. return false;
  40387. }
  40388. }
  40389. if (this._microSurfaceTexture) {
  40390. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40391. return false;
  40392. }
  40393. }
  40394. }
  40395. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40396. // Bump texture cannot be not blocking.
  40397. if (!this._bumpTexture.isReady()) {
  40398. return false;
  40399. }
  40400. }
  40401. var refractionTexture = this._getRefractionTexture();
  40402. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40403. if (!refractionTexture.isReadyOrNotBlocking()) {
  40404. return false;
  40405. }
  40406. }
  40407. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40408. // This is blocking.
  40409. if (!this._environmentBRDFTexture.isReady()) {
  40410. return false;
  40411. }
  40412. }
  40413. }
  40414. }
  40415. if (defines._areImageProcessingDirty) {
  40416. if (!this._imageProcessingConfiguration.isReady()) {
  40417. return false;
  40418. }
  40419. }
  40420. if (!engine.getCaps().standardDerivatives) {
  40421. var bufferMesh = null;
  40422. if (mesh.getClassName() === "InstancedMesh") {
  40423. bufferMesh = mesh.sourceMesh;
  40424. }
  40425. else if (mesh.getClassName() === "Mesh") {
  40426. bufferMesh = mesh;
  40427. }
  40428. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40429. bufferMesh.createNormals(true);
  40430. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40431. }
  40432. }
  40433. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40434. if (effect) {
  40435. scene.resetCachedMaterial();
  40436. subMesh.setEffect(effect, defines);
  40437. this.buildUniformLayout();
  40438. }
  40439. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40440. return false;
  40441. }
  40442. defines._renderId = scene.getRenderId();
  40443. this._wasPreviouslyReady = true;
  40444. return true;
  40445. };
  40446. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40447. if (onCompiled === void 0) { onCompiled = null; }
  40448. if (onError === void 0) { onError = null; }
  40449. if (useInstances === void 0) { useInstances = null; }
  40450. if (useClipPlane === void 0) { useClipPlane = null; }
  40451. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40452. if (!defines.isDirty) {
  40453. return null;
  40454. }
  40455. defines.markAsProcessed();
  40456. var scene = this.getScene();
  40457. var engine = scene.getEngine();
  40458. // Fallbacks
  40459. var fallbacks = new BABYLON.EffectFallbacks();
  40460. var fallbackRank = 0;
  40461. if (defines.USESPHERICALINVERTEX) {
  40462. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40463. }
  40464. if (defines.FOG) {
  40465. fallbacks.addFallback(fallbackRank, "FOG");
  40466. }
  40467. if (defines.POINTSIZE) {
  40468. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40469. }
  40470. if (defines.LOGARITHMICDEPTH) {
  40471. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40472. }
  40473. if (defines.PARALLAX) {
  40474. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40475. }
  40476. if (defines.PARALLAXOCCLUSION) {
  40477. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40478. }
  40479. if (defines.ENVIRONMENTBRDF) {
  40480. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40481. }
  40482. if (defines.TANGENT) {
  40483. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40484. }
  40485. if (defines.BUMP) {
  40486. fallbacks.addFallback(fallbackRank++, "BUMP");
  40487. }
  40488. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40489. if (defines.SPECULARTERM) {
  40490. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40491. }
  40492. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40493. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40494. }
  40495. if (defines.LIGHTMAP) {
  40496. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40497. }
  40498. if (defines.NORMAL) {
  40499. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40500. }
  40501. if (defines.AMBIENT) {
  40502. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40503. }
  40504. if (defines.EMISSIVE) {
  40505. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40506. }
  40507. if (defines.VERTEXCOLOR) {
  40508. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40509. }
  40510. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40511. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40512. }
  40513. if (defines.MORPHTARGETS) {
  40514. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40515. }
  40516. //Attributes
  40517. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40518. if (defines.NORMAL) {
  40519. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40520. }
  40521. if (defines.TANGENT) {
  40522. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40523. }
  40524. if (defines.UV1) {
  40525. attribs.push(BABYLON.VertexBuffer.UVKind);
  40526. }
  40527. if (defines.UV2) {
  40528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40529. }
  40530. if (defines.VERTEXCOLOR) {
  40531. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40532. }
  40533. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40534. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40535. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40536. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40537. "vFogInfos", "vFogColor", "pointSize",
  40538. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40539. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40540. "mBones",
  40541. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40542. "vLightingIntensity",
  40543. "logarithmicDepthConstant",
  40544. "vSphericalX", "vSphericalY", "vSphericalZ",
  40545. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40546. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40547. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40548. "vTangentSpaceParams"
  40549. ];
  40550. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40551. "bumpSampler", "lightmapSampler", "opacitySampler",
  40552. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40553. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40554. "microSurfaceSampler", "environmentBrdfSampler"];
  40555. var uniformBuffers = ["Material", "Scene"];
  40556. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40557. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40558. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40559. uniformsNames: uniforms,
  40560. uniformBuffersNames: uniformBuffers,
  40561. samplers: samplers,
  40562. defines: defines,
  40563. maxSimultaneousLights: this._maxSimultaneousLights
  40564. });
  40565. var join = defines.toString();
  40566. return engine.createEffect("pbr", {
  40567. attributes: attribs,
  40568. uniformsNames: uniforms,
  40569. uniformBuffersNames: uniformBuffers,
  40570. samplers: samplers,
  40571. defines: join,
  40572. fallbacks: fallbacks,
  40573. onCompiled: onCompiled,
  40574. onError: onError,
  40575. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40576. }, engine);
  40577. };
  40578. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40579. if (useInstances === void 0) { useInstances = null; }
  40580. if (useClipPlane === void 0) { useClipPlane = null; }
  40581. var scene = this.getScene();
  40582. var engine = scene.getEngine();
  40583. // Lights
  40584. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40585. defines._needNormals = true;
  40586. // Textures
  40587. if (defines._areTexturesDirty) {
  40588. defines._needUVs = false;
  40589. if (scene.texturesEnabled) {
  40590. if (scene.getEngine().getCaps().textureLOD) {
  40591. defines.LODBASEDMICROSFURACE = true;
  40592. }
  40593. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40594. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40595. }
  40596. else {
  40597. defines.ALBEDO = false;
  40598. }
  40599. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40600. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40601. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40602. }
  40603. else {
  40604. defines.AMBIENT = false;
  40605. }
  40606. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40608. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40609. }
  40610. else {
  40611. defines.OPACITY = false;
  40612. }
  40613. var reflectionTexture = this._getReflectionTexture();
  40614. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40615. defines.REFLECTION = true;
  40616. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40617. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40618. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40619. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40620. defines.INVERTCUBICMAP = true;
  40621. }
  40622. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40623. switch (reflectionTexture.coordinatesMode) {
  40624. case BABYLON.Texture.CUBIC_MODE:
  40625. case BABYLON.Texture.INVCUBIC_MODE:
  40626. defines.REFLECTIONMAP_CUBIC = true;
  40627. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40628. break;
  40629. case BABYLON.Texture.EXPLICIT_MODE:
  40630. defines.REFLECTIONMAP_EXPLICIT = true;
  40631. break;
  40632. case BABYLON.Texture.PLANAR_MODE:
  40633. defines.REFLECTIONMAP_PLANAR = true;
  40634. break;
  40635. case BABYLON.Texture.PROJECTION_MODE:
  40636. defines.REFLECTIONMAP_PROJECTION = true;
  40637. break;
  40638. case BABYLON.Texture.SKYBOX_MODE:
  40639. defines.REFLECTIONMAP_SKYBOX = true;
  40640. break;
  40641. case BABYLON.Texture.SPHERICAL_MODE:
  40642. defines.REFLECTIONMAP_SPHERICAL = true;
  40643. break;
  40644. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40645. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40646. break;
  40647. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40648. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40649. break;
  40650. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40651. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40652. break;
  40653. }
  40654. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40655. if (reflectionTexture.sphericalPolynomial) {
  40656. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40657. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40658. defines.USESPHERICALINVERTEX = false;
  40659. }
  40660. else {
  40661. defines.USESPHERICALINVERTEX = true;
  40662. }
  40663. }
  40664. }
  40665. }
  40666. else {
  40667. defines.REFLECTION = false;
  40668. defines.REFLECTIONMAP_3D = false;
  40669. defines.REFLECTIONMAP_SPHERICAL = false;
  40670. defines.REFLECTIONMAP_PLANAR = false;
  40671. defines.REFLECTIONMAP_CUBIC = false;
  40672. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40673. defines.REFLECTIONMAP_PROJECTION = false;
  40674. defines.REFLECTIONMAP_SKYBOX = false;
  40675. defines.REFLECTIONMAP_EXPLICIT = false;
  40676. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40677. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40678. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40679. defines.INVERTCUBICMAP = false;
  40680. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40681. defines.USESPHERICALINVERTEX = false;
  40682. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40683. defines.LODINREFLECTIONALPHA = false;
  40684. defines.GAMMAREFLECTION = false;
  40685. }
  40686. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40687. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40688. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40689. }
  40690. else {
  40691. defines.LIGHTMAP = false;
  40692. }
  40693. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40694. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40695. }
  40696. else {
  40697. defines.EMISSIVE = false;
  40698. }
  40699. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40700. if (this._metallicTexture) {
  40701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40702. defines.METALLICWORKFLOW = true;
  40703. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40704. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40705. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40706. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40707. }
  40708. else if (this._reflectivityTexture) {
  40709. defines.METALLICWORKFLOW = false;
  40710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40711. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40712. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40713. }
  40714. else {
  40715. defines.METALLICWORKFLOW = false;
  40716. defines.REFLECTIVITY = false;
  40717. }
  40718. if (this._microSurfaceTexture) {
  40719. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40720. }
  40721. else {
  40722. defines.MICROSURFACEMAP = false;
  40723. }
  40724. }
  40725. else {
  40726. defines.REFLECTIVITY = false;
  40727. defines.MICROSURFACEMAP = false;
  40728. }
  40729. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40731. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40732. defines.PARALLAX = true;
  40733. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40734. }
  40735. else {
  40736. defines.PARALLAX = false;
  40737. }
  40738. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40739. }
  40740. else {
  40741. defines.BUMP = false;
  40742. }
  40743. var refractionTexture = this._getRefractionTexture();
  40744. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40745. defines.REFRACTION = true;
  40746. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40747. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40748. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40749. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40750. if (this._linkRefractionWithTransparency) {
  40751. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40752. }
  40753. }
  40754. else {
  40755. defines.REFRACTION = false;
  40756. }
  40757. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40758. defines.ENVIRONMENTBRDF = true;
  40759. }
  40760. else {
  40761. defines.ENVIRONMENTBRDF = false;
  40762. }
  40763. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40764. defines.ALPHAFROMALBEDO = true;
  40765. }
  40766. else {
  40767. defines.ALPHAFROMALBEDO = false;
  40768. }
  40769. }
  40770. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40771. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40772. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40773. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40774. defines.METALLICWORKFLOW = true;
  40775. }
  40776. else {
  40777. defines.METALLICWORKFLOW = false;
  40778. }
  40779. if (!this.backFaceCulling && this._twoSidedLighting) {
  40780. defines.TWOSIDEDLIGHTING = true;
  40781. }
  40782. else {
  40783. defines.TWOSIDEDLIGHTING = false;
  40784. }
  40785. defines.ALPHATESTVALUE = this._alphaCutOff;
  40786. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40787. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40788. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40789. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40790. }
  40791. if (defines._areImageProcessingDirty) {
  40792. this._imageProcessingConfiguration.prepareDefines(defines);
  40793. }
  40794. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40795. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40796. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40797. // Misc.
  40798. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40799. // Values that need to be evaluated on every frame
  40800. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40801. // Attribs
  40802. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40803. };
  40804. /**
  40805. * Force shader compilation
  40806. */
  40807. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40808. var _this = this;
  40809. var localOptions = __assign({ clipPlane: false }, options);
  40810. var defines = new PBRMaterialDefines();
  40811. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40812. if (effect.isReady()) {
  40813. if (onCompiled) {
  40814. onCompiled(this);
  40815. }
  40816. }
  40817. else {
  40818. effect.onCompileObservable.add(function () {
  40819. if (onCompiled) {
  40820. onCompiled(_this);
  40821. }
  40822. });
  40823. }
  40824. };
  40825. /**
  40826. * Initializes the uniform buffer layout for the shader.
  40827. */
  40828. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40829. // Order is important !
  40830. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40831. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40832. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40833. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40834. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40835. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40836. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40837. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40838. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40839. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40840. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40841. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40842. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40843. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40844. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40845. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40846. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40847. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40848. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40849. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40850. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40851. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40852. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40853. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40854. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40855. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40856. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40857. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40858. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40859. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40860. this._uniformBuffer.addUniform("pointSize", 1);
  40861. this._uniformBuffer.create();
  40862. };
  40863. /**
  40864. * Unbinds the textures.
  40865. */
  40866. PBRBaseMaterial.prototype.unbind = function () {
  40867. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40868. this._uniformBuffer.setTexture("reflectionSampler", null);
  40869. }
  40870. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40871. this._uniformBuffer.setTexture("refractionSampler", null);
  40872. }
  40873. _super.prototype.unbind.call(this);
  40874. };
  40875. /**
  40876. * Binds the submesh data.
  40877. * @param world - The world matrix.
  40878. * @param mesh - The BJS mesh.
  40879. * @param subMesh - A submesh of the BJS mesh.
  40880. */
  40881. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40882. var scene = this.getScene();
  40883. var defines = subMesh._materialDefines;
  40884. if (!defines) {
  40885. return;
  40886. }
  40887. var effect = subMesh.effect;
  40888. if (!effect) {
  40889. return;
  40890. }
  40891. this._activeEffect = effect;
  40892. // Matrices
  40893. this.bindOnlyWorldMatrix(world);
  40894. // Normal Matrix
  40895. if (defines.OBJECTSPACE_NORMALMAP) {
  40896. world.toNormalMatrix(this._normalMatrix);
  40897. this.bindOnlyNormalMatrix(this._normalMatrix);
  40898. }
  40899. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40900. // Bones
  40901. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40902. var reflectionTexture = null;
  40903. if (mustRebind) {
  40904. this._uniformBuffer.bindToEffect(effect, "Material");
  40905. this.bindViewProjection(effect);
  40906. reflectionTexture = this._getReflectionTexture();
  40907. var refractionTexture = this._getRefractionTexture();
  40908. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40909. // Texture uniforms
  40910. if (scene.texturesEnabled) {
  40911. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40912. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40913. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40914. }
  40915. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40916. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40917. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40918. }
  40919. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40920. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40921. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40922. }
  40923. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40924. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40925. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40926. if (reflectionTexture.boundingBoxSize) {
  40927. var cubeTexture = reflectionTexture;
  40928. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40929. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40930. }
  40931. var polynomials = reflectionTexture.sphericalPolynomial;
  40932. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40933. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40934. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40935. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40936. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40937. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40938. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40939. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40940. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40941. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40942. }
  40943. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40944. }
  40945. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40946. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40947. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40948. }
  40949. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40950. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40951. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40952. }
  40953. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40954. if (this._metallicTexture) {
  40955. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40956. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40957. }
  40958. else if (this._reflectivityTexture) {
  40959. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40960. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40961. }
  40962. if (this._microSurfaceTexture) {
  40963. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40964. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40965. }
  40966. }
  40967. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40968. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40969. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40970. if (scene._mirroredCameraPosition) {
  40971. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40972. }
  40973. else {
  40974. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40975. }
  40976. }
  40977. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40978. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40979. var depth = 1.0;
  40980. if (!refractionTexture.isCube) {
  40981. if (refractionTexture.depth) {
  40982. depth = refractionTexture.depth;
  40983. }
  40984. }
  40985. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40986. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40987. }
  40988. }
  40989. // Point size
  40990. if (this.pointsCloud) {
  40991. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40992. }
  40993. // Colors
  40994. if (defines.METALLICWORKFLOW) {
  40995. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40996. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40997. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40998. }
  40999. else {
  41000. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41001. }
  41002. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41003. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41004. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41005. // Misc
  41006. this._lightingInfos.x = this._directIntensity;
  41007. this._lightingInfos.y = this._emissiveIntensity;
  41008. this._lightingInfos.z = this._environmentIntensity;
  41009. this._lightingInfos.w = this._specularIntensity;
  41010. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41011. }
  41012. // Textures
  41013. if (scene.texturesEnabled) {
  41014. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41015. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41016. }
  41017. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41018. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41019. }
  41020. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41021. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41022. }
  41023. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41024. if (defines.LODBASEDMICROSFURACE) {
  41025. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41026. }
  41027. else {
  41028. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41029. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41030. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41031. }
  41032. }
  41033. if (defines.ENVIRONMENTBRDF) {
  41034. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41035. }
  41036. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41037. if (defines.LODBASEDMICROSFURACE) {
  41038. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41039. }
  41040. else {
  41041. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41042. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41043. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41044. }
  41045. }
  41046. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41047. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41048. }
  41049. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41050. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41051. }
  41052. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41053. if (this._metallicTexture) {
  41054. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41055. }
  41056. else if (this._reflectivityTexture) {
  41057. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41058. }
  41059. if (this._microSurfaceTexture) {
  41060. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41061. }
  41062. }
  41063. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41064. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41065. }
  41066. }
  41067. // Clip plane
  41068. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41069. // Colors
  41070. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41071. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41072. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41073. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41074. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41075. }
  41076. if (mustRebind || !this.isFrozen) {
  41077. // Lights
  41078. if (scene.lightsEnabled && !this._disableLighting) {
  41079. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41080. }
  41081. // View
  41082. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41083. this.bindView(effect);
  41084. }
  41085. // Fog
  41086. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41087. // Morph targets
  41088. if (defines.NUM_MORPH_INFLUENCERS) {
  41089. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41090. }
  41091. // image processing
  41092. this._imageProcessingConfiguration.bind(this._activeEffect);
  41093. // Log. depth
  41094. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41095. }
  41096. this._uniformBuffer.update();
  41097. this._afterBind(mesh);
  41098. };
  41099. /**
  41100. * Returns the animatable textures.
  41101. * @returns - Array of animatable textures.
  41102. */
  41103. PBRBaseMaterial.prototype.getAnimatables = function () {
  41104. var results = [];
  41105. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41106. results.push(this._albedoTexture);
  41107. }
  41108. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41109. results.push(this._ambientTexture);
  41110. }
  41111. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41112. results.push(this._opacityTexture);
  41113. }
  41114. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41115. results.push(this._reflectionTexture);
  41116. }
  41117. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41118. results.push(this._emissiveTexture);
  41119. }
  41120. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41121. results.push(this._metallicTexture);
  41122. }
  41123. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41124. results.push(this._reflectivityTexture);
  41125. }
  41126. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41127. results.push(this._bumpTexture);
  41128. }
  41129. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41130. results.push(this._lightmapTexture);
  41131. }
  41132. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41133. results.push(this._refractionTexture);
  41134. }
  41135. return results;
  41136. };
  41137. /**
  41138. * Returns the texture used for reflections.
  41139. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41140. */
  41141. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41142. if (this._reflectionTexture) {
  41143. return this._reflectionTexture;
  41144. }
  41145. return this.getScene().environmentTexture;
  41146. };
  41147. /**
  41148. * Returns the texture used for refraction or null if none is used.
  41149. * @returns - Refection texture if present. If no refraction texture and refraction
  41150. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41151. */
  41152. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41153. if (this._refractionTexture) {
  41154. return this._refractionTexture;
  41155. }
  41156. if (this._linkRefractionWithTransparency) {
  41157. return this.getScene().environmentTexture;
  41158. }
  41159. return null;
  41160. };
  41161. /**
  41162. * Disposes the resources of the material.
  41163. * @param forceDisposeEffect - Forces the disposal of effects.
  41164. * @param forceDisposeTextures - Forces the disposal of all textures.
  41165. */
  41166. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41167. if (forceDisposeTextures) {
  41168. if (this._albedoTexture) {
  41169. this._albedoTexture.dispose();
  41170. }
  41171. if (this._ambientTexture) {
  41172. this._ambientTexture.dispose();
  41173. }
  41174. if (this._opacityTexture) {
  41175. this._opacityTexture.dispose();
  41176. }
  41177. if (this._reflectionTexture) {
  41178. this._reflectionTexture.dispose();
  41179. }
  41180. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41181. this._environmentBRDFTexture.dispose();
  41182. }
  41183. if (this._emissiveTexture) {
  41184. this._emissiveTexture.dispose();
  41185. }
  41186. if (this._metallicTexture) {
  41187. this._metallicTexture.dispose();
  41188. }
  41189. if (this._reflectivityTexture) {
  41190. this._reflectivityTexture.dispose();
  41191. }
  41192. if (this._bumpTexture) {
  41193. this._bumpTexture.dispose();
  41194. }
  41195. if (this._lightmapTexture) {
  41196. this._lightmapTexture.dispose();
  41197. }
  41198. if (this._refractionTexture) {
  41199. this._refractionTexture.dispose();
  41200. }
  41201. }
  41202. this._renderTargets.dispose();
  41203. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41204. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41205. }
  41206. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41207. };
  41208. /**
  41209. * Stores the reflectivity values based on metallic roughness workflow.
  41210. */
  41211. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41212. __decorate([
  41213. BABYLON.serializeAsImageProcessingConfiguration()
  41214. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41215. __decorate([
  41216. BABYLON.serialize()
  41217. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41218. __decorate([
  41219. BABYLON.serialize()
  41220. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41221. return PBRBaseMaterial;
  41222. }(BABYLON.PushMaterial));
  41223. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41224. })(BABYLON || (BABYLON = {}));
  41225. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41226. var BABYLON;
  41227. (function (BABYLON) {
  41228. /**
  41229. * The Physically based simple base material of BJS.
  41230. *
  41231. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41232. * It is used as the base class for both the specGloss and metalRough conventions.
  41233. */
  41234. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41235. __extends(PBRBaseSimpleMaterial, _super);
  41236. /**
  41237. * Instantiates a new PBRMaterial instance.
  41238. *
  41239. * @param name The material name
  41240. * @param scene The scene the material will be use in.
  41241. */
  41242. function PBRBaseSimpleMaterial(name, scene) {
  41243. var _this = _super.call(this, name, scene) || this;
  41244. /**
  41245. * Number of Simultaneous lights allowed on the material.
  41246. */
  41247. _this.maxSimultaneousLights = 4;
  41248. /**
  41249. * If sets to true, disables all the lights affecting the material.
  41250. */
  41251. _this.disableLighting = false;
  41252. /**
  41253. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41254. */
  41255. _this.invertNormalMapX = false;
  41256. /**
  41257. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41258. */
  41259. _this.invertNormalMapY = false;
  41260. /**
  41261. * Emissivie color used to self-illuminate the model.
  41262. */
  41263. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41264. /**
  41265. * Occlusion Channel Strenght.
  41266. */
  41267. _this.occlusionStrength = 1.0;
  41268. _this.useLightmapAsShadowmap = false;
  41269. _this._useAlphaFromAlbedoTexture = true;
  41270. _this._useAmbientInGrayScale = true;
  41271. return _this;
  41272. }
  41273. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41274. /**
  41275. * Gets the current double sided mode.
  41276. */
  41277. get: function () {
  41278. return this._twoSidedLighting;
  41279. },
  41280. /**
  41281. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41282. */
  41283. set: function (value) {
  41284. if (this._twoSidedLighting === value) {
  41285. return;
  41286. }
  41287. this._twoSidedLighting = value;
  41288. this.backFaceCulling = !value;
  41289. this._markAllSubMeshesAsTexturesDirty();
  41290. },
  41291. enumerable: true,
  41292. configurable: true
  41293. });
  41294. /**
  41295. * Return the active textures of the material.
  41296. */
  41297. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41298. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41299. if (this.environmentTexture) {
  41300. activeTextures.push(this.environmentTexture);
  41301. }
  41302. if (this.normalTexture) {
  41303. activeTextures.push(this.normalTexture);
  41304. }
  41305. if (this.emissiveTexture) {
  41306. activeTextures.push(this.emissiveTexture);
  41307. }
  41308. if (this.occlusionTexture) {
  41309. activeTextures.push(this.occlusionTexture);
  41310. }
  41311. if (this.lightmapTexture) {
  41312. activeTextures.push(this.lightmapTexture);
  41313. }
  41314. return activeTextures;
  41315. };
  41316. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41317. if (_super.prototype.hasTexture.call(this, texture)) {
  41318. return true;
  41319. }
  41320. if (this.lightmapTexture === texture) {
  41321. return true;
  41322. }
  41323. return false;
  41324. };
  41325. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41326. return "PBRBaseSimpleMaterial";
  41327. };
  41328. __decorate([
  41329. BABYLON.serialize(),
  41330. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41331. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41332. __decorate([
  41333. BABYLON.serialize(),
  41334. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41335. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41336. __decorate([
  41337. BABYLON.serializeAsTexture(),
  41338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41339. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41340. __decorate([
  41341. BABYLON.serialize(),
  41342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41343. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41344. __decorate([
  41345. BABYLON.serialize(),
  41346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41347. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41348. __decorate([
  41349. BABYLON.serializeAsTexture(),
  41350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41351. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41352. __decorate([
  41353. BABYLON.serializeAsColor3("emissive"),
  41354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41355. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41356. __decorate([
  41357. BABYLON.serializeAsTexture(),
  41358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41359. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41360. __decorate([
  41361. BABYLON.serialize(),
  41362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41363. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41364. __decorate([
  41365. BABYLON.serializeAsTexture(),
  41366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41367. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41368. __decorate([
  41369. BABYLON.serialize(),
  41370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41371. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41372. __decorate([
  41373. BABYLON.serialize()
  41374. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41375. __decorate([
  41376. BABYLON.serializeAsTexture(),
  41377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41378. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41379. __decorate([
  41380. BABYLON.serialize(),
  41381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41382. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41383. return PBRBaseSimpleMaterial;
  41384. }(BABYLON.PBRBaseMaterial));
  41385. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41386. })(BABYLON || (BABYLON = {}));
  41387. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41388. var BABYLON;
  41389. (function (BABYLON) {
  41390. /**
  41391. * The Physically based material of BJS.
  41392. *
  41393. * This offers the main features of a standard PBR material.
  41394. * For more information, please refer to the documentation :
  41395. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41396. */
  41397. var PBRMaterial = /** @class */ (function (_super) {
  41398. __extends(PBRMaterial, _super);
  41399. /**
  41400. * Instantiates a new PBRMaterial instance.
  41401. *
  41402. * @param name The material name
  41403. * @param scene The scene the material will be use in.
  41404. */
  41405. function PBRMaterial(name, scene) {
  41406. var _this = _super.call(this, name, scene) || this;
  41407. /**
  41408. * Intensity of the direct lights e.g. the four lights available in your scene.
  41409. * This impacts both the direct diffuse and specular highlights.
  41410. */
  41411. _this.directIntensity = 1.0;
  41412. /**
  41413. * Intensity of the emissive part of the material.
  41414. * This helps controlling the emissive effect without modifying the emissive color.
  41415. */
  41416. _this.emissiveIntensity = 1.0;
  41417. /**
  41418. * Intensity of the environment e.g. how much the environment will light the object
  41419. * either through harmonics for rough material or through the refelction for shiny ones.
  41420. */
  41421. _this.environmentIntensity = 1.0;
  41422. /**
  41423. * This is a special control allowing the reduction of the specular highlights coming from the
  41424. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41425. */
  41426. _this.specularIntensity = 1.0;
  41427. /**
  41428. * Debug Control allowing disabling the bump map on this material.
  41429. */
  41430. _this.disableBumpMap = false;
  41431. /**
  41432. * AKA Occlusion Texture Intensity in other nomenclature.
  41433. */
  41434. _this.ambientTextureStrength = 1.0;
  41435. /**
  41436. * The color of a material in ambient lighting.
  41437. */
  41438. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41439. /**
  41440. * AKA Diffuse Color in other nomenclature.
  41441. */
  41442. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41443. /**
  41444. * AKA Specular Color in other nomenclature.
  41445. */
  41446. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41447. /**
  41448. * The color reflected from the material.
  41449. */
  41450. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41451. /**
  41452. * The color emitted from the material.
  41453. */
  41454. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41455. /**
  41456. * AKA Glossiness in other nomenclature.
  41457. */
  41458. _this.microSurface = 1.0;
  41459. /**
  41460. * source material index of refraction (IOR)' / 'destination material IOR.
  41461. */
  41462. _this.indexOfRefraction = 0.66;
  41463. /**
  41464. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41465. */
  41466. _this.invertRefractionY = false;
  41467. /**
  41468. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41469. * Materials half opaque for instance using refraction could benefit from this control.
  41470. */
  41471. _this.linkRefractionWithTransparency = false;
  41472. _this.useLightmapAsShadowmap = false;
  41473. /**
  41474. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41475. */
  41476. _this.useAlphaFromAlbedoTexture = false;
  41477. /**
  41478. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41479. */
  41480. _this.forceAlphaTest = false;
  41481. /**
  41482. * Defines the alpha limits in alpha test mode.
  41483. */
  41484. _this.alphaCutOff = 0.4;
  41485. /**
  41486. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41487. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41488. */
  41489. _this.useSpecularOverAlpha = true;
  41490. /**
  41491. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41492. */
  41493. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41494. /**
  41495. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41496. */
  41497. _this.useRoughnessFromMetallicTextureAlpha = true;
  41498. /**
  41499. * Specifies if the metallic texture contains the roughness information in its green channel.
  41500. */
  41501. _this.useRoughnessFromMetallicTextureGreen = false;
  41502. /**
  41503. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41504. */
  41505. _this.useMetallnessFromMetallicTextureBlue = false;
  41506. /**
  41507. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41508. */
  41509. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41510. /**
  41511. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41512. */
  41513. _this.useAmbientInGrayScale = false;
  41514. /**
  41515. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41516. * The material will try to infer what glossiness each pixel should be.
  41517. */
  41518. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41519. /**
  41520. * BJS is using an harcoded light falloff based on a manually sets up range.
  41521. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41522. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41523. */
  41524. _this.usePhysicalLightFalloff = true;
  41525. /**
  41526. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41527. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41528. */
  41529. _this.useRadianceOverAlpha = true;
  41530. /**
  41531. * Allows using an object space normal map (instead of tangent space).
  41532. */
  41533. _this.useObjectSpaceNormalMap = false;
  41534. /**
  41535. * Allows using the bump map in parallax mode.
  41536. */
  41537. _this.useParallax = false;
  41538. /**
  41539. * Allows using the bump map in parallax occlusion mode.
  41540. */
  41541. _this.useParallaxOcclusion = false;
  41542. /**
  41543. * Controls the scale bias of the parallax mode.
  41544. */
  41545. _this.parallaxScaleBias = 0.05;
  41546. /**
  41547. * If sets to true, disables all the lights affecting the material.
  41548. */
  41549. _this.disableLighting = false;
  41550. /**
  41551. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41552. */
  41553. _this.forceIrradianceInFragment = false;
  41554. /**
  41555. * Number of Simultaneous lights allowed on the material.
  41556. */
  41557. _this.maxSimultaneousLights = 4;
  41558. /**
  41559. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41560. */
  41561. _this.invertNormalMapX = false;
  41562. /**
  41563. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41564. */
  41565. _this.invertNormalMapY = false;
  41566. /**
  41567. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41568. */
  41569. _this.twoSidedLighting = false;
  41570. /**
  41571. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41572. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41573. */
  41574. _this.useAlphaFresnel = false;
  41575. /**
  41576. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41577. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41578. */
  41579. _this.useLinearAlphaFresnel = false;
  41580. /**
  41581. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41582. * And/Or occlude the blended part.
  41583. */
  41584. _this.environmentBRDFTexture = null;
  41585. /**
  41586. * Force normal to face away from face.
  41587. */
  41588. _this.forceNormalForward = false;
  41589. /**
  41590. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41591. * makes the reflect vector face the model (under horizon).
  41592. */
  41593. _this.useHorizonOcclusion = true;
  41594. /**
  41595. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41596. * too much the area relying on ambient texture to define their ambient occlusion.
  41597. */
  41598. _this.useRadianceOcclusion = true;
  41599. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41600. return _this;
  41601. }
  41602. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41603. /**
  41604. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41605. */
  41606. get: function () {
  41607. return this._PBRMATERIAL_OPAQUE;
  41608. },
  41609. enumerable: true,
  41610. configurable: true
  41611. });
  41612. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41613. /**
  41614. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41615. */
  41616. get: function () {
  41617. return this._PBRMATERIAL_ALPHATEST;
  41618. },
  41619. enumerable: true,
  41620. configurable: true
  41621. });
  41622. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41623. /**
  41624. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41625. */
  41626. get: function () {
  41627. return this._PBRMATERIAL_ALPHABLEND;
  41628. },
  41629. enumerable: true,
  41630. configurable: true
  41631. });
  41632. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41633. /**
  41634. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41635. * They are also discarded below the alpha cutoff threshold to improve performances.
  41636. */
  41637. get: function () {
  41638. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41639. },
  41640. enumerable: true,
  41641. configurable: true
  41642. });
  41643. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41644. /**
  41645. * Gets the image processing configuration used either in this material.
  41646. */
  41647. get: function () {
  41648. return this._imageProcessingConfiguration;
  41649. },
  41650. /**
  41651. * Sets the Default image processing configuration used either in the this material.
  41652. *
  41653. * If sets to null, the scene one is in use.
  41654. */
  41655. set: function (value) {
  41656. this._attachImageProcessingConfiguration(value);
  41657. // Ensure the effect will be rebuilt.
  41658. this._markAllSubMeshesAsTexturesDirty();
  41659. },
  41660. enumerable: true,
  41661. configurable: true
  41662. });
  41663. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41664. /**
  41665. * Gets wether the color curves effect is enabled.
  41666. */
  41667. get: function () {
  41668. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41669. },
  41670. /**
  41671. * Sets wether the color curves effect is enabled.
  41672. */
  41673. set: function (value) {
  41674. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41680. /**
  41681. * Gets wether the color grading effect is enabled.
  41682. */
  41683. get: function () {
  41684. return this.imageProcessingConfiguration.colorGradingEnabled;
  41685. },
  41686. /**
  41687. * Gets wether the color grading effect is enabled.
  41688. */
  41689. set: function (value) {
  41690. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41691. },
  41692. enumerable: true,
  41693. configurable: true
  41694. });
  41695. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41696. /**
  41697. * Gets wether tonemapping is enabled or not.
  41698. */
  41699. get: function () {
  41700. return this._imageProcessingConfiguration.toneMappingEnabled;
  41701. },
  41702. /**
  41703. * Sets wether tonemapping is enabled or not
  41704. */
  41705. set: function (value) {
  41706. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. ;
  41712. ;
  41713. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41714. /**
  41715. * The camera exposure used on this material.
  41716. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41717. * This corresponds to a photographic exposure.
  41718. */
  41719. get: function () {
  41720. return this._imageProcessingConfiguration.exposure;
  41721. },
  41722. /**
  41723. * The camera exposure used on this material.
  41724. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41725. * This corresponds to a photographic exposure.
  41726. */
  41727. set: function (value) {
  41728. this._imageProcessingConfiguration.exposure = value;
  41729. },
  41730. enumerable: true,
  41731. configurable: true
  41732. });
  41733. ;
  41734. ;
  41735. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41736. /**
  41737. * Gets The camera contrast used on this material.
  41738. */
  41739. get: function () {
  41740. return this._imageProcessingConfiguration.contrast;
  41741. },
  41742. /**
  41743. * Sets The camera contrast used on this material.
  41744. */
  41745. set: function (value) {
  41746. this._imageProcessingConfiguration.contrast = value;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41752. /**
  41753. * Gets the Color Grading 2D Lookup Texture.
  41754. */
  41755. get: function () {
  41756. return this._imageProcessingConfiguration.colorGradingTexture;
  41757. },
  41758. /**
  41759. * Sets the Color Grading 2D Lookup Texture.
  41760. */
  41761. set: function (value) {
  41762. this._imageProcessingConfiguration.colorGradingTexture = value;
  41763. },
  41764. enumerable: true,
  41765. configurable: true
  41766. });
  41767. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41768. /**
  41769. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41770. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41771. * 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;
  41772. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41773. */
  41774. get: function () {
  41775. return this._imageProcessingConfiguration.colorCurves;
  41776. },
  41777. /**
  41778. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41779. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41780. * 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;
  41781. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41782. */
  41783. set: function (value) {
  41784. this._imageProcessingConfiguration.colorCurves = value;
  41785. },
  41786. enumerable: true,
  41787. configurable: true
  41788. });
  41789. /**
  41790. * Returns the name of this material class.
  41791. */
  41792. PBRMaterial.prototype.getClassName = function () {
  41793. return "PBRMaterial";
  41794. };
  41795. /**
  41796. * Returns an array of the actively used textures.
  41797. * @returns - Array of BaseTextures
  41798. */
  41799. PBRMaterial.prototype.getActiveTextures = function () {
  41800. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41801. if (this._albedoTexture) {
  41802. activeTextures.push(this._albedoTexture);
  41803. }
  41804. if (this._ambientTexture) {
  41805. activeTextures.push(this._ambientTexture);
  41806. }
  41807. if (this._opacityTexture) {
  41808. activeTextures.push(this._opacityTexture);
  41809. }
  41810. if (this._reflectionTexture) {
  41811. activeTextures.push(this._reflectionTexture);
  41812. }
  41813. if (this._emissiveTexture) {
  41814. activeTextures.push(this._emissiveTexture);
  41815. }
  41816. if (this._reflectivityTexture) {
  41817. activeTextures.push(this._reflectivityTexture);
  41818. }
  41819. if (this._metallicTexture) {
  41820. activeTextures.push(this._metallicTexture);
  41821. }
  41822. if (this._microSurfaceTexture) {
  41823. activeTextures.push(this._microSurfaceTexture);
  41824. }
  41825. if (this._bumpTexture) {
  41826. activeTextures.push(this._bumpTexture);
  41827. }
  41828. if (this._lightmapTexture) {
  41829. activeTextures.push(this._lightmapTexture);
  41830. }
  41831. if (this._refractionTexture) {
  41832. activeTextures.push(this._refractionTexture);
  41833. }
  41834. return activeTextures;
  41835. };
  41836. /**
  41837. * Checks to see if a texture is used in the material.
  41838. * @param texture - Base texture to use.
  41839. * @returns - Boolean specifying if a texture is used in the material.
  41840. */
  41841. PBRMaterial.prototype.hasTexture = function (texture) {
  41842. if (_super.prototype.hasTexture.call(this, texture)) {
  41843. return true;
  41844. }
  41845. if (this._albedoTexture === texture) {
  41846. return true;
  41847. }
  41848. if (this._ambientTexture === texture) {
  41849. return true;
  41850. }
  41851. if (this._opacityTexture === texture) {
  41852. return true;
  41853. }
  41854. if (this._reflectionTexture === texture) {
  41855. return true;
  41856. }
  41857. if (this._reflectivityTexture === texture) {
  41858. return true;
  41859. }
  41860. if (this._metallicTexture === texture) {
  41861. return true;
  41862. }
  41863. if (this._microSurfaceTexture === texture) {
  41864. return true;
  41865. }
  41866. if (this._bumpTexture === texture) {
  41867. return true;
  41868. }
  41869. if (this._lightmapTexture === texture) {
  41870. return true;
  41871. }
  41872. if (this._refractionTexture === texture) {
  41873. return true;
  41874. }
  41875. return false;
  41876. };
  41877. /**
  41878. * Makes a duplicate of the current material.
  41879. * @param name - name to use for the new material.
  41880. */
  41881. PBRMaterial.prototype.clone = function (name) {
  41882. var _this = this;
  41883. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41884. clone.id = name;
  41885. clone.name = name;
  41886. return clone;
  41887. };
  41888. /**
  41889. * Serializes this PBR Material.
  41890. * @returns - An object with the serialized material.
  41891. */
  41892. PBRMaterial.prototype.serialize = function () {
  41893. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41894. serializationObject.customType = "BABYLON.PBRMaterial";
  41895. return serializationObject;
  41896. };
  41897. // Statics
  41898. /**
  41899. * Parses a PBR Material from a serialized object.
  41900. * @param source - Serialized object.
  41901. * @param scene - BJS scene instance.
  41902. * @param rootUrl - url for the scene object
  41903. * @returns - PBRMaterial
  41904. */
  41905. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41906. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41907. };
  41908. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41909. /**
  41910. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41911. */
  41912. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41913. /**
  41914. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41915. */
  41916. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41917. /**
  41918. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41919. * They are also discarded below the alpha cutoff threshold to improve performances.
  41920. */
  41921. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41922. __decorate([
  41923. BABYLON.serialize(),
  41924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41925. ], PBRMaterial.prototype, "directIntensity", void 0);
  41926. __decorate([
  41927. BABYLON.serialize(),
  41928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41929. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41930. __decorate([
  41931. BABYLON.serialize(),
  41932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41933. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41934. __decorate([
  41935. BABYLON.serialize(),
  41936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41937. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41938. __decorate([
  41939. BABYLON.serialize(),
  41940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41941. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41942. __decorate([
  41943. BABYLON.serializeAsTexture(),
  41944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41945. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41946. __decorate([
  41947. BABYLON.serializeAsTexture(),
  41948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41949. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41950. __decorate([
  41951. BABYLON.serialize(),
  41952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41953. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41954. __decorate([
  41955. BABYLON.serializeAsTexture(),
  41956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41957. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41958. __decorate([
  41959. BABYLON.serializeAsTexture(),
  41960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41961. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41962. __decorate([
  41963. BABYLON.serializeAsTexture(),
  41964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41965. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41966. __decorate([
  41967. BABYLON.serializeAsTexture(),
  41968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41969. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41970. __decorate([
  41971. BABYLON.serializeAsTexture(),
  41972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41973. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41974. __decorate([
  41975. BABYLON.serialize(),
  41976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41977. ], PBRMaterial.prototype, "metallic", void 0);
  41978. __decorate([
  41979. BABYLON.serialize(),
  41980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41981. ], PBRMaterial.prototype, "roughness", void 0);
  41982. __decorate([
  41983. BABYLON.serializeAsTexture(),
  41984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41985. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41986. __decorate([
  41987. BABYLON.serializeAsTexture(),
  41988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41989. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41990. __decorate([
  41991. BABYLON.serializeAsTexture(),
  41992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41993. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41994. __decorate([
  41995. BABYLON.serializeAsTexture(),
  41996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41997. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41998. __decorate([
  41999. BABYLON.serializeAsColor3("ambient"),
  42000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42001. ], PBRMaterial.prototype, "ambientColor", void 0);
  42002. __decorate([
  42003. BABYLON.serializeAsColor3("albedo"),
  42004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42005. ], PBRMaterial.prototype, "albedoColor", void 0);
  42006. __decorate([
  42007. BABYLON.serializeAsColor3("reflectivity"),
  42008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42009. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42010. __decorate([
  42011. BABYLON.serializeAsColor3("reflection"),
  42012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42013. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42014. __decorate([
  42015. BABYLON.serializeAsColor3("emissive"),
  42016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42017. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42018. __decorate([
  42019. BABYLON.serialize(),
  42020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42021. ], PBRMaterial.prototype, "microSurface", void 0);
  42022. __decorate([
  42023. BABYLON.serialize(),
  42024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42025. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42026. __decorate([
  42027. BABYLON.serialize(),
  42028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42029. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42030. __decorate([
  42031. BABYLON.serialize(),
  42032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42033. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42034. __decorate([
  42035. BABYLON.serialize(),
  42036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42037. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42038. __decorate([
  42039. BABYLON.serialize(),
  42040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42041. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42042. __decorate([
  42043. BABYLON.serialize(),
  42044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42045. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42046. __decorate([
  42047. BABYLON.serialize(),
  42048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42049. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42050. __decorate([
  42051. BABYLON.serialize(),
  42052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42053. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42054. __decorate([
  42055. BABYLON.serialize(),
  42056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42057. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42058. __decorate([
  42059. BABYLON.serialize(),
  42060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42061. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42062. __decorate([
  42063. BABYLON.serialize(),
  42064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42065. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42066. __decorate([
  42067. BABYLON.serialize(),
  42068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42069. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42070. __decorate([
  42071. BABYLON.serialize(),
  42072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42073. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42074. __decorate([
  42075. BABYLON.serialize(),
  42076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42077. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42078. __decorate([
  42079. BABYLON.serialize(),
  42080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42081. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42082. __decorate([
  42083. BABYLON.serialize(),
  42084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42085. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42086. __decorate([
  42087. BABYLON.serialize(),
  42088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42089. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42090. __decorate([
  42091. BABYLON.serialize(),
  42092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42093. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42094. __decorate([
  42095. BABYLON.serialize(),
  42096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42097. ], PBRMaterial.prototype, "useParallax", void 0);
  42098. __decorate([
  42099. BABYLON.serialize(),
  42100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42101. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42102. __decorate([
  42103. BABYLON.serialize(),
  42104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42105. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42106. __decorate([
  42107. BABYLON.serialize(),
  42108. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42109. ], PBRMaterial.prototype, "disableLighting", void 0);
  42110. __decorate([
  42111. BABYLON.serialize(),
  42112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42113. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42114. __decorate([
  42115. BABYLON.serialize(),
  42116. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42117. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42118. __decorate([
  42119. BABYLON.serialize(),
  42120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42121. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42122. __decorate([
  42123. BABYLON.serialize(),
  42124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42125. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42126. __decorate([
  42127. BABYLON.serialize(),
  42128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42129. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42130. __decorate([
  42131. BABYLON.serialize(),
  42132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42133. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42134. __decorate([
  42135. BABYLON.serialize(),
  42136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42137. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42138. __decorate([
  42139. BABYLON.serializeAsTexture(),
  42140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42141. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42142. __decorate([
  42143. BABYLON.serialize(),
  42144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42145. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42146. __decorate([
  42147. BABYLON.serialize(),
  42148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42149. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42150. __decorate([
  42151. BABYLON.serialize(),
  42152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42153. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42154. return PBRMaterial;
  42155. }(BABYLON.PBRBaseMaterial));
  42156. BABYLON.PBRMaterial = PBRMaterial;
  42157. })(BABYLON || (BABYLON = {}));
  42158. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42159. var BABYLON;
  42160. (function (BABYLON) {
  42161. /**
  42162. * The PBR material of BJS following the metal roughness convention.
  42163. *
  42164. * This fits to the PBR convention in the GLTF definition:
  42165. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42166. */
  42167. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42168. __extends(PBRMetallicRoughnessMaterial, _super);
  42169. /**
  42170. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42171. *
  42172. * @param name The material name
  42173. * @param scene The scene the material will be use in.
  42174. */
  42175. function PBRMetallicRoughnessMaterial(name, scene) {
  42176. var _this = _super.call(this, name, scene) || this;
  42177. _this._useRoughnessFromMetallicTextureAlpha = false;
  42178. _this._useRoughnessFromMetallicTextureGreen = true;
  42179. _this._useMetallnessFromMetallicTextureBlue = true;
  42180. _this._forceMetallicWorkflow = true;
  42181. return _this;
  42182. }
  42183. /**
  42184. * Return the currrent class name of the material.
  42185. */
  42186. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42187. return "PBRMetallicRoughnessMaterial";
  42188. };
  42189. /**
  42190. * Return the active textures of the material.
  42191. */
  42192. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42193. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42194. if (this.baseTexture) {
  42195. activeTextures.push(this.baseTexture);
  42196. }
  42197. if (this.metallicRoughnessTexture) {
  42198. activeTextures.push(this.metallicRoughnessTexture);
  42199. }
  42200. return activeTextures;
  42201. };
  42202. /**
  42203. * Checks to see if a texture is used in the material.
  42204. * @param texture - Base texture to use.
  42205. * @returns - Boolean specifying if a texture is used in the material.
  42206. */
  42207. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42208. if (_super.prototype.hasTexture.call(this, texture)) {
  42209. return true;
  42210. }
  42211. if (this.baseTexture === texture) {
  42212. return true;
  42213. }
  42214. if (this.metallicRoughnessTexture === texture) {
  42215. return true;
  42216. }
  42217. return false;
  42218. };
  42219. /**
  42220. * Makes a duplicate of the current material.
  42221. * @param name - name to use for the new material.
  42222. */
  42223. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42224. var _this = this;
  42225. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42226. clone.id = name;
  42227. clone.name = name;
  42228. return clone;
  42229. };
  42230. /**
  42231. * Serialize the material to a parsable JSON object.
  42232. */
  42233. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42234. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42235. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42236. return serializationObject;
  42237. };
  42238. /**
  42239. * Parses a JSON object correponding to the serialize function.
  42240. */
  42241. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42242. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42243. };
  42244. __decorate([
  42245. BABYLON.serializeAsColor3(),
  42246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42247. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42248. __decorate([
  42249. BABYLON.serializeAsTexture(),
  42250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42251. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42252. __decorate([
  42253. BABYLON.serialize(),
  42254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42255. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42256. __decorate([
  42257. BABYLON.serialize(),
  42258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42259. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42260. __decorate([
  42261. BABYLON.serializeAsTexture(),
  42262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42263. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42264. return PBRMetallicRoughnessMaterial;
  42265. }(BABYLON.PBRBaseSimpleMaterial));
  42266. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42267. })(BABYLON || (BABYLON = {}));
  42268. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42269. var BABYLON;
  42270. (function (BABYLON) {
  42271. /**
  42272. * The PBR material of BJS following the specular glossiness convention.
  42273. *
  42274. * This fits to the PBR convention in the GLTF definition:
  42275. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42276. */
  42277. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42278. __extends(PBRSpecularGlossinessMaterial, _super);
  42279. /**
  42280. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42281. *
  42282. * @param name The material name
  42283. * @param scene The scene the material will be use in.
  42284. */
  42285. function PBRSpecularGlossinessMaterial(name, scene) {
  42286. var _this = _super.call(this, name, scene) || this;
  42287. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42288. return _this;
  42289. }
  42290. /**
  42291. * Return the currrent class name of the material.
  42292. */
  42293. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42294. return "PBRSpecularGlossinessMaterial";
  42295. };
  42296. /**
  42297. * Return the active textures of the material.
  42298. */
  42299. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42300. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42301. if (this.diffuseTexture) {
  42302. activeTextures.push(this.diffuseTexture);
  42303. }
  42304. if (this.specularGlossinessTexture) {
  42305. activeTextures.push(this.specularGlossinessTexture);
  42306. }
  42307. return activeTextures;
  42308. };
  42309. /**
  42310. * Checks to see if a texture is used in the material.
  42311. * @param texture - Base texture to use.
  42312. * @returns - Boolean specifying if a texture is used in the material.
  42313. */
  42314. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42315. if (_super.prototype.hasTexture.call(this, texture)) {
  42316. return true;
  42317. }
  42318. if (this.diffuseTexture === texture) {
  42319. return true;
  42320. }
  42321. if (this.specularGlossinessTexture === texture) {
  42322. return true;
  42323. }
  42324. return false;
  42325. };
  42326. /**
  42327. * Makes a duplicate of the current material.
  42328. * @param name - name to use for the new material.
  42329. */
  42330. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42331. var _this = this;
  42332. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42333. clone.id = name;
  42334. clone.name = name;
  42335. return clone;
  42336. };
  42337. /**
  42338. * Serialize the material to a parsable JSON object.
  42339. */
  42340. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42342. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42343. return serializationObject;
  42344. };
  42345. /**
  42346. * Parses a JSON object correponding to the serialize function.
  42347. */
  42348. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42349. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42350. };
  42351. __decorate([
  42352. BABYLON.serializeAsColor3("diffuse"),
  42353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42354. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42355. __decorate([
  42356. BABYLON.serializeAsTexture(),
  42357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42358. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42359. __decorate([
  42360. BABYLON.serializeAsColor3("specular"),
  42361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42362. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42363. __decorate([
  42364. BABYLON.serialize(),
  42365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42366. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42367. __decorate([
  42368. BABYLON.serializeAsTexture(),
  42369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42370. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42371. return PBRSpecularGlossinessMaterial;
  42372. }(BABYLON.PBRBaseSimpleMaterial));
  42373. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42374. })(BABYLON || (BABYLON = {}));
  42375. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42376. var BABYLON;
  42377. (function (BABYLON) {
  42378. BABYLON.CameraInputTypes = {};
  42379. var CameraInputsManager = /** @class */ (function () {
  42380. function CameraInputsManager(camera) {
  42381. this.attached = {};
  42382. this.camera = camera;
  42383. this.checkInputs = function () { };
  42384. }
  42385. /**
  42386. * Add an input method to a camera.
  42387. * builtin inputs example: camera.inputs.addGamepad();
  42388. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42389. * @param input camera input method
  42390. */
  42391. CameraInputsManager.prototype.add = function (input) {
  42392. var type = input.getSimpleName();
  42393. if (this.attached[type]) {
  42394. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42395. return;
  42396. }
  42397. this.attached[type] = input;
  42398. input.camera = this.camera;
  42399. //for checkInputs, we are dynamically creating a function
  42400. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42401. if (input.checkInputs) {
  42402. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42403. }
  42404. if (this.attachedElement) {
  42405. input.attachControl(this.attachedElement);
  42406. }
  42407. };
  42408. /**
  42409. * Remove a specific input method from a camera
  42410. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42411. * @param inputToRemove camera input method
  42412. */
  42413. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42414. for (var cam in this.attached) {
  42415. var input = this.attached[cam];
  42416. if (input === inputToRemove) {
  42417. input.detachControl(this.attachedElement);
  42418. input.camera = null;
  42419. delete this.attached[cam];
  42420. this.rebuildInputCheck();
  42421. }
  42422. }
  42423. };
  42424. CameraInputsManager.prototype.removeByType = function (inputType) {
  42425. for (var cam in this.attached) {
  42426. var input = this.attached[cam];
  42427. if (input.getClassName() === inputType) {
  42428. input.detachControl(this.attachedElement);
  42429. input.camera = null;
  42430. delete this.attached[cam];
  42431. this.rebuildInputCheck();
  42432. }
  42433. }
  42434. };
  42435. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42436. var current = this.checkInputs;
  42437. return function () {
  42438. current();
  42439. fn();
  42440. };
  42441. };
  42442. CameraInputsManager.prototype.attachInput = function (input) {
  42443. if (this.attachedElement) {
  42444. input.attachControl(this.attachedElement, this.noPreventDefault);
  42445. }
  42446. };
  42447. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42448. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42449. if (this.attachedElement) {
  42450. return;
  42451. }
  42452. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42453. this.attachedElement = element;
  42454. this.noPreventDefault = noPreventDefault;
  42455. for (var cam in this.attached) {
  42456. this.attached[cam].attachControl(element, noPreventDefault);
  42457. }
  42458. };
  42459. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42460. if (disconnect === void 0) { disconnect = false; }
  42461. if (this.attachedElement !== element) {
  42462. return;
  42463. }
  42464. for (var cam in this.attached) {
  42465. this.attached[cam].detachControl(element);
  42466. if (disconnect) {
  42467. this.attached[cam].camera = null;
  42468. }
  42469. }
  42470. this.attachedElement = null;
  42471. };
  42472. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42473. this.checkInputs = function () { };
  42474. for (var cam in this.attached) {
  42475. var input = this.attached[cam];
  42476. if (input.checkInputs) {
  42477. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42478. }
  42479. }
  42480. };
  42481. /**
  42482. * Remove all attached input methods from a camera
  42483. */
  42484. CameraInputsManager.prototype.clear = function () {
  42485. if (this.attachedElement) {
  42486. this.detachElement(this.attachedElement, true);
  42487. }
  42488. this.attached = {};
  42489. this.attachedElement = null;
  42490. this.checkInputs = function () { };
  42491. };
  42492. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42493. var inputs = {};
  42494. for (var cam in this.attached) {
  42495. var input = this.attached[cam];
  42496. var res = BABYLON.SerializationHelper.Serialize(input);
  42497. inputs[input.getClassName()] = res;
  42498. }
  42499. serializedCamera.inputsmgr = inputs;
  42500. };
  42501. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42502. var parsedInputs = parsedCamera.inputsmgr;
  42503. if (parsedInputs) {
  42504. this.clear();
  42505. for (var n in parsedInputs) {
  42506. var construct = BABYLON.CameraInputTypes[n];
  42507. if (construct) {
  42508. var parsedinput = parsedInputs[n];
  42509. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42510. this.add(input);
  42511. }
  42512. }
  42513. }
  42514. else {
  42515. //2016-03-08 this part is for managing backward compatibility
  42516. for (var n in this.attached) {
  42517. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42518. if (construct) {
  42519. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42520. this.remove(this.attached[n]);
  42521. this.add(input);
  42522. }
  42523. }
  42524. }
  42525. };
  42526. return CameraInputsManager;
  42527. }());
  42528. BABYLON.CameraInputsManager = CameraInputsManager;
  42529. })(BABYLON || (BABYLON = {}));
  42530. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42531. var BABYLON;
  42532. (function (BABYLON) {
  42533. var TargetCamera = /** @class */ (function (_super) {
  42534. __extends(TargetCamera, _super);
  42535. function TargetCamera(name, position, scene) {
  42536. var _this = _super.call(this, name, position, scene) || this;
  42537. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42538. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42539. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42540. _this.speed = 2.0;
  42541. _this.noRotationConstraint = false;
  42542. _this.lockedTarget = null;
  42543. _this._currentTarget = BABYLON.Vector3.Zero();
  42544. _this._viewMatrix = BABYLON.Matrix.Zero();
  42545. _this._camMatrix = BABYLON.Matrix.Zero();
  42546. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42547. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42548. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42549. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42550. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42551. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42552. _this._tempMatrix = BABYLON.Matrix.Zero();
  42553. return _this;
  42554. }
  42555. TargetCamera.prototype.getFrontPosition = function (distance) {
  42556. this.getWorldMatrix();
  42557. var direction = this.getTarget().subtract(this.position);
  42558. direction.normalize();
  42559. direction.scaleInPlace(distance);
  42560. return this.globalPosition.add(direction);
  42561. };
  42562. TargetCamera.prototype._getLockedTargetPosition = function () {
  42563. if (!this.lockedTarget) {
  42564. return null;
  42565. }
  42566. if (this.lockedTarget.absolutePosition) {
  42567. this.lockedTarget.computeWorldMatrix();
  42568. }
  42569. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42570. };
  42571. TargetCamera.prototype.storeState = function () {
  42572. this._storedPosition = this.position.clone();
  42573. this._storedRotation = this.rotation.clone();
  42574. if (this.rotationQuaternion) {
  42575. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42576. }
  42577. return _super.prototype.storeState.call(this);
  42578. };
  42579. /**
  42580. * Restored camera state. You must call storeState() first
  42581. */
  42582. TargetCamera.prototype._restoreStateValues = function () {
  42583. if (!_super.prototype._restoreStateValues.call(this)) {
  42584. return false;
  42585. }
  42586. this.position = this._storedPosition.clone();
  42587. this.rotation = this._storedRotation.clone();
  42588. if (this.rotationQuaternion) {
  42589. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42590. }
  42591. this.cameraDirection.copyFromFloats(0, 0, 0);
  42592. this.cameraRotation.copyFromFloats(0, 0);
  42593. return true;
  42594. };
  42595. // Cache
  42596. TargetCamera.prototype._initCache = function () {
  42597. _super.prototype._initCache.call(this);
  42598. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42599. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42600. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42601. };
  42602. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42603. if (!ignoreParentClass) {
  42604. _super.prototype._updateCache.call(this);
  42605. }
  42606. var lockedTargetPosition = this._getLockedTargetPosition();
  42607. if (!lockedTargetPosition) {
  42608. this._cache.lockedTarget = null;
  42609. }
  42610. else {
  42611. if (!this._cache.lockedTarget) {
  42612. this._cache.lockedTarget = lockedTargetPosition.clone();
  42613. }
  42614. else {
  42615. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42616. }
  42617. }
  42618. this._cache.rotation.copyFrom(this.rotation);
  42619. if (this.rotationQuaternion)
  42620. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42621. };
  42622. // Synchronized
  42623. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42624. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42625. return false;
  42626. }
  42627. var lockedTargetPosition = this._getLockedTargetPosition();
  42628. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42629. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42630. };
  42631. // Methods
  42632. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42633. var engine = this.getEngine();
  42634. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42635. };
  42636. // Target
  42637. TargetCamera.prototype.setTarget = function (target) {
  42638. this.upVector.normalize();
  42639. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42640. this._camMatrix.invert();
  42641. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42642. var vDir = target.subtract(this.position);
  42643. if (vDir.x >= 0.0) {
  42644. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42645. }
  42646. else {
  42647. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42648. }
  42649. this.rotation.z = 0;
  42650. if (isNaN(this.rotation.x)) {
  42651. this.rotation.x = 0;
  42652. }
  42653. if (isNaN(this.rotation.y)) {
  42654. this.rotation.y = 0;
  42655. }
  42656. if (isNaN(this.rotation.z)) {
  42657. this.rotation.z = 0;
  42658. }
  42659. if (this.rotationQuaternion) {
  42660. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42661. }
  42662. };
  42663. /**
  42664. * Return the current target position of the camera. This value is expressed in local space.
  42665. */
  42666. TargetCamera.prototype.getTarget = function () {
  42667. return this._currentTarget;
  42668. };
  42669. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42670. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42671. };
  42672. TargetCamera.prototype._updatePosition = function () {
  42673. if (this.parent) {
  42674. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42675. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42676. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42677. return;
  42678. }
  42679. this.position.addInPlace(this.cameraDirection);
  42680. };
  42681. TargetCamera.prototype._checkInputs = function () {
  42682. var needToMove = this._decideIfNeedsToMove();
  42683. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42684. // Move
  42685. if (needToMove) {
  42686. this._updatePosition();
  42687. }
  42688. // Rotate
  42689. if (needToRotate) {
  42690. this.rotation.x += this.cameraRotation.x;
  42691. this.rotation.y += this.cameraRotation.y;
  42692. //rotate, if quaternion is set and rotation was used
  42693. if (this.rotationQuaternion) {
  42694. var len = this.rotation.lengthSquared();
  42695. if (len) {
  42696. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42697. }
  42698. }
  42699. if (!this.noRotationConstraint) {
  42700. var limit = (Math.PI / 2) * 0.95;
  42701. if (this.rotation.x > limit)
  42702. this.rotation.x = limit;
  42703. if (this.rotation.x < -limit)
  42704. this.rotation.x = -limit;
  42705. }
  42706. }
  42707. // Inertia
  42708. if (needToMove) {
  42709. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42710. this.cameraDirection.x = 0;
  42711. }
  42712. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42713. this.cameraDirection.y = 0;
  42714. }
  42715. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42716. this.cameraDirection.z = 0;
  42717. }
  42718. this.cameraDirection.scaleInPlace(this.inertia);
  42719. }
  42720. if (needToRotate) {
  42721. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42722. this.cameraRotation.x = 0;
  42723. }
  42724. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42725. this.cameraRotation.y = 0;
  42726. }
  42727. this.cameraRotation.scaleInPlace(this.inertia);
  42728. }
  42729. _super.prototype._checkInputs.call(this);
  42730. };
  42731. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42732. if (this.rotationQuaternion) {
  42733. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42734. }
  42735. else {
  42736. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42737. }
  42738. //update the up vector!
  42739. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42740. };
  42741. TargetCamera.prototype._getViewMatrix = function () {
  42742. if (this.lockedTarget) {
  42743. this.setTarget(this._getLockedTargetPosition());
  42744. }
  42745. // Compute
  42746. this._updateCameraRotationMatrix();
  42747. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42748. // Computing target and final matrix
  42749. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42750. if (this.getScene().useRightHandedSystem) {
  42751. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42752. }
  42753. else {
  42754. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42755. }
  42756. return this._viewMatrix;
  42757. };
  42758. /**
  42759. * @override
  42760. * Override Camera.createRigCamera
  42761. */
  42762. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42763. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42764. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42765. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42766. if (!this.rotationQuaternion) {
  42767. this.rotationQuaternion = new BABYLON.Quaternion();
  42768. }
  42769. rigCamera._cameraRigParams = {};
  42770. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42771. }
  42772. return rigCamera;
  42773. }
  42774. return null;
  42775. };
  42776. /**
  42777. * @override
  42778. * Override Camera._updateRigCameras
  42779. */
  42780. TargetCamera.prototype._updateRigCameras = function () {
  42781. var camLeft = this._rigCameras[0];
  42782. var camRight = this._rigCameras[1];
  42783. switch (this.cameraRigMode) {
  42784. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42785. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42786. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42787. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42788. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42789. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42790. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42791. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42792. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42793. camLeft.setTarget(this.getTarget());
  42794. camRight.setTarget(this.getTarget());
  42795. break;
  42796. case BABYLON.Camera.RIG_MODE_VR:
  42797. if (camLeft.rotationQuaternion) {
  42798. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42799. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42800. }
  42801. else {
  42802. camLeft.rotation.copyFrom(this.rotation);
  42803. camRight.rotation.copyFrom(this.rotation);
  42804. }
  42805. camLeft.position.copyFrom(this.position);
  42806. camRight.position.copyFrom(this.position);
  42807. break;
  42808. }
  42809. _super.prototype._updateRigCameras.call(this);
  42810. };
  42811. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42812. if (!this._rigCamTransformMatrix) {
  42813. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42814. }
  42815. var target = this.getTarget();
  42816. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42817. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42818. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42819. };
  42820. TargetCamera.prototype.getClassName = function () {
  42821. return "TargetCamera";
  42822. };
  42823. __decorate([
  42824. BABYLON.serializeAsVector3()
  42825. ], TargetCamera.prototype, "rotation", void 0);
  42826. __decorate([
  42827. BABYLON.serialize()
  42828. ], TargetCamera.prototype, "speed", void 0);
  42829. __decorate([
  42830. BABYLON.serializeAsMeshReference("lockedTargetId")
  42831. ], TargetCamera.prototype, "lockedTarget", void 0);
  42832. return TargetCamera;
  42833. }(BABYLON.Camera));
  42834. BABYLON.TargetCamera = TargetCamera;
  42835. })(BABYLON || (BABYLON = {}));
  42836. //# sourceMappingURL=babylon.targetCamera.js.map
  42837. var BABYLON;
  42838. (function (BABYLON) {
  42839. var FreeCameraMouseInput = /** @class */ (function () {
  42840. function FreeCameraMouseInput(touchEnabled) {
  42841. if (touchEnabled === void 0) { touchEnabled = true; }
  42842. this.touchEnabled = touchEnabled;
  42843. this.buttons = [0, 1, 2];
  42844. this.angularSensibility = 2000.0;
  42845. this.previousPosition = null;
  42846. }
  42847. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42848. var _this = this;
  42849. var engine = this.camera.getEngine();
  42850. if (!this._pointerInput) {
  42851. this._pointerInput = function (p, s) {
  42852. var evt = p.event;
  42853. if (engine.isInVRExclusivePointerMode) {
  42854. return;
  42855. }
  42856. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42857. return;
  42858. }
  42859. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42860. return;
  42861. }
  42862. var srcElement = (evt.srcElement || evt.target);
  42863. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42864. try {
  42865. srcElement.setPointerCapture(evt.pointerId);
  42866. }
  42867. catch (e) {
  42868. //Nothing to do with the error. Execution will continue.
  42869. }
  42870. _this.previousPosition = {
  42871. x: evt.clientX,
  42872. y: evt.clientY
  42873. };
  42874. if (!noPreventDefault) {
  42875. evt.preventDefault();
  42876. element.focus();
  42877. }
  42878. }
  42879. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42880. try {
  42881. srcElement.releasePointerCapture(evt.pointerId);
  42882. }
  42883. catch (e) {
  42884. //Nothing to do with the error.
  42885. }
  42886. _this.previousPosition = null;
  42887. if (!noPreventDefault) {
  42888. evt.preventDefault();
  42889. }
  42890. }
  42891. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42892. if (!_this.previousPosition || engine.isPointerLock) {
  42893. return;
  42894. }
  42895. var offsetX = evt.clientX - _this.previousPosition.x;
  42896. var offsetY = evt.clientY - _this.previousPosition.y;
  42897. if (_this.camera.getScene().useRightHandedSystem) {
  42898. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42899. }
  42900. else {
  42901. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42902. }
  42903. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42904. _this.previousPosition = {
  42905. x: evt.clientX,
  42906. y: evt.clientY
  42907. };
  42908. if (!noPreventDefault) {
  42909. evt.preventDefault();
  42910. }
  42911. }
  42912. };
  42913. }
  42914. this._onMouseMove = function (evt) {
  42915. if (!engine.isPointerLock) {
  42916. return;
  42917. }
  42918. if (engine.isInVRExclusivePointerMode) {
  42919. return;
  42920. }
  42921. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42922. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42923. if (_this.camera.getScene().useRightHandedSystem) {
  42924. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42925. }
  42926. else {
  42927. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42928. }
  42929. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42930. _this.previousPosition = null;
  42931. if (!noPreventDefault) {
  42932. evt.preventDefault();
  42933. }
  42934. };
  42935. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42936. element.addEventListener("mousemove", this._onMouseMove, false);
  42937. };
  42938. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42939. if (this._observer && element) {
  42940. this.camera.getScene().onPointerObservable.remove(this._observer);
  42941. if (this._onMouseMove) {
  42942. element.removeEventListener("mousemove", this._onMouseMove);
  42943. }
  42944. this._observer = null;
  42945. this._onMouseMove = null;
  42946. this.previousPosition = null;
  42947. }
  42948. };
  42949. FreeCameraMouseInput.prototype.getClassName = function () {
  42950. return "FreeCameraMouseInput";
  42951. };
  42952. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42953. return "mouse";
  42954. };
  42955. __decorate([
  42956. BABYLON.serialize()
  42957. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42958. __decorate([
  42959. BABYLON.serialize()
  42960. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42961. return FreeCameraMouseInput;
  42962. }());
  42963. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42964. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42965. })(BABYLON || (BABYLON = {}));
  42966. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42967. var BABYLON;
  42968. (function (BABYLON) {
  42969. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42970. function FreeCameraKeyboardMoveInput() {
  42971. this._keys = new Array();
  42972. this.keysUp = [38];
  42973. this.keysDown = [40];
  42974. this.keysLeft = [37];
  42975. this.keysRight = [39];
  42976. }
  42977. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42978. var _this = this;
  42979. if (this._onCanvasBlurObserver) {
  42980. return;
  42981. }
  42982. this._scene = this.camera.getScene();
  42983. this._engine = this._scene.getEngine();
  42984. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42985. _this._keys = [];
  42986. });
  42987. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42988. var evt = info.event;
  42989. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42990. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42991. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42992. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42993. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42994. var index = _this._keys.indexOf(evt.keyCode);
  42995. if (index === -1) {
  42996. _this._keys.push(evt.keyCode);
  42997. }
  42998. if (!noPreventDefault) {
  42999. evt.preventDefault();
  43000. }
  43001. }
  43002. }
  43003. else {
  43004. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43005. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43006. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43007. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43008. var index = _this._keys.indexOf(evt.keyCode);
  43009. if (index >= 0) {
  43010. _this._keys.splice(index, 1);
  43011. }
  43012. if (!noPreventDefault) {
  43013. evt.preventDefault();
  43014. }
  43015. }
  43016. }
  43017. });
  43018. };
  43019. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43020. if (this._scene) {
  43021. if (this._onKeyboardObserver) {
  43022. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43023. }
  43024. if (this._onCanvasBlurObserver) {
  43025. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43026. }
  43027. this._onKeyboardObserver = null;
  43028. this._onCanvasBlurObserver = null;
  43029. }
  43030. this._keys = [];
  43031. };
  43032. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43033. if (this._onKeyboardObserver) {
  43034. var camera = this.camera;
  43035. // Keyboard
  43036. for (var index = 0; index < this._keys.length; index++) {
  43037. var keyCode = this._keys[index];
  43038. var speed = camera._computeLocalCameraSpeed();
  43039. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43040. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43041. }
  43042. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43043. camera._localDirection.copyFromFloats(0, 0, speed);
  43044. }
  43045. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43046. camera._localDirection.copyFromFloats(speed, 0, 0);
  43047. }
  43048. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43049. camera._localDirection.copyFromFloats(0, 0, -speed);
  43050. }
  43051. if (camera.getScene().useRightHandedSystem) {
  43052. camera._localDirection.z *= -1;
  43053. }
  43054. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43055. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43056. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43057. }
  43058. }
  43059. };
  43060. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43061. return "FreeCameraKeyboardMoveInput";
  43062. };
  43063. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43064. this._keys = [];
  43065. };
  43066. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43067. return "keyboard";
  43068. };
  43069. __decorate([
  43070. BABYLON.serialize()
  43071. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43072. __decorate([
  43073. BABYLON.serialize()
  43074. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43075. __decorate([
  43076. BABYLON.serialize()
  43077. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43078. __decorate([
  43079. BABYLON.serialize()
  43080. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43081. return FreeCameraKeyboardMoveInput;
  43082. }());
  43083. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43084. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43085. })(BABYLON || (BABYLON = {}));
  43086. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43087. var BABYLON;
  43088. (function (BABYLON) {
  43089. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43090. __extends(FreeCameraInputsManager, _super);
  43091. function FreeCameraInputsManager(camera) {
  43092. return _super.call(this, camera) || this;
  43093. }
  43094. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43095. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43096. return this;
  43097. };
  43098. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43099. if (touchEnabled === void 0) { touchEnabled = true; }
  43100. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43101. return this;
  43102. };
  43103. FreeCameraInputsManager.prototype.addGamepad = function () {
  43104. this.add(new BABYLON.FreeCameraGamepadInput());
  43105. return this;
  43106. };
  43107. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43108. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43109. return this;
  43110. };
  43111. FreeCameraInputsManager.prototype.addTouch = function () {
  43112. this.add(new BABYLON.FreeCameraTouchInput());
  43113. return this;
  43114. };
  43115. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43116. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43117. return this;
  43118. };
  43119. return FreeCameraInputsManager;
  43120. }(BABYLON.CameraInputsManager));
  43121. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43122. })(BABYLON || (BABYLON = {}));
  43123. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43124. var BABYLON;
  43125. (function (BABYLON) {
  43126. var FreeCamera = /** @class */ (function (_super) {
  43127. __extends(FreeCamera, _super);
  43128. function FreeCamera(name, position, scene) {
  43129. var _this = _super.call(this, name, position, scene) || this;
  43130. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43131. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43132. _this.checkCollisions = false;
  43133. _this.applyGravity = false;
  43134. _this._needMoveForGravity = false;
  43135. _this._oldPosition = BABYLON.Vector3.Zero();
  43136. _this._diffPosition = BABYLON.Vector3.Zero();
  43137. _this._newPosition = BABYLON.Vector3.Zero();
  43138. // Collisions
  43139. _this._collisionMask = -1;
  43140. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43141. if (collidedMesh === void 0) { collidedMesh = null; }
  43142. //TODO move this to the collision coordinator!
  43143. if (_this.getScene().workerCollisions)
  43144. newPosition.multiplyInPlace(_this._collider._radius);
  43145. var updatePosition = function (newPos) {
  43146. _this._newPosition.copyFrom(newPos);
  43147. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43148. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43149. _this.position.addInPlace(_this._diffPosition);
  43150. if (_this.onCollide && collidedMesh) {
  43151. _this.onCollide(collidedMesh);
  43152. }
  43153. }
  43154. };
  43155. updatePosition(newPosition);
  43156. };
  43157. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43158. _this.inputs.addKeyboard().addMouse();
  43159. return _this;
  43160. }
  43161. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43162. //-- begin properties for backward compatibility for inputs
  43163. /**
  43164. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43165. * Higher values reduce sensitivity.
  43166. */
  43167. get: function () {
  43168. var mouse = this.inputs.attached["mouse"];
  43169. if (mouse)
  43170. return mouse.angularSensibility;
  43171. return 0;
  43172. },
  43173. /**
  43174. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43175. * Higher values reduce sensitivity.
  43176. */
  43177. set: function (value) {
  43178. var mouse = this.inputs.attached["mouse"];
  43179. if (mouse)
  43180. mouse.angularSensibility = value;
  43181. },
  43182. enumerable: true,
  43183. configurable: true
  43184. });
  43185. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43186. get: function () {
  43187. var keyboard = this.inputs.attached["keyboard"];
  43188. if (keyboard)
  43189. return keyboard.keysUp;
  43190. return [];
  43191. },
  43192. set: function (value) {
  43193. var keyboard = this.inputs.attached["keyboard"];
  43194. if (keyboard)
  43195. keyboard.keysUp = value;
  43196. },
  43197. enumerable: true,
  43198. configurable: true
  43199. });
  43200. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43201. get: function () {
  43202. var keyboard = this.inputs.attached["keyboard"];
  43203. if (keyboard)
  43204. return keyboard.keysDown;
  43205. return [];
  43206. },
  43207. set: function (value) {
  43208. var keyboard = this.inputs.attached["keyboard"];
  43209. if (keyboard)
  43210. keyboard.keysDown = value;
  43211. },
  43212. enumerable: true,
  43213. configurable: true
  43214. });
  43215. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43216. get: function () {
  43217. var keyboard = this.inputs.attached["keyboard"];
  43218. if (keyboard)
  43219. return keyboard.keysLeft;
  43220. return [];
  43221. },
  43222. set: function (value) {
  43223. var keyboard = this.inputs.attached["keyboard"];
  43224. if (keyboard)
  43225. keyboard.keysLeft = value;
  43226. },
  43227. enumerable: true,
  43228. configurable: true
  43229. });
  43230. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43231. get: function () {
  43232. var keyboard = this.inputs.attached["keyboard"];
  43233. if (keyboard)
  43234. return keyboard.keysRight;
  43235. return [];
  43236. },
  43237. set: function (value) {
  43238. var keyboard = this.inputs.attached["keyboard"];
  43239. if (keyboard)
  43240. keyboard.keysRight = value;
  43241. },
  43242. enumerable: true,
  43243. configurable: true
  43244. });
  43245. // Controls
  43246. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43247. this.inputs.attachElement(element, noPreventDefault);
  43248. };
  43249. FreeCamera.prototype.detachControl = function (element) {
  43250. this.inputs.detachElement(element);
  43251. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43252. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43253. };
  43254. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43255. get: function () {
  43256. return this._collisionMask;
  43257. },
  43258. set: function (mask) {
  43259. this._collisionMask = !isNaN(mask) ? mask : -1;
  43260. },
  43261. enumerable: true,
  43262. configurable: true
  43263. });
  43264. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43265. var globalPosition;
  43266. if (this.parent) {
  43267. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43268. }
  43269. else {
  43270. globalPosition = this.position;
  43271. }
  43272. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43273. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43274. if (!this._collider) {
  43275. this._collider = new BABYLON.Collider();
  43276. }
  43277. this._collider._radius = this.ellipsoid;
  43278. this._collider.collisionMask = this._collisionMask;
  43279. //no need for clone, as long as gravity is not on.
  43280. var actualDisplacement = displacement;
  43281. //add gravity to the direction to prevent the dual-collision checking
  43282. if (this.applyGravity) {
  43283. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43284. actualDisplacement = displacement.add(this.getScene().gravity);
  43285. }
  43286. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43287. };
  43288. FreeCamera.prototype._checkInputs = function () {
  43289. if (!this._localDirection) {
  43290. this._localDirection = BABYLON.Vector3.Zero();
  43291. this._transformedDirection = BABYLON.Vector3.Zero();
  43292. }
  43293. this.inputs.checkInputs();
  43294. _super.prototype._checkInputs.call(this);
  43295. };
  43296. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43297. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43298. };
  43299. FreeCamera.prototype._updatePosition = function () {
  43300. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43301. this._collideWithWorld(this.cameraDirection);
  43302. }
  43303. else {
  43304. _super.prototype._updatePosition.call(this);
  43305. }
  43306. };
  43307. FreeCamera.prototype.dispose = function () {
  43308. this.inputs.clear();
  43309. _super.prototype.dispose.call(this);
  43310. };
  43311. FreeCamera.prototype.getClassName = function () {
  43312. return "FreeCamera";
  43313. };
  43314. __decorate([
  43315. BABYLON.serializeAsVector3()
  43316. ], FreeCamera.prototype, "ellipsoid", void 0);
  43317. __decorate([
  43318. BABYLON.serializeAsVector3()
  43319. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43320. __decorate([
  43321. BABYLON.serialize()
  43322. ], FreeCamera.prototype, "checkCollisions", void 0);
  43323. __decorate([
  43324. BABYLON.serialize()
  43325. ], FreeCamera.prototype, "applyGravity", void 0);
  43326. return FreeCamera;
  43327. }(BABYLON.TargetCamera));
  43328. BABYLON.FreeCamera = FreeCamera;
  43329. })(BABYLON || (BABYLON = {}));
  43330. //# sourceMappingURL=babylon.freeCamera.js.map
  43331. var BABYLON;
  43332. (function (BABYLON) {
  43333. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43334. function ArcRotateCameraKeyboardMoveInput() {
  43335. this._keys = new Array();
  43336. this.keysUp = [38];
  43337. this.keysDown = [40];
  43338. this.keysLeft = [37];
  43339. this.keysRight = [39];
  43340. this.keysReset = [220];
  43341. this.panningSensibility = 50.0;
  43342. this.zoomingSensibility = 25.0;
  43343. this.useAltToZoom = true;
  43344. }
  43345. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43346. var _this = this;
  43347. if (this._onCanvasBlurObserver) {
  43348. return;
  43349. }
  43350. this._scene = this.camera.getScene();
  43351. this._engine = this._scene.getEngine();
  43352. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43353. _this._keys = [];
  43354. });
  43355. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43356. var evt = info.event;
  43357. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43358. _this._ctrlPressed = evt.ctrlKey;
  43359. _this._altPressed = evt.altKey;
  43360. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43361. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43362. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43363. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43364. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43365. var index = _this._keys.indexOf(evt.keyCode);
  43366. if (index === -1) {
  43367. _this._keys.push(evt.keyCode);
  43368. }
  43369. if (evt.preventDefault) {
  43370. if (!noPreventDefault) {
  43371. evt.preventDefault();
  43372. }
  43373. }
  43374. }
  43375. }
  43376. else {
  43377. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43378. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43379. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43380. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43381. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43382. var index = _this._keys.indexOf(evt.keyCode);
  43383. if (index >= 0) {
  43384. _this._keys.splice(index, 1);
  43385. }
  43386. if (evt.preventDefault) {
  43387. if (!noPreventDefault) {
  43388. evt.preventDefault();
  43389. }
  43390. }
  43391. }
  43392. }
  43393. });
  43394. };
  43395. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43396. if (this._scene) {
  43397. if (this._onKeyboardObserver) {
  43398. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43399. }
  43400. if (this._onCanvasBlurObserver) {
  43401. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43402. }
  43403. this._onKeyboardObserver = null;
  43404. this._onCanvasBlurObserver = null;
  43405. }
  43406. this._keys = [];
  43407. };
  43408. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43409. if (this._onKeyboardObserver) {
  43410. var camera = this.camera;
  43411. for (var index = 0; index < this._keys.length; index++) {
  43412. var keyCode = this._keys[index];
  43413. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43414. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43415. camera.inertialPanningX -= 1 / this.panningSensibility;
  43416. }
  43417. else {
  43418. camera.inertialAlphaOffset -= 0.01;
  43419. }
  43420. }
  43421. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43422. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43423. camera.inertialPanningY += 1 / this.panningSensibility;
  43424. }
  43425. else if (this._altPressed && this.useAltToZoom) {
  43426. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43427. }
  43428. else {
  43429. camera.inertialBetaOffset -= 0.01;
  43430. }
  43431. }
  43432. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43433. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43434. camera.inertialPanningX += 1 / this.panningSensibility;
  43435. }
  43436. else {
  43437. camera.inertialAlphaOffset += 0.01;
  43438. }
  43439. }
  43440. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43441. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43442. camera.inertialPanningY -= 1 / this.panningSensibility;
  43443. }
  43444. else if (this._altPressed && this.useAltToZoom) {
  43445. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43446. }
  43447. else {
  43448. camera.inertialBetaOffset += 0.01;
  43449. }
  43450. }
  43451. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43452. camera.restoreState();
  43453. }
  43454. }
  43455. }
  43456. };
  43457. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43458. return "ArcRotateCameraKeyboardMoveInput";
  43459. };
  43460. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43461. return "keyboard";
  43462. };
  43463. __decorate([
  43464. BABYLON.serialize()
  43465. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43466. __decorate([
  43467. BABYLON.serialize()
  43468. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43469. __decorate([
  43470. BABYLON.serialize()
  43471. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43472. __decorate([
  43473. BABYLON.serialize()
  43474. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43475. __decorate([
  43476. BABYLON.serialize()
  43477. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43478. __decorate([
  43479. BABYLON.serialize()
  43480. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43481. __decorate([
  43482. BABYLON.serialize()
  43483. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43484. __decorate([
  43485. BABYLON.serialize()
  43486. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43487. return ArcRotateCameraKeyboardMoveInput;
  43488. }());
  43489. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43490. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43491. })(BABYLON || (BABYLON = {}));
  43492. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43493. var BABYLON;
  43494. (function (BABYLON) {
  43495. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43496. function ArcRotateCameraMouseWheelInput() {
  43497. this.wheelPrecision = 3.0;
  43498. /**
  43499. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43500. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43501. */
  43502. this.wheelDeltaPercentage = 0;
  43503. }
  43504. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43505. var _this = this;
  43506. this._wheel = function (p, s) {
  43507. //sanity check - this should be a PointerWheel event.
  43508. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43509. return;
  43510. var event = p.event;
  43511. var delta = 0;
  43512. if (event.wheelDelta) {
  43513. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43514. }
  43515. else if (event.detail) {
  43516. delta = -event.detail / _this.wheelPrecision;
  43517. }
  43518. if (delta)
  43519. _this.camera.inertialRadiusOffset += delta;
  43520. if (event.preventDefault) {
  43521. if (!noPreventDefault) {
  43522. event.preventDefault();
  43523. }
  43524. }
  43525. };
  43526. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43527. };
  43528. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43529. if (this._observer && element) {
  43530. this.camera.getScene().onPointerObservable.remove(this._observer);
  43531. this._observer = null;
  43532. this._wheel = null;
  43533. }
  43534. };
  43535. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43536. return "ArcRotateCameraMouseWheelInput";
  43537. };
  43538. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43539. return "mousewheel";
  43540. };
  43541. __decorate([
  43542. BABYLON.serialize()
  43543. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43544. __decorate([
  43545. BABYLON.serialize()
  43546. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43547. return ArcRotateCameraMouseWheelInput;
  43548. }());
  43549. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43550. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43551. })(BABYLON || (BABYLON = {}));
  43552. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43553. var BABYLON;
  43554. (function (BABYLON) {
  43555. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43556. function ArcRotateCameraPointersInput() {
  43557. this.buttons = [0, 1, 2];
  43558. this.angularSensibilityX = 1000.0;
  43559. this.angularSensibilityY = 1000.0;
  43560. this.pinchPrecision = 12.0;
  43561. /**
  43562. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43563. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43564. */
  43565. this.pinchDeltaPercentage = 0;
  43566. this.panningSensibility = 1000.0;
  43567. this.multiTouchPanning = true;
  43568. this.multiTouchPanAndZoom = true;
  43569. this._isPanClick = false;
  43570. this.pinchInwards = true;
  43571. }
  43572. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43573. var _this = this;
  43574. var engine = this.camera.getEngine();
  43575. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43576. var pointA = null;
  43577. var pointB = null;
  43578. var previousPinchSquaredDistance = 0;
  43579. var initialDistance = 0;
  43580. var twoFingerActivityCount = 0;
  43581. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43582. this._pointerInput = function (p, s) {
  43583. var evt = p.event;
  43584. var isTouch = p.event.pointerType === "touch";
  43585. if (engine.isInVRExclusivePointerMode) {
  43586. return;
  43587. }
  43588. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43589. return;
  43590. }
  43591. var srcElement = (evt.srcElement || evt.target);
  43592. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43593. try {
  43594. srcElement.setPointerCapture(evt.pointerId);
  43595. }
  43596. catch (e) {
  43597. //Nothing to do with the error. Execution will continue.
  43598. }
  43599. // Manage panning with pan button click
  43600. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43601. // manage pointers
  43602. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43603. if (pointA === null) {
  43604. pointA = cacheSoloPointer;
  43605. }
  43606. else if (pointB === null) {
  43607. pointB = cacheSoloPointer;
  43608. }
  43609. if (!noPreventDefault) {
  43610. evt.preventDefault();
  43611. element.focus();
  43612. }
  43613. }
  43614. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43615. _this.camera.restoreState();
  43616. }
  43617. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43618. try {
  43619. srcElement.releasePointerCapture(evt.pointerId);
  43620. }
  43621. catch (e) {
  43622. //Nothing to do with the error.
  43623. }
  43624. cacheSoloPointer = null;
  43625. previousPinchSquaredDistance = 0;
  43626. previousMultiTouchPanPosition.isPaning = false;
  43627. previousMultiTouchPanPosition.isPinching = false;
  43628. twoFingerActivityCount = 0;
  43629. initialDistance = 0;
  43630. if (!isTouch) {
  43631. pointB = null; // Mouse and pen are mono pointer
  43632. }
  43633. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43634. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43635. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43636. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43637. if (engine.badOS) {
  43638. pointA = pointB = null;
  43639. }
  43640. else {
  43641. //only remove the impacted pointer in case of multitouch allowing on most
  43642. //platforms switching from rotate to zoom and pan seamlessly.
  43643. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43644. pointA = pointB;
  43645. pointB = null;
  43646. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43647. }
  43648. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43649. pointB = null;
  43650. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43651. }
  43652. else {
  43653. pointA = pointB = null;
  43654. }
  43655. }
  43656. if (!noPreventDefault) {
  43657. evt.preventDefault();
  43658. }
  43659. }
  43660. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43661. if (!noPreventDefault) {
  43662. evt.preventDefault();
  43663. }
  43664. // One button down
  43665. if (pointA && pointB === null && cacheSoloPointer) {
  43666. if (_this.panningSensibility !== 0 &&
  43667. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43668. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43669. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43670. }
  43671. else {
  43672. var offsetX = evt.clientX - cacheSoloPointer.x;
  43673. var offsetY = evt.clientY - cacheSoloPointer.y;
  43674. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43675. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43676. }
  43677. cacheSoloPointer.x = evt.clientX;
  43678. cacheSoloPointer.y = evt.clientY;
  43679. }
  43680. else if (pointA && pointB) {
  43681. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43682. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43683. ed.x = evt.clientX;
  43684. ed.y = evt.clientY;
  43685. var direction = _this.pinchInwards ? 1 : -1;
  43686. var distX = pointA.x - pointB.x;
  43687. var distY = pointA.y - pointB.y;
  43688. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43689. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43690. if (previousPinchSquaredDistance === 0) {
  43691. initialDistance = pinchDistance;
  43692. previousPinchSquaredDistance = pinchSquaredDistance;
  43693. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43694. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43695. return;
  43696. }
  43697. if (_this.multiTouchPanAndZoom) {
  43698. if (_this.pinchDeltaPercentage) {
  43699. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43700. }
  43701. else {
  43702. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43703. (_this.pinchPrecision *
  43704. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43705. direction);
  43706. }
  43707. if (_this.panningSensibility !== 0) {
  43708. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43709. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43710. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43711. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43712. previousMultiTouchPanPosition.x = pointersCenterX;
  43713. previousMultiTouchPanPosition.y = pointersCenterY;
  43714. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43715. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43716. }
  43717. }
  43718. else {
  43719. twoFingerActivityCount++;
  43720. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43721. if (_this.pinchDeltaPercentage) {
  43722. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43723. }
  43724. else {
  43725. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43726. (_this.pinchPrecision *
  43727. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43728. direction);
  43729. }
  43730. previousMultiTouchPanPosition.isPaning = false;
  43731. previousMultiTouchPanPosition.isPinching = true;
  43732. }
  43733. else {
  43734. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43735. if (!previousMultiTouchPanPosition.isPaning) {
  43736. previousMultiTouchPanPosition.isPaning = true;
  43737. previousMultiTouchPanPosition.isPinching = false;
  43738. previousMultiTouchPanPosition.x = ed.x;
  43739. previousMultiTouchPanPosition.y = ed.y;
  43740. return;
  43741. }
  43742. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43743. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43744. }
  43745. }
  43746. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43747. previousMultiTouchPanPosition.x = ed.x;
  43748. previousMultiTouchPanPosition.y = ed.y;
  43749. }
  43750. }
  43751. previousPinchSquaredDistance = pinchSquaredDistance;
  43752. }
  43753. }
  43754. };
  43755. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43756. this._onContextMenu = function (evt) {
  43757. evt.preventDefault();
  43758. };
  43759. if (!this.camera._useCtrlForPanning) {
  43760. element.addEventListener("contextmenu", this._onContextMenu, false);
  43761. }
  43762. this._onLostFocus = function () {
  43763. //this._keys = [];
  43764. pointA = pointB = null;
  43765. previousPinchSquaredDistance = 0;
  43766. previousMultiTouchPanPosition.isPaning = false;
  43767. previousMultiTouchPanPosition.isPinching = false;
  43768. twoFingerActivityCount = 0;
  43769. cacheSoloPointer = null;
  43770. initialDistance = 0;
  43771. };
  43772. this._onMouseMove = function (evt) {
  43773. if (!engine.isPointerLock) {
  43774. return;
  43775. }
  43776. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43777. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43778. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43779. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43780. if (!noPreventDefault) {
  43781. evt.preventDefault();
  43782. }
  43783. };
  43784. this._onGestureStart = function (e) {
  43785. if (window.MSGesture === undefined) {
  43786. return;
  43787. }
  43788. if (!_this._MSGestureHandler) {
  43789. _this._MSGestureHandler = new MSGesture();
  43790. _this._MSGestureHandler.target = element;
  43791. }
  43792. _this._MSGestureHandler.addPointer(e.pointerId);
  43793. };
  43794. this._onGesture = function (e) {
  43795. _this.camera.radius *= e.scale;
  43796. if (e.preventDefault) {
  43797. if (!noPreventDefault) {
  43798. e.stopPropagation();
  43799. e.preventDefault();
  43800. }
  43801. }
  43802. };
  43803. element.addEventListener("mousemove", this._onMouseMove, false);
  43804. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43805. element.addEventListener("MSGestureChange", this._onGesture, false);
  43806. BABYLON.Tools.RegisterTopRootEvents([
  43807. { name: "blur", handler: this._onLostFocus }
  43808. ]);
  43809. };
  43810. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43811. if (this._onLostFocus) {
  43812. BABYLON.Tools.UnregisterTopRootEvents([
  43813. { name: "blur", handler: this._onLostFocus }
  43814. ]);
  43815. }
  43816. if (element && this._observer) {
  43817. this.camera.getScene().onPointerObservable.remove(this._observer);
  43818. this._observer = null;
  43819. if (this._onContextMenu) {
  43820. element.removeEventListener("contextmenu", this._onContextMenu);
  43821. }
  43822. if (this._onMouseMove) {
  43823. element.removeEventListener("mousemove", this._onMouseMove);
  43824. }
  43825. if (this._onGestureStart) {
  43826. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43827. }
  43828. if (this._onGesture) {
  43829. element.removeEventListener("MSGestureChange", this._onGesture);
  43830. }
  43831. this._isPanClick = false;
  43832. this.pinchInwards = true;
  43833. this._onMouseMove = null;
  43834. this._onGestureStart = null;
  43835. this._onGesture = null;
  43836. this._MSGestureHandler = null;
  43837. this._onLostFocus = null;
  43838. this._onContextMenu = null;
  43839. }
  43840. };
  43841. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43842. return "ArcRotateCameraPointersInput";
  43843. };
  43844. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43845. return "pointers";
  43846. };
  43847. __decorate([
  43848. BABYLON.serialize()
  43849. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43850. __decorate([
  43851. BABYLON.serialize()
  43852. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43853. __decorate([
  43854. BABYLON.serialize()
  43855. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43856. __decorate([
  43857. BABYLON.serialize()
  43858. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43859. __decorate([
  43860. BABYLON.serialize()
  43861. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43862. __decorate([
  43863. BABYLON.serialize()
  43864. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43865. __decorate([
  43866. BABYLON.serialize()
  43867. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43868. __decorate([
  43869. BABYLON.serialize()
  43870. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43871. return ArcRotateCameraPointersInput;
  43872. }());
  43873. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43874. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43875. })(BABYLON || (BABYLON = {}));
  43876. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43877. var BABYLON;
  43878. (function (BABYLON) {
  43879. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43880. __extends(ArcRotateCameraInputsManager, _super);
  43881. function ArcRotateCameraInputsManager(camera) {
  43882. return _super.call(this, camera) || this;
  43883. }
  43884. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43885. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43886. return this;
  43887. };
  43888. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43889. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43890. return this;
  43891. };
  43892. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43893. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43894. return this;
  43895. };
  43896. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43897. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43898. return this;
  43899. };
  43900. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43901. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43902. return this;
  43903. };
  43904. return ArcRotateCameraInputsManager;
  43905. }(BABYLON.CameraInputsManager));
  43906. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43907. })(BABYLON || (BABYLON = {}));
  43908. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43909. var BABYLON;
  43910. (function (BABYLON) {
  43911. var ArcRotateCamera = /** @class */ (function (_super) {
  43912. __extends(ArcRotateCamera, _super);
  43913. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43914. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43915. _this.inertialAlphaOffset = 0;
  43916. _this.inertialBetaOffset = 0;
  43917. _this.inertialRadiusOffset = 0;
  43918. _this.lowerAlphaLimit = null;
  43919. _this.upperAlphaLimit = null;
  43920. _this.lowerBetaLimit = 0.01;
  43921. _this.upperBetaLimit = Math.PI;
  43922. _this.lowerRadiusLimit = null;
  43923. _this.upperRadiusLimit = null;
  43924. _this.inertialPanningX = 0;
  43925. _this.inertialPanningY = 0;
  43926. _this.pinchToPanMaxDistance = 20;
  43927. _this.panningDistanceLimit = null;
  43928. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43929. _this.panningInertia = 0.9;
  43930. //-- end properties for backward compatibility for inputs
  43931. _this.zoomOnFactor = 1;
  43932. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43933. _this.allowUpsideDown = true;
  43934. _this._viewMatrix = new BABYLON.Matrix();
  43935. // Panning
  43936. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43937. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43938. _this.checkCollisions = false;
  43939. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43940. _this._previousPosition = BABYLON.Vector3.Zero();
  43941. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43942. _this._newPosition = BABYLON.Vector3.Zero();
  43943. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43944. if (collidedMesh === void 0) { collidedMesh = null; }
  43945. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43946. newPosition.multiplyInPlace(_this._collider._radius);
  43947. }
  43948. if (!collidedMesh) {
  43949. _this._previousPosition.copyFrom(_this.position);
  43950. }
  43951. else {
  43952. _this.setPosition(newPosition);
  43953. if (_this.onCollide) {
  43954. _this.onCollide(collidedMesh);
  43955. }
  43956. }
  43957. // Recompute because of constraints
  43958. var cosa = Math.cos(_this.alpha);
  43959. var sina = Math.sin(_this.alpha);
  43960. var cosb = Math.cos(_this.beta);
  43961. var sinb = Math.sin(_this.beta);
  43962. if (sinb === 0) {
  43963. sinb = 0.0001;
  43964. }
  43965. var target = _this._getTargetPosition();
  43966. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43967. _this.position.copyFrom(_this._newPosition);
  43968. var up = _this.upVector;
  43969. if (_this.allowUpsideDown && _this.beta < 0) {
  43970. up = up.clone();
  43971. up = up.negate();
  43972. }
  43973. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43974. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43975. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43976. _this._collisionTriggered = false;
  43977. };
  43978. _this._target = BABYLON.Vector3.Zero();
  43979. if (target) {
  43980. _this.setTarget(target);
  43981. }
  43982. _this.alpha = alpha;
  43983. _this.beta = beta;
  43984. _this.radius = radius;
  43985. _this.getViewMatrix();
  43986. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43987. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43988. return _this;
  43989. }
  43990. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43991. get: function () {
  43992. return this._target;
  43993. },
  43994. set: function (value) {
  43995. this.setTarget(value);
  43996. },
  43997. enumerable: true,
  43998. configurable: true
  43999. });
  44000. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44001. //-- begin properties for backward compatibility for inputs
  44002. get: function () {
  44003. var pointers = this.inputs.attached["pointers"];
  44004. if (pointers)
  44005. return pointers.angularSensibilityX;
  44006. return 0;
  44007. },
  44008. set: function (value) {
  44009. var pointers = this.inputs.attached["pointers"];
  44010. if (pointers) {
  44011. pointers.angularSensibilityX = value;
  44012. }
  44013. },
  44014. enumerable: true,
  44015. configurable: true
  44016. });
  44017. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44018. get: function () {
  44019. var pointers = this.inputs.attached["pointers"];
  44020. if (pointers)
  44021. return pointers.angularSensibilityY;
  44022. return 0;
  44023. },
  44024. set: function (value) {
  44025. var pointers = this.inputs.attached["pointers"];
  44026. if (pointers) {
  44027. pointers.angularSensibilityY = value;
  44028. }
  44029. },
  44030. enumerable: true,
  44031. configurable: true
  44032. });
  44033. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44034. get: function () {
  44035. var pointers = this.inputs.attached["pointers"];
  44036. if (pointers)
  44037. return pointers.pinchPrecision;
  44038. return 0;
  44039. },
  44040. set: function (value) {
  44041. var pointers = this.inputs.attached["pointers"];
  44042. if (pointers) {
  44043. pointers.pinchPrecision = value;
  44044. }
  44045. },
  44046. enumerable: true,
  44047. configurable: true
  44048. });
  44049. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44050. get: function () {
  44051. var pointers = this.inputs.attached["pointers"];
  44052. if (pointers)
  44053. return pointers.pinchDeltaPercentage;
  44054. return 0;
  44055. },
  44056. set: function (value) {
  44057. var pointers = this.inputs.attached["pointers"];
  44058. if (pointers) {
  44059. pointers.pinchDeltaPercentage = value;
  44060. }
  44061. },
  44062. enumerable: true,
  44063. configurable: true
  44064. });
  44065. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44066. get: function () {
  44067. var pointers = this.inputs.attached["pointers"];
  44068. if (pointers)
  44069. return pointers.panningSensibility;
  44070. return 0;
  44071. },
  44072. set: function (value) {
  44073. var pointers = this.inputs.attached["pointers"];
  44074. if (pointers) {
  44075. pointers.panningSensibility = value;
  44076. }
  44077. },
  44078. enumerable: true,
  44079. configurable: true
  44080. });
  44081. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44082. get: function () {
  44083. var keyboard = this.inputs.attached["keyboard"];
  44084. if (keyboard)
  44085. return keyboard.keysUp;
  44086. return [];
  44087. },
  44088. set: function (value) {
  44089. var keyboard = this.inputs.attached["keyboard"];
  44090. if (keyboard)
  44091. keyboard.keysUp = value;
  44092. },
  44093. enumerable: true,
  44094. configurable: true
  44095. });
  44096. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44097. get: function () {
  44098. var keyboard = this.inputs.attached["keyboard"];
  44099. if (keyboard)
  44100. return keyboard.keysDown;
  44101. return [];
  44102. },
  44103. set: function (value) {
  44104. var keyboard = this.inputs.attached["keyboard"];
  44105. if (keyboard)
  44106. keyboard.keysDown = value;
  44107. },
  44108. enumerable: true,
  44109. configurable: true
  44110. });
  44111. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44112. get: function () {
  44113. var keyboard = this.inputs.attached["keyboard"];
  44114. if (keyboard)
  44115. return keyboard.keysLeft;
  44116. return [];
  44117. },
  44118. set: function (value) {
  44119. var keyboard = this.inputs.attached["keyboard"];
  44120. if (keyboard)
  44121. keyboard.keysLeft = value;
  44122. },
  44123. enumerable: true,
  44124. configurable: true
  44125. });
  44126. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44127. get: function () {
  44128. var keyboard = this.inputs.attached["keyboard"];
  44129. if (keyboard)
  44130. return keyboard.keysRight;
  44131. return [];
  44132. },
  44133. set: function (value) {
  44134. var keyboard = this.inputs.attached["keyboard"];
  44135. if (keyboard)
  44136. keyboard.keysRight = value;
  44137. },
  44138. enumerable: true,
  44139. configurable: true
  44140. });
  44141. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44142. get: function () {
  44143. var mousewheel = this.inputs.attached["mousewheel"];
  44144. if (mousewheel)
  44145. return mousewheel.wheelPrecision;
  44146. return 0;
  44147. },
  44148. set: function (value) {
  44149. var mousewheel = this.inputs.attached["mousewheel"];
  44150. if (mousewheel)
  44151. mousewheel.wheelPrecision = value;
  44152. },
  44153. enumerable: true,
  44154. configurable: true
  44155. });
  44156. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44157. get: function () {
  44158. var mousewheel = this.inputs.attached["mousewheel"];
  44159. if (mousewheel)
  44160. return mousewheel.wheelDeltaPercentage;
  44161. return 0;
  44162. },
  44163. set: function (value) {
  44164. var mousewheel = this.inputs.attached["mousewheel"];
  44165. if (mousewheel)
  44166. mousewheel.wheelDeltaPercentage = value;
  44167. },
  44168. enumerable: true,
  44169. configurable: true
  44170. });
  44171. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44172. get: function () {
  44173. return this._bouncingBehavior;
  44174. },
  44175. enumerable: true,
  44176. configurable: true
  44177. });
  44178. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44179. get: function () {
  44180. return this._bouncingBehavior != null;
  44181. },
  44182. set: function (value) {
  44183. if (value === this.useBouncingBehavior) {
  44184. return;
  44185. }
  44186. if (value) {
  44187. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44188. this.addBehavior(this._bouncingBehavior);
  44189. }
  44190. else if (this._bouncingBehavior) {
  44191. this.removeBehavior(this._bouncingBehavior);
  44192. this._bouncingBehavior = null;
  44193. }
  44194. },
  44195. enumerable: true,
  44196. configurable: true
  44197. });
  44198. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44199. get: function () {
  44200. return this._framingBehavior;
  44201. },
  44202. enumerable: true,
  44203. configurable: true
  44204. });
  44205. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44206. get: function () {
  44207. return this._framingBehavior != null;
  44208. },
  44209. set: function (value) {
  44210. if (value === this.useFramingBehavior) {
  44211. return;
  44212. }
  44213. if (value) {
  44214. this._framingBehavior = new BABYLON.FramingBehavior();
  44215. this.addBehavior(this._framingBehavior);
  44216. }
  44217. else if (this._framingBehavior) {
  44218. this.removeBehavior(this._framingBehavior);
  44219. this._framingBehavior = null;
  44220. }
  44221. },
  44222. enumerable: true,
  44223. configurable: true
  44224. });
  44225. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44226. get: function () {
  44227. return this._autoRotationBehavior;
  44228. },
  44229. enumerable: true,
  44230. configurable: true
  44231. });
  44232. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44233. get: function () {
  44234. return this._autoRotationBehavior != null;
  44235. },
  44236. set: function (value) {
  44237. if (value === this.useAutoRotationBehavior) {
  44238. return;
  44239. }
  44240. if (value) {
  44241. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44242. this.addBehavior(this._autoRotationBehavior);
  44243. }
  44244. else if (this._autoRotationBehavior) {
  44245. this.removeBehavior(this._autoRotationBehavior);
  44246. this._autoRotationBehavior = null;
  44247. }
  44248. },
  44249. enumerable: true,
  44250. configurable: true
  44251. });
  44252. // Cache
  44253. ArcRotateCamera.prototype._initCache = function () {
  44254. _super.prototype._initCache.call(this);
  44255. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44256. this._cache.alpha = undefined;
  44257. this._cache.beta = undefined;
  44258. this._cache.radius = undefined;
  44259. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44260. };
  44261. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44262. if (!ignoreParentClass) {
  44263. _super.prototype._updateCache.call(this);
  44264. }
  44265. this._cache._target.copyFrom(this._getTargetPosition());
  44266. this._cache.alpha = this.alpha;
  44267. this._cache.beta = this.beta;
  44268. this._cache.radius = this.radius;
  44269. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44270. };
  44271. ArcRotateCamera.prototype._getTargetPosition = function () {
  44272. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44273. var pos = this._targetHost.getAbsolutePosition();
  44274. if (this._targetBoundingCenter) {
  44275. pos.addToRef(this._targetBoundingCenter, this._target);
  44276. }
  44277. else {
  44278. this._target.copyFrom(pos);
  44279. }
  44280. }
  44281. var lockedTargetPosition = this._getLockedTargetPosition();
  44282. if (lockedTargetPosition) {
  44283. return lockedTargetPosition;
  44284. }
  44285. return this._target;
  44286. };
  44287. ArcRotateCamera.prototype.storeState = function () {
  44288. this._storedAlpha = this.alpha;
  44289. this._storedBeta = this.beta;
  44290. this._storedRadius = this.radius;
  44291. this._storedTarget = this._getTargetPosition().clone();
  44292. return _super.prototype.storeState.call(this);
  44293. };
  44294. /**
  44295. * Restored camera state. You must call storeState() first
  44296. */
  44297. ArcRotateCamera.prototype._restoreStateValues = function () {
  44298. if (!_super.prototype._restoreStateValues.call(this)) {
  44299. return false;
  44300. }
  44301. this.alpha = this._storedAlpha;
  44302. this.beta = this._storedBeta;
  44303. this.radius = this._storedRadius;
  44304. this.setTarget(this._storedTarget.clone());
  44305. this.inertialAlphaOffset = 0;
  44306. this.inertialBetaOffset = 0;
  44307. this.inertialRadiusOffset = 0;
  44308. this.inertialPanningX = 0;
  44309. this.inertialPanningY = 0;
  44310. return true;
  44311. };
  44312. // Synchronized
  44313. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44314. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44315. return false;
  44316. return this._cache._target.equals(this._getTargetPosition())
  44317. && this._cache.alpha === this.alpha
  44318. && this._cache.beta === this.beta
  44319. && this._cache.radius === this.radius
  44320. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44321. };
  44322. // Methods
  44323. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44324. var _this = this;
  44325. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44326. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44327. this._useCtrlForPanning = useCtrlForPanning;
  44328. this._panningMouseButton = panningMouseButton;
  44329. this.inputs.attachElement(element, noPreventDefault);
  44330. this._reset = function () {
  44331. _this.inertialAlphaOffset = 0;
  44332. _this.inertialBetaOffset = 0;
  44333. _this.inertialRadiusOffset = 0;
  44334. _this.inertialPanningX = 0;
  44335. _this.inertialPanningY = 0;
  44336. };
  44337. };
  44338. ArcRotateCamera.prototype.detachControl = function (element) {
  44339. this.inputs.detachElement(element);
  44340. if (this._reset) {
  44341. this._reset();
  44342. }
  44343. };
  44344. ArcRotateCamera.prototype._checkInputs = function () {
  44345. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44346. if (this._collisionTriggered) {
  44347. return;
  44348. }
  44349. this.inputs.checkInputs();
  44350. // Inertia
  44351. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44352. if (this.getScene().useRightHandedSystem) {
  44353. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44354. }
  44355. else {
  44356. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44357. }
  44358. this.beta += this.inertialBetaOffset;
  44359. this.radius -= this.inertialRadiusOffset;
  44360. this.inertialAlphaOffset *= this.inertia;
  44361. this.inertialBetaOffset *= this.inertia;
  44362. this.inertialRadiusOffset *= this.inertia;
  44363. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44364. this.inertialAlphaOffset = 0;
  44365. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44366. this.inertialBetaOffset = 0;
  44367. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44368. this.inertialRadiusOffset = 0;
  44369. }
  44370. // Panning inertia
  44371. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44372. if (!this._localDirection) {
  44373. this._localDirection = BABYLON.Vector3.Zero();
  44374. this._transformedDirection = BABYLON.Vector3.Zero();
  44375. }
  44376. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44377. this._localDirection.multiplyInPlace(this.panningAxis);
  44378. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44379. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44380. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44381. if (!this.panningAxis.y) {
  44382. this._transformedDirection.y = 0;
  44383. }
  44384. if (!this._targetHost) {
  44385. if (this.panningDistanceLimit) {
  44386. this._transformedDirection.addInPlace(this._target);
  44387. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44388. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44389. this._target.copyFrom(this._transformedDirection);
  44390. }
  44391. }
  44392. else {
  44393. this._target.addInPlace(this._transformedDirection);
  44394. }
  44395. }
  44396. this.inertialPanningX *= this.panningInertia;
  44397. this.inertialPanningY *= this.panningInertia;
  44398. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44399. this.inertialPanningX = 0;
  44400. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44401. this.inertialPanningY = 0;
  44402. }
  44403. // Limits
  44404. this._checkLimits();
  44405. _super.prototype._checkInputs.call(this);
  44406. };
  44407. ArcRotateCamera.prototype._checkLimits = function () {
  44408. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44409. if (this.allowUpsideDown && this.beta > Math.PI) {
  44410. this.beta = this.beta - (2 * Math.PI);
  44411. }
  44412. }
  44413. else {
  44414. if (this.beta < this.lowerBetaLimit) {
  44415. this.beta = this.lowerBetaLimit;
  44416. }
  44417. }
  44418. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44419. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44420. this.beta = this.beta + (2 * Math.PI);
  44421. }
  44422. }
  44423. else {
  44424. if (this.beta > this.upperBetaLimit) {
  44425. this.beta = this.upperBetaLimit;
  44426. }
  44427. }
  44428. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44429. this.alpha = this.lowerAlphaLimit;
  44430. }
  44431. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44432. this.alpha = this.upperAlphaLimit;
  44433. }
  44434. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44435. this.radius = this.lowerRadiusLimit;
  44436. }
  44437. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44438. this.radius = this.upperRadiusLimit;
  44439. }
  44440. };
  44441. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44442. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44443. this.radius = radiusv3.length();
  44444. if (this.radius === 0) {
  44445. this.radius = 0.0001; // Just to avoid division by zero
  44446. }
  44447. // Alpha
  44448. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44449. if (radiusv3.z < 0) {
  44450. this.alpha = 2 * Math.PI - this.alpha;
  44451. }
  44452. // Beta
  44453. this.beta = Math.acos(radiusv3.y / this.radius);
  44454. this._checkLimits();
  44455. };
  44456. ArcRotateCamera.prototype.setPosition = function (position) {
  44457. if (this.position.equals(position)) {
  44458. return;
  44459. }
  44460. this.position.copyFrom(position);
  44461. this.rebuildAnglesAndRadius();
  44462. };
  44463. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44464. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44465. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44466. if (target.getBoundingInfo) {
  44467. if (toBoundingCenter) {
  44468. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44469. }
  44470. else {
  44471. this._targetBoundingCenter = null;
  44472. }
  44473. this._targetHost = target;
  44474. this._target = this._getTargetPosition();
  44475. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44476. }
  44477. else {
  44478. var newTarget = target;
  44479. var currentTarget = this._getTargetPosition();
  44480. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44481. return;
  44482. }
  44483. this._targetHost = null;
  44484. this._target = newTarget;
  44485. this._targetBoundingCenter = null;
  44486. this.onMeshTargetChangedObservable.notifyObservers(null);
  44487. }
  44488. this.rebuildAnglesAndRadius();
  44489. };
  44490. ArcRotateCamera.prototype._getViewMatrix = function () {
  44491. // Compute
  44492. var cosa = Math.cos(this.alpha);
  44493. var sina = Math.sin(this.alpha);
  44494. var cosb = Math.cos(this.beta);
  44495. var sinb = Math.sin(this.beta);
  44496. if (sinb === 0) {
  44497. sinb = 0.0001;
  44498. }
  44499. var target = this._getTargetPosition();
  44500. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44501. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44502. if (!this._collider) {
  44503. this._collider = new BABYLON.Collider();
  44504. }
  44505. this._collider._radius = this.collisionRadius;
  44506. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44507. this._collisionTriggered = true;
  44508. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44509. }
  44510. else {
  44511. this.position.copyFrom(this._newPosition);
  44512. var up = this.upVector;
  44513. if (this.allowUpsideDown && sinb < 0) {
  44514. up = up.clone();
  44515. up = up.negate();
  44516. }
  44517. if (this.getScene().useRightHandedSystem) {
  44518. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44519. }
  44520. else {
  44521. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44522. }
  44523. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44524. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44525. }
  44526. this._currentTarget = target;
  44527. return this._viewMatrix;
  44528. };
  44529. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44530. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44531. meshes = meshes || this.getScene().meshes;
  44532. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44533. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44534. this.radius = distance * this.zoomOnFactor;
  44535. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44536. };
  44537. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44538. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44539. var meshesOrMinMaxVector;
  44540. var distance;
  44541. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44542. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44543. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44544. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44545. }
  44546. else {
  44547. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44548. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44549. distance = minMaxVectorAndDistance.distance;
  44550. }
  44551. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44552. if (!doNotUpdateMaxZ) {
  44553. this.maxZ = distance * 2;
  44554. }
  44555. };
  44556. /**
  44557. * @override
  44558. * Override Camera.createRigCamera
  44559. */
  44560. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44561. var alphaShift = 0;
  44562. switch (this.cameraRigMode) {
  44563. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44564. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44566. case BABYLON.Camera.RIG_MODE_VR:
  44567. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44568. break;
  44569. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44570. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44571. break;
  44572. }
  44573. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44574. rigCam._cameraRigParams = {};
  44575. return rigCam;
  44576. };
  44577. /**
  44578. * @override
  44579. * Override Camera._updateRigCameras
  44580. */
  44581. ArcRotateCamera.prototype._updateRigCameras = function () {
  44582. var camLeft = this._rigCameras[0];
  44583. var camRight = this._rigCameras[1];
  44584. camLeft.beta = camRight.beta = this.beta;
  44585. camLeft.radius = camRight.radius = this.radius;
  44586. switch (this.cameraRigMode) {
  44587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44588. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44590. case BABYLON.Camera.RIG_MODE_VR:
  44591. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44592. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44593. break;
  44594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44595. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44596. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44597. break;
  44598. }
  44599. _super.prototype._updateRigCameras.call(this);
  44600. };
  44601. ArcRotateCamera.prototype.dispose = function () {
  44602. this.inputs.clear();
  44603. _super.prototype.dispose.call(this);
  44604. };
  44605. ArcRotateCamera.prototype.getClassName = function () {
  44606. return "ArcRotateCamera";
  44607. };
  44608. __decorate([
  44609. BABYLON.serialize()
  44610. ], ArcRotateCamera.prototype, "alpha", void 0);
  44611. __decorate([
  44612. BABYLON.serialize()
  44613. ], ArcRotateCamera.prototype, "beta", void 0);
  44614. __decorate([
  44615. BABYLON.serialize()
  44616. ], ArcRotateCamera.prototype, "radius", void 0);
  44617. __decorate([
  44618. BABYLON.serializeAsVector3("target")
  44619. ], ArcRotateCamera.prototype, "_target", void 0);
  44620. __decorate([
  44621. BABYLON.serialize()
  44622. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44623. __decorate([
  44624. BABYLON.serialize()
  44625. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44626. __decorate([
  44627. BABYLON.serialize()
  44628. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44629. __decorate([
  44630. BABYLON.serialize()
  44631. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44632. __decorate([
  44633. BABYLON.serialize()
  44634. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44635. __decorate([
  44636. BABYLON.serialize()
  44637. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44638. __decorate([
  44639. BABYLON.serialize()
  44640. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44641. __decorate([
  44642. BABYLON.serialize()
  44643. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44644. __decorate([
  44645. BABYLON.serialize()
  44646. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44647. __decorate([
  44648. BABYLON.serialize()
  44649. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44650. __decorate([
  44651. BABYLON.serialize()
  44652. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44653. __decorate([
  44654. BABYLON.serialize()
  44655. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44656. __decorate([
  44657. BABYLON.serialize()
  44658. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44659. __decorate([
  44660. BABYLON.serializeAsVector3()
  44661. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44662. __decorate([
  44663. BABYLON.serialize()
  44664. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44665. __decorate([
  44666. BABYLON.serialize()
  44667. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44668. __decorate([
  44669. BABYLON.serialize()
  44670. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44671. return ArcRotateCamera;
  44672. }(BABYLON.TargetCamera));
  44673. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44674. })(BABYLON || (BABYLON = {}));
  44675. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44676. var BABYLON;
  44677. (function (BABYLON) {
  44678. /**
  44679. * The HemisphericLight simulates the ambient environment light,
  44680. * so the passed direction is the light reflection direction, not the incoming direction.
  44681. */
  44682. var HemisphericLight = /** @class */ (function (_super) {
  44683. __extends(HemisphericLight, _super);
  44684. /**
  44685. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44686. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44687. * The HemisphericLight can't cast shadows.
  44688. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44689. * @param name The friendly name of the light
  44690. * @param direction The direction of the light reflection
  44691. * @param scene The scene the light belongs to
  44692. */
  44693. function HemisphericLight(name, direction, scene) {
  44694. var _this = _super.call(this, name, scene) || this;
  44695. /**
  44696. * The groundColor is the light in the opposite direction to the one specified during creation.
  44697. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  44698. */
  44699. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44700. _this.direction = direction || BABYLON.Vector3.Up();
  44701. return _this;
  44702. }
  44703. HemisphericLight.prototype._buildUniformLayout = function () {
  44704. this._uniformBuffer.addUniform("vLightData", 4);
  44705. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44706. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44707. this._uniformBuffer.addUniform("vLightGround", 3);
  44708. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44709. this._uniformBuffer.addUniform("depthValues", 2);
  44710. this._uniformBuffer.create();
  44711. };
  44712. /**
  44713. * Returns the string "HemisphericLight".
  44714. * @return The class name
  44715. */
  44716. HemisphericLight.prototype.getClassName = function () {
  44717. return "HemisphericLight";
  44718. };
  44719. /**
  44720. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44721. * Returns the updated direction.
  44722. * @param target The target the direction should point to
  44723. * @return The computed direction
  44724. */
  44725. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44726. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44727. return this.direction;
  44728. };
  44729. /**
  44730. * Returns the shadow generator associated to the light.
  44731. * @returns Always null for hemispheric lights because it does not support shadows.
  44732. */
  44733. HemisphericLight.prototype.getShadowGenerator = function () {
  44734. return null;
  44735. };
  44736. /**
  44737. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44738. * @param effect The effect to update
  44739. * @param lightIndex The index of the light in the effect to update
  44740. * @returns The hemispheric light
  44741. */
  44742. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44743. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44744. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44745. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44746. return this;
  44747. };
  44748. /**
  44749. * @ignore internal use only.
  44750. */
  44751. HemisphericLight.prototype._getWorldMatrix = function () {
  44752. if (!this._worldMatrix) {
  44753. this._worldMatrix = BABYLON.Matrix.Identity();
  44754. }
  44755. return this._worldMatrix;
  44756. };
  44757. /**
  44758. * Returns the integer 3.
  44759. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44760. */
  44761. HemisphericLight.prototype.getTypeID = function () {
  44762. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44763. };
  44764. __decorate([
  44765. BABYLON.serializeAsColor3()
  44766. ], HemisphericLight.prototype, "groundColor", void 0);
  44767. __decorate([
  44768. BABYLON.serializeAsVector3()
  44769. ], HemisphericLight.prototype, "direction", void 0);
  44770. return HemisphericLight;
  44771. }(BABYLON.Light));
  44772. BABYLON.HemisphericLight = HemisphericLight;
  44773. })(BABYLON || (BABYLON = {}));
  44774. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44775. var BABYLON;
  44776. (function (BABYLON) {
  44777. /**
  44778. * Base implementation of @see IShadowLight
  44779. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44780. */
  44781. var ShadowLight = /** @class */ (function (_super) {
  44782. __extends(ShadowLight, _super);
  44783. function ShadowLight() {
  44784. var _this = _super !== null && _super.apply(this, arguments) || this;
  44785. _this._needProjectionMatrixCompute = true;
  44786. return _this;
  44787. }
  44788. ShadowLight.prototype._setPosition = function (value) {
  44789. this._position = value;
  44790. };
  44791. Object.defineProperty(ShadowLight.prototype, "position", {
  44792. /**
  44793. * Sets the position the shadow will be casted from. Also use as the light position for both
  44794. * point and spot lights.
  44795. */
  44796. get: function () {
  44797. return this._position;
  44798. },
  44799. /**
  44800. * Sets the position the shadow will be casted from. Also use as the light position for both
  44801. * point and spot lights.
  44802. */
  44803. set: function (value) {
  44804. this._setPosition(value);
  44805. },
  44806. enumerable: true,
  44807. configurable: true
  44808. });
  44809. ShadowLight.prototype._setDirection = function (value) {
  44810. this._direction = value;
  44811. };
  44812. Object.defineProperty(ShadowLight.prototype, "direction", {
  44813. /**
  44814. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44815. * Also use as the light direction on spot and directional lights.
  44816. */
  44817. get: function () {
  44818. return this._direction;
  44819. },
  44820. /**
  44821. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44822. * Also use as the light direction on spot and directional lights.
  44823. */
  44824. set: function (value) {
  44825. this._setDirection(value);
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44831. /**
  44832. * Gets the shadow projection clipping minimum z value.
  44833. */
  44834. get: function () {
  44835. return this._shadowMinZ;
  44836. },
  44837. /**
  44838. * Sets the shadow projection clipping minimum z value.
  44839. */
  44840. set: function (value) {
  44841. this._shadowMinZ = value;
  44842. this.forceProjectionMatrixCompute();
  44843. },
  44844. enumerable: true,
  44845. configurable: true
  44846. });
  44847. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44848. /**
  44849. * Sets the shadow projection clipping maximum z value.
  44850. */
  44851. get: function () {
  44852. return this._shadowMaxZ;
  44853. },
  44854. /**
  44855. * Gets the shadow projection clipping maximum z value.
  44856. */
  44857. set: function (value) {
  44858. this._shadowMaxZ = value;
  44859. this.forceProjectionMatrixCompute();
  44860. },
  44861. enumerable: true,
  44862. configurable: true
  44863. });
  44864. /**
  44865. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44866. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44867. */
  44868. ShadowLight.prototype.computeTransformedInformation = function () {
  44869. if (this.parent && this.parent.getWorldMatrix) {
  44870. if (!this.transformedPosition) {
  44871. this.transformedPosition = BABYLON.Vector3.Zero();
  44872. }
  44873. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44874. // In case the direction is present.
  44875. if (this.direction) {
  44876. if (!this.transformedDirection) {
  44877. this.transformedDirection = BABYLON.Vector3.Zero();
  44878. }
  44879. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44880. }
  44881. return true;
  44882. }
  44883. return false;
  44884. };
  44885. /**
  44886. * Return the depth scale used for the shadow map.
  44887. * @returns the depth scale.
  44888. */
  44889. ShadowLight.prototype.getDepthScale = function () {
  44890. return 50.0;
  44891. };
  44892. /**
  44893. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44894. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44895. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44896. */
  44897. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44898. return this.transformedDirection ? this.transformedDirection : this.direction;
  44899. };
  44900. /**
  44901. * Returns the ShadowLight absolute position in the World.
  44902. * @returns the position vector in world space
  44903. */
  44904. ShadowLight.prototype.getAbsolutePosition = function () {
  44905. return this.transformedPosition ? this.transformedPosition : this.position;
  44906. };
  44907. /**
  44908. * Sets the ShadowLight direction toward the passed target.
  44909. * @param target The point tot target in local space
  44910. * @returns the updated ShadowLight direction
  44911. */
  44912. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44913. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44914. return this.direction;
  44915. };
  44916. /**
  44917. * Returns the light rotation in euler definition.
  44918. * @returns the x y z rotation in local space.
  44919. */
  44920. ShadowLight.prototype.getRotation = function () {
  44921. this.direction.normalize();
  44922. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44923. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44924. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44925. };
  44926. /**
  44927. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44928. * @returns true if a cube texture needs to be use
  44929. */
  44930. ShadowLight.prototype.needCube = function () {
  44931. return false;
  44932. };
  44933. /**
  44934. * Detects if the projection matrix requires to be recomputed this frame.
  44935. * @returns true if it requires to be recomputed otherwise, false.
  44936. */
  44937. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44938. return this._needProjectionMatrixCompute;
  44939. };
  44940. /**
  44941. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44942. */
  44943. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44944. this._needProjectionMatrixCompute = true;
  44945. };
  44946. /**
  44947. * Get the world matrix of the sahdow lights.
  44948. * @ignore Internal Use Only
  44949. */
  44950. ShadowLight.prototype._getWorldMatrix = function () {
  44951. if (!this._worldMatrix) {
  44952. this._worldMatrix = BABYLON.Matrix.Identity();
  44953. }
  44954. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44955. return this._worldMatrix;
  44956. };
  44957. /**
  44958. * Gets the minZ used for shadow according to both the scene and the light.
  44959. * @param activeCamera The camera we are returning the min for
  44960. * @returns the depth min z
  44961. */
  44962. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44963. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44964. };
  44965. /**
  44966. * Gets the maxZ used for shadow according to both the scene and the light.
  44967. * @param activeCamera The camera we are returning the max for
  44968. * @returns the depth max z
  44969. */
  44970. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44971. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44972. };
  44973. /**
  44974. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44975. * @param matrix The materix to updated with the projection information
  44976. * @param viewMatrix The transform matrix of the light
  44977. * @param renderList The list of mesh to render in the map
  44978. * @returns The current light
  44979. */
  44980. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44981. if (this.customProjectionMatrixBuilder) {
  44982. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44983. }
  44984. else {
  44985. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44986. }
  44987. return this;
  44988. };
  44989. __decorate([
  44990. BABYLON.serializeAsVector3()
  44991. ], ShadowLight.prototype, "position", null);
  44992. __decorate([
  44993. BABYLON.serializeAsVector3()
  44994. ], ShadowLight.prototype, "direction", null);
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], ShadowLight.prototype, "shadowMinZ", null);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], ShadowLight.prototype, "shadowMaxZ", null);
  45001. return ShadowLight;
  45002. }(BABYLON.Light));
  45003. BABYLON.ShadowLight = ShadowLight;
  45004. })(BABYLON || (BABYLON = {}));
  45005. //# sourceMappingURL=babylon.shadowLight.js.map
  45006. var BABYLON;
  45007. (function (BABYLON) {
  45008. /**
  45009. * A point light is a light defined by an unique point in world space.
  45010. * The light is emitted in every direction from this point.
  45011. * A good example of a point light is a standard light bulb.
  45012. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45013. */
  45014. var PointLight = /** @class */ (function (_super) {
  45015. __extends(PointLight, _super);
  45016. /**
  45017. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45018. * A PointLight emits the light in every direction.
  45019. * It can cast shadows.
  45020. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45021. * ```javascript
  45022. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45023. * ```
  45024. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45025. * @param name The light friendly name
  45026. * @param position The position of the point light in the scene
  45027. * @param scene The scene the lights belongs to
  45028. */
  45029. function PointLight(name, position, scene) {
  45030. var _this = _super.call(this, name, scene) || this;
  45031. _this._shadowAngle = Math.PI / 2;
  45032. _this.position = position;
  45033. return _this;
  45034. }
  45035. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45036. /**
  45037. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45038. * This specifies what angle the shadow will use to be created.
  45039. *
  45040. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45041. */
  45042. get: function () {
  45043. return this._shadowAngle;
  45044. },
  45045. /**
  45046. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45047. * This specifies what angle the shadow will use to be created.
  45048. *
  45049. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45050. */
  45051. set: function (value) {
  45052. this._shadowAngle = value;
  45053. this.forceProjectionMatrixCompute();
  45054. },
  45055. enumerable: true,
  45056. configurable: true
  45057. });
  45058. Object.defineProperty(PointLight.prototype, "direction", {
  45059. /**
  45060. * Gets the direction if it has been set.
  45061. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45062. */
  45063. get: function () {
  45064. return this._direction;
  45065. },
  45066. /**
  45067. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45068. */
  45069. set: function (value) {
  45070. var previousNeedCube = this.needCube();
  45071. this._direction = value;
  45072. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45073. this._shadowGenerator.recreateShadowMap();
  45074. }
  45075. },
  45076. enumerable: true,
  45077. configurable: true
  45078. });
  45079. /**
  45080. * Returns the string "PointLight"
  45081. * @returns the class name
  45082. */
  45083. PointLight.prototype.getClassName = function () {
  45084. return "PointLight";
  45085. };
  45086. /**
  45087. * Returns the integer 0.
  45088. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45089. */
  45090. PointLight.prototype.getTypeID = function () {
  45091. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45092. };
  45093. /**
  45094. * Specifies wether or not the shadowmap should be a cube texture.
  45095. * @returns true if the shadowmap needs to be a cube texture.
  45096. */
  45097. PointLight.prototype.needCube = function () {
  45098. return !this.direction;
  45099. };
  45100. /**
  45101. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45102. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45103. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45104. */
  45105. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45106. if (this.direction) {
  45107. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45108. }
  45109. else {
  45110. switch (faceIndex) {
  45111. case 0:
  45112. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45113. case 1:
  45114. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45115. case 2:
  45116. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45117. case 3:
  45118. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45119. case 4:
  45120. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45121. case 5:
  45122. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45123. }
  45124. }
  45125. return BABYLON.Vector3.Zero();
  45126. };
  45127. /**
  45128. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45129. * - fov = PI / 2
  45130. * - aspect ratio : 1.0
  45131. * - z-near and far equal to the active camera minZ and maxZ.
  45132. * Returns the PointLight.
  45133. */
  45134. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45135. var activeCamera = this.getScene().activeCamera;
  45136. if (!activeCamera) {
  45137. return;
  45138. }
  45139. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45140. };
  45141. PointLight.prototype._buildUniformLayout = function () {
  45142. this._uniformBuffer.addUniform("vLightData", 4);
  45143. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45144. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45145. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45146. this._uniformBuffer.addUniform("depthValues", 2);
  45147. this._uniformBuffer.create();
  45148. };
  45149. /**
  45150. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45151. * @param effect The effect to update
  45152. * @param lightIndex The index of the light in the effect to update
  45153. * @returns The point light
  45154. */
  45155. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45156. if (this.computeTransformedInformation()) {
  45157. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45158. return this;
  45159. }
  45160. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45161. return this;
  45162. };
  45163. __decorate([
  45164. BABYLON.serialize()
  45165. ], PointLight.prototype, "shadowAngle", null);
  45166. return PointLight;
  45167. }(BABYLON.ShadowLight));
  45168. BABYLON.PointLight = PointLight;
  45169. })(BABYLON || (BABYLON = {}));
  45170. //# sourceMappingURL=babylon.pointLight.js.map
  45171. var BABYLON;
  45172. (function (BABYLON) {
  45173. /**
  45174. * A directional light is defined by a direction (what a surprise!).
  45175. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45176. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  45177. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45178. */
  45179. var DirectionalLight = /** @class */ (function (_super) {
  45180. __extends(DirectionalLight, _super);
  45181. /**
  45182. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45183. * The directional light is emitted from everywhere in the given direction.
  45184. * It can cast shawdows.
  45185. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45186. * @param name The friendly name of the light
  45187. * @param direction The direction of the light
  45188. * @param scene The scene the light belongs to
  45189. */
  45190. function DirectionalLight(name, direction, scene) {
  45191. var _this = _super.call(this, name, scene) || this;
  45192. _this._shadowFrustumSize = 0;
  45193. _this._shadowOrthoScale = 0.5;
  45194. /**
  45195. * Automatically compute the projection matrix to best fit (including all the casters)
  45196. * on each frame.
  45197. */
  45198. _this.autoUpdateExtends = true;
  45199. // Cache
  45200. _this._orthoLeft = Number.MAX_VALUE;
  45201. _this._orthoRight = Number.MIN_VALUE;
  45202. _this._orthoTop = Number.MIN_VALUE;
  45203. _this._orthoBottom = Number.MAX_VALUE;
  45204. _this.position = direction.scale(-1.0);
  45205. _this.direction = direction;
  45206. return _this;
  45207. }
  45208. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45209. /**
  45210. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45211. */
  45212. get: function () {
  45213. return this._shadowFrustumSize;
  45214. },
  45215. /**
  45216. * Specifies a fix frustum size for the shadow generation.
  45217. */
  45218. set: function (value) {
  45219. this._shadowFrustumSize = value;
  45220. this.forceProjectionMatrixCompute();
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45226. /**
  45227. * Gets the shadow projection scale against the optimal computed one.
  45228. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45229. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45230. */
  45231. get: function () {
  45232. return this._shadowOrthoScale;
  45233. },
  45234. /**
  45235. * Sets the shadow projection scale against the optimal computed one.
  45236. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45237. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45238. */
  45239. set: function (value) {
  45240. this._shadowOrthoScale = value;
  45241. this.forceProjectionMatrixCompute();
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. /**
  45247. * Returns the string "DirectionalLight".
  45248. * @return The class name
  45249. */
  45250. DirectionalLight.prototype.getClassName = function () {
  45251. return "DirectionalLight";
  45252. };
  45253. /**
  45254. * Returns the integer 1.
  45255. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45256. */
  45257. DirectionalLight.prototype.getTypeID = function () {
  45258. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45259. };
  45260. /**
  45261. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45262. * Returns the DirectionalLight Shadow projection matrix.
  45263. */
  45264. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45265. if (this.shadowFrustumSize > 0) {
  45266. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45267. }
  45268. else {
  45269. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45270. }
  45271. };
  45272. /**
  45273. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45274. * Returns the DirectionalLight Shadow projection matrix.
  45275. */
  45276. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45277. var activeCamera = this.getScene().activeCamera;
  45278. if (!activeCamera) {
  45279. return;
  45280. }
  45281. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45282. };
  45283. /**
  45284. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45285. * Returns the DirectionalLight Shadow projection matrix.
  45286. */
  45287. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45288. var activeCamera = this.getScene().activeCamera;
  45289. if (!activeCamera) {
  45290. return;
  45291. }
  45292. // Check extends
  45293. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45294. var tempVector3 = BABYLON.Vector3.Zero();
  45295. this._orthoLeft = Number.MAX_VALUE;
  45296. this._orthoRight = Number.MIN_VALUE;
  45297. this._orthoTop = Number.MIN_VALUE;
  45298. this._orthoBottom = Number.MAX_VALUE;
  45299. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45300. var mesh = renderList[meshIndex];
  45301. if (!mesh) {
  45302. continue;
  45303. }
  45304. var boundingInfo = mesh.getBoundingInfo();
  45305. var boundingBox = boundingInfo.boundingBox;
  45306. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45307. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45308. if (tempVector3.x < this._orthoLeft)
  45309. this._orthoLeft = tempVector3.x;
  45310. if (tempVector3.y < this._orthoBottom)
  45311. this._orthoBottom = tempVector3.y;
  45312. if (tempVector3.x > this._orthoRight)
  45313. this._orthoRight = tempVector3.x;
  45314. if (tempVector3.y > this._orthoTop)
  45315. this._orthoTop = tempVector3.y;
  45316. }
  45317. }
  45318. }
  45319. var xOffset = this._orthoRight - this._orthoLeft;
  45320. var yOffset = this._orthoTop - this._orthoBottom;
  45321. 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);
  45322. };
  45323. DirectionalLight.prototype._buildUniformLayout = function () {
  45324. this._uniformBuffer.addUniform("vLightData", 4);
  45325. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45326. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45327. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45328. this._uniformBuffer.addUniform("depthValues", 2);
  45329. this._uniformBuffer.create();
  45330. };
  45331. /**
  45332. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45333. * @param effect The effect to update
  45334. * @param lightIndex The index of the light in the effect to update
  45335. * @returns The directional light
  45336. */
  45337. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45338. if (this.computeTransformedInformation()) {
  45339. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45340. return this;
  45341. }
  45342. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45343. return this;
  45344. };
  45345. /**
  45346. * Gets the minZ used for shadow according to both the scene and the light.
  45347. *
  45348. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45349. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45350. * @param activeCamera The camera we are returning the min for
  45351. * @returns the depth min z
  45352. */
  45353. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45354. return 1;
  45355. };
  45356. /**
  45357. * Gets the maxZ used for shadow according to both the scene and the light.
  45358. *
  45359. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45360. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45361. * @param activeCamera The camera we are returning the max for
  45362. * @returns the depth max z
  45363. */
  45364. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45365. return 1;
  45366. };
  45367. __decorate([
  45368. BABYLON.serialize()
  45369. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45370. __decorate([
  45371. BABYLON.serialize()
  45372. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45373. __decorate([
  45374. BABYLON.serialize()
  45375. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45376. return DirectionalLight;
  45377. }(BABYLON.ShadowLight));
  45378. BABYLON.DirectionalLight = DirectionalLight;
  45379. })(BABYLON || (BABYLON = {}));
  45380. //# sourceMappingURL=babylon.directionalLight.js.map
  45381. var BABYLON;
  45382. (function (BABYLON) {
  45383. /**
  45384. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45385. * These values define a cone of light starting from the position, emitting toward the direction.
  45386. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45387. * and the exponent defines the speed of the decay of the light with distance (reach).
  45388. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45389. */
  45390. var SpotLight = /** @class */ (function (_super) {
  45391. __extends(SpotLight, _super);
  45392. /**
  45393. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45394. * It can cast shadows.
  45395. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45396. * @param name The light friendly name
  45397. * @param position The position of the spot light in the scene
  45398. * @param direction The direction of the light in the scene
  45399. * @param angle The cone angle of the light in Radians
  45400. * @param exponent The light decay speed with the distance from the emission spot
  45401. * @param scene The scene the lights belongs to
  45402. */
  45403. function SpotLight(name, position, direction, angle, exponent, scene) {
  45404. var _this = _super.call(this, name, scene) || this;
  45405. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45406. _this._projectionTextureLightNear = 1e-6;
  45407. _this._projectionTextureLightFar = 1000.0;
  45408. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45409. _this._projectionTextureViewLightDirty = true;
  45410. _this._projectionTextureProjectionLightDirty = true;
  45411. _this._projectionTextureDirty = true;
  45412. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45413. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45414. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45415. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  45416. _this.position = position;
  45417. _this.direction = direction;
  45418. _this.angle = angle;
  45419. _this.exponent = exponent;
  45420. return _this;
  45421. }
  45422. Object.defineProperty(SpotLight.prototype, "angle", {
  45423. /**
  45424. * Gets the cone angle of the spot light in Radians.
  45425. */
  45426. get: function () {
  45427. return this._angle;
  45428. },
  45429. /**
  45430. * Sets the cone angle of the spot light in Radians.
  45431. */
  45432. set: function (value) {
  45433. this._angle = value;
  45434. this._projectionTextureProjectionLightDirty = true;
  45435. this.forceProjectionMatrixCompute();
  45436. },
  45437. enumerable: true,
  45438. configurable: true
  45439. });
  45440. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45441. /**
  45442. * Allows scaling the angle of the light for shadow generation only.
  45443. */
  45444. get: function () {
  45445. return this._shadowAngleScale;
  45446. },
  45447. /**
  45448. * Allows scaling the angle of the light for shadow generation only.
  45449. */
  45450. set: function (value) {
  45451. this._shadowAngleScale = value;
  45452. this.forceProjectionMatrixCompute();
  45453. },
  45454. enumerable: true,
  45455. configurable: true
  45456. });
  45457. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45458. /**
  45459. * Allows reading the projecton texture
  45460. */
  45461. get: function () {
  45462. return this._projectionTextureMatrix;
  45463. },
  45464. enumerable: true,
  45465. configurable: true
  45466. });
  45467. ;
  45468. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45469. /**
  45470. * Gets the near clip of the Spotlight for texture projection.
  45471. */
  45472. get: function () {
  45473. return this._projectionTextureLightNear;
  45474. },
  45475. /**
  45476. * Sets the near clip of the Spotlight for texture projection.
  45477. */
  45478. set: function (value) {
  45479. this._projectionTextureLightNear = value;
  45480. this._projectionTextureProjectionLightDirty = true;
  45481. },
  45482. enumerable: true,
  45483. configurable: true
  45484. });
  45485. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45486. /**
  45487. * Gets the far clip of the Spotlight for texture projection.
  45488. */
  45489. get: function () {
  45490. return this._projectionTextureLightFar;
  45491. },
  45492. /**
  45493. * Sets the far clip of the Spotlight for texture projection.
  45494. */
  45495. set: function (value) {
  45496. this._projectionTextureLightFar = value;
  45497. this._projectionTextureProjectionLightDirty = true;
  45498. },
  45499. enumerable: true,
  45500. configurable: true
  45501. });
  45502. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45503. /**
  45504. * Gets the Up vector of the Spotlight for texture projection.
  45505. */
  45506. get: function () {
  45507. return this._projectionTextureUpDirection;
  45508. },
  45509. /**
  45510. * Sets the Up vector of the Spotlight for texture projection.
  45511. */
  45512. set: function (value) {
  45513. this._projectionTextureUpDirection = value;
  45514. this._projectionTextureProjectionLightDirty = true;
  45515. },
  45516. enumerable: true,
  45517. configurable: true
  45518. });
  45519. ;
  45520. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45521. /**
  45522. * Gets the projection texture of the light.
  45523. */
  45524. get: function () {
  45525. return this._projectionTexture;
  45526. },
  45527. /**
  45528. * Sets the projection texture of the light.
  45529. */
  45530. set: function (value) {
  45531. this._projectionTexture = value;
  45532. this._projectionTextureDirty = true;
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. /**
  45538. * Returns the string "SpotLight".
  45539. * @returns the class name
  45540. */
  45541. SpotLight.prototype.getClassName = function () {
  45542. return "SpotLight";
  45543. };
  45544. /**
  45545. * Returns the integer 2.
  45546. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45547. */
  45548. SpotLight.prototype.getTypeID = function () {
  45549. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45550. };
  45551. /**
  45552. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45553. */
  45554. SpotLight.prototype._setDirection = function (value) {
  45555. _super.prototype._setDirection.call(this, value);
  45556. this._projectionTextureViewLightDirty = true;
  45557. };
  45558. /**
  45559. * Overrides the position setter to recompute the projection texture view light Matrix.
  45560. */
  45561. SpotLight.prototype._setPosition = function (value) {
  45562. _super.prototype._setPosition.call(this, value);
  45563. this._projectionTextureViewLightDirty = true;
  45564. };
  45565. /**
  45566. * 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.
  45567. * Returns the SpotLight.
  45568. */
  45569. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45570. var activeCamera = this.getScene().activeCamera;
  45571. if (!activeCamera) {
  45572. return;
  45573. }
  45574. this._shadowAngleScale = this._shadowAngleScale || 1;
  45575. var angle = this._shadowAngleScale * this._angle;
  45576. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45577. };
  45578. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45579. this._projectionTextureViewLightDirty = false;
  45580. this._projectionTextureDirty = true;
  45581. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45582. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45583. };
  45584. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45585. this._projectionTextureProjectionLightDirty = false;
  45586. this._projectionTextureDirty = true;
  45587. var light_far = this.projectionTextureLightFar;
  45588. var light_near = this.projectionTextureLightNear;
  45589. var P = light_far / (light_far - light_near);
  45590. var Q = -P * light_near;
  45591. var S = 1.0 / Math.tan(this._angle / 2.0);
  45592. var A = 1.0;
  45593. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  45594. };
  45595. /**
  45596. * Main function for light texture projection matrix computing.
  45597. */
  45598. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45599. this._projectionTextureDirty = false;
  45600. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45601. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45602. };
  45603. SpotLight.prototype._buildUniformLayout = function () {
  45604. this._uniformBuffer.addUniform("vLightData", 4);
  45605. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45606. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45607. this._uniformBuffer.addUniform("vLightDirection", 3);
  45608. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45609. this._uniformBuffer.addUniform("depthValues", 2);
  45610. this._uniformBuffer.create();
  45611. };
  45612. /**
  45613. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45614. * @param effect The effect to update
  45615. * @param lightIndex The index of the light in the effect to update
  45616. * @returns The spot light
  45617. */
  45618. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45619. var normalizeDirection;
  45620. if (this.computeTransformedInformation()) {
  45621. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45622. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45623. }
  45624. else {
  45625. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45626. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45627. }
  45628. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45629. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45630. if (this._projectionTextureViewLightDirty) {
  45631. this._computeProjectionTextureViewLightMatrix();
  45632. }
  45633. if (this._projectionTextureProjectionLightDirty) {
  45634. this._computeProjectionTextureProjectionLightMatrix();
  45635. }
  45636. if (this._projectionTextureDirty) {
  45637. this._computeProjectionTextureMatrix();
  45638. }
  45639. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45640. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45641. }
  45642. return this;
  45643. };
  45644. /**
  45645. * Disposes the light and the associated resources.
  45646. */
  45647. SpotLight.prototype.dispose = function () {
  45648. _super.prototype.dispose.call(this);
  45649. if (this._projectionTexture) {
  45650. this._projectionTexture.dispose();
  45651. }
  45652. };
  45653. __decorate([
  45654. BABYLON.serialize()
  45655. ], SpotLight.prototype, "angle", null);
  45656. __decorate([
  45657. BABYLON.serialize()
  45658. ], SpotLight.prototype, "shadowAngleScale", null);
  45659. __decorate([
  45660. BABYLON.serialize()
  45661. ], SpotLight.prototype, "exponent", void 0);
  45662. __decorate([
  45663. BABYLON.serialize()
  45664. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45665. __decorate([
  45666. BABYLON.serialize()
  45667. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45668. __decorate([
  45669. BABYLON.serialize()
  45670. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45671. __decorate([
  45672. BABYLON.serializeAsTexture("projectedLightTexture")
  45673. ], SpotLight.prototype, "_projectionTexture", void 0);
  45674. return SpotLight;
  45675. }(BABYLON.ShadowLight));
  45676. BABYLON.SpotLight = SpotLight;
  45677. })(BABYLON || (BABYLON = {}));
  45678. //# sourceMappingURL=babylon.spotLight.js.map
  45679. var BABYLON;
  45680. (function (BABYLON) {
  45681. var AnimationRange = /** @class */ (function () {
  45682. function AnimationRange(name, from, to) {
  45683. this.name = name;
  45684. this.from = from;
  45685. this.to = to;
  45686. }
  45687. AnimationRange.prototype.clone = function () {
  45688. return new AnimationRange(this.name, this.from, this.to);
  45689. };
  45690. return AnimationRange;
  45691. }());
  45692. BABYLON.AnimationRange = AnimationRange;
  45693. /**
  45694. * Composed of a frame, and an action function
  45695. */
  45696. var AnimationEvent = /** @class */ (function () {
  45697. function AnimationEvent(frame, action, onlyOnce) {
  45698. this.frame = frame;
  45699. this.action = action;
  45700. this.onlyOnce = onlyOnce;
  45701. this.isDone = false;
  45702. }
  45703. return AnimationEvent;
  45704. }());
  45705. BABYLON.AnimationEvent = AnimationEvent;
  45706. var PathCursor = /** @class */ (function () {
  45707. function PathCursor(path) {
  45708. this.path = path;
  45709. this._onchange = new Array();
  45710. this.value = 0;
  45711. this.animations = new Array();
  45712. }
  45713. PathCursor.prototype.getPoint = function () {
  45714. var point = this.path.getPointAtLengthPosition(this.value);
  45715. return new BABYLON.Vector3(point.x, 0, point.y);
  45716. };
  45717. PathCursor.prototype.moveAhead = function (step) {
  45718. if (step === void 0) { step = 0.002; }
  45719. this.move(step);
  45720. return this;
  45721. };
  45722. PathCursor.prototype.moveBack = function (step) {
  45723. if (step === void 0) { step = 0.002; }
  45724. this.move(-step);
  45725. return this;
  45726. };
  45727. PathCursor.prototype.move = function (step) {
  45728. if (Math.abs(step) > 1) {
  45729. throw "step size should be less than 1.";
  45730. }
  45731. this.value += step;
  45732. this.ensureLimits();
  45733. this.raiseOnChange();
  45734. return this;
  45735. };
  45736. PathCursor.prototype.ensureLimits = function () {
  45737. while (this.value > 1) {
  45738. this.value -= 1;
  45739. }
  45740. while (this.value < 0) {
  45741. this.value += 1;
  45742. }
  45743. return this;
  45744. };
  45745. // used by animation engine
  45746. PathCursor.prototype.raiseOnChange = function () {
  45747. var _this = this;
  45748. this._onchange.forEach(function (f) { return f(_this); });
  45749. return this;
  45750. };
  45751. PathCursor.prototype.onchange = function (f) {
  45752. this._onchange.push(f);
  45753. return this;
  45754. };
  45755. return PathCursor;
  45756. }());
  45757. BABYLON.PathCursor = PathCursor;
  45758. var AnimationKeyInterpolation;
  45759. (function (AnimationKeyInterpolation) {
  45760. /**
  45761. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45762. */
  45763. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45764. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45765. var Animation = /** @class */ (function () {
  45766. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45767. this.name = name;
  45768. this.targetProperty = targetProperty;
  45769. this.framePerSecond = framePerSecond;
  45770. this.dataType = dataType;
  45771. this.loopMode = loopMode;
  45772. this.enableBlending = enableBlending;
  45773. this._runtimeAnimations = new Array();
  45774. // The set of event that will be linked to this animation
  45775. this._events = new Array();
  45776. this.blendingSpeed = 0.01;
  45777. this._ranges = {};
  45778. this.targetPropertyPath = targetProperty.split(".");
  45779. this.dataType = dataType;
  45780. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45781. }
  45782. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45783. var dataType = undefined;
  45784. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45785. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45786. }
  45787. else if (from instanceof BABYLON.Quaternion) {
  45788. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45789. }
  45790. else if (from instanceof BABYLON.Vector3) {
  45791. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45792. }
  45793. else if (from instanceof BABYLON.Vector2) {
  45794. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45795. }
  45796. else if (from instanceof BABYLON.Color3) {
  45797. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45798. }
  45799. else if (from instanceof BABYLON.Size) {
  45800. dataType = Animation.ANIMATIONTYPE_SIZE;
  45801. }
  45802. if (dataType == undefined) {
  45803. return null;
  45804. }
  45805. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45806. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45807. animation.setKeys(keys);
  45808. if (easingFunction !== undefined) {
  45809. animation.setEasingFunction(easingFunction);
  45810. }
  45811. return animation;
  45812. };
  45813. /**
  45814. * Sets up an animation.
  45815. * @param property the property to animate
  45816. * @param animationType the animation type to apply
  45817. * @param easingFunction the easing function used in the animation
  45818. * @returns The created animation
  45819. */
  45820. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45821. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45822. animation.setEasingFunction(easingFunction);
  45823. return animation;
  45824. };
  45825. /**
  45826. * Create and start an animation on a node
  45827. * @param {string} name defines the name of the global animation that will be run on all nodes
  45828. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45829. * @param {string} targetProperty defines property to animate
  45830. * @param {number} framePerSecond defines the number of frame per second yo use
  45831. * @param {number} totalFrame defines the number of frames in total
  45832. * @param {any} from defines the initial value
  45833. * @param {any} to defines the final value
  45834. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45835. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45836. * @param onAnimationEnd defines the callback to call when animation end
  45837. * @returns the animatable created for this animation
  45838. */
  45839. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45840. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45841. if (!animation) {
  45842. return null;
  45843. }
  45844. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45845. };
  45846. /**
  45847. * Create and start an animation on a node and its descendants
  45848. * @param {string} name defines the name of the global animation that will be run on all nodes
  45849. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45850. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  45851. * @param {string} targetProperty defines property to animate
  45852. * @param {number} framePerSecond defines the number of frame per second yo use
  45853. * @param {number} totalFrame defines the number of frames in total
  45854. * @param {any} from defines the initial value
  45855. * @param {any} to defines the final value
  45856. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45857. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45858. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45859. * @returns the list of animatables created for all nodes
  45860. * @example https://www.babylonjs-playground.com/#MH0VLI
  45861. */
  45862. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45863. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45864. if (!animation) {
  45865. return null;
  45866. }
  45867. var scene = node.getScene();
  45868. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45869. };
  45870. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45871. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45872. if (!animation) {
  45873. return null;
  45874. }
  45875. node.animations.push(animation);
  45876. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45877. };
  45878. /**
  45879. * Transition property of the Camera to the target Value.
  45880. * @param property The property to transition
  45881. * @param targetValue The target Value of the property
  45882. * @param host The object where the property to animate belongs
  45883. * @param scene Scene used to run the animation
  45884. * @param frameRate Framerate (in frame/s) to use
  45885. * @param transition The transition type we want to use
  45886. * @param duration The duration of the animation, in milliseconds
  45887. * @param onAnimationEnd Call back trigger at the end of the animation.
  45888. */
  45889. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45890. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45891. if (duration <= 0) {
  45892. host[property] = targetValue;
  45893. if (onAnimationEnd) {
  45894. onAnimationEnd();
  45895. }
  45896. return null;
  45897. }
  45898. var endFrame = frameRate * (duration / 1000);
  45899. transition.setKeys([{
  45900. frame: 0,
  45901. value: host[property].clone ? host[property].clone() : host[property]
  45902. },
  45903. {
  45904. frame: endFrame,
  45905. value: targetValue
  45906. }]);
  45907. if (!host.animations) {
  45908. host.animations = [];
  45909. }
  45910. host.animations.push(transition);
  45911. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45912. animation.onAnimationEnd = onAnimationEnd;
  45913. return animation;
  45914. };
  45915. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45916. /**
  45917. * Return the array of runtime animations currently using this animation
  45918. */
  45919. get: function () {
  45920. return this._runtimeAnimations;
  45921. },
  45922. enumerable: true,
  45923. configurable: true
  45924. });
  45925. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45926. get: function () {
  45927. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45928. var runtimeAnimation = _a[_i];
  45929. if (!runtimeAnimation.isStopped) {
  45930. return true;
  45931. }
  45932. }
  45933. return false;
  45934. },
  45935. enumerable: true,
  45936. configurable: true
  45937. });
  45938. // Methods
  45939. /**
  45940. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45941. */
  45942. Animation.prototype.toString = function (fullDetails) {
  45943. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45944. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45945. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45946. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45947. if (fullDetails) {
  45948. ret += ", Ranges: {";
  45949. var first = true;
  45950. for (var name in this._ranges) {
  45951. if (first) {
  45952. ret += ", ";
  45953. first = false;
  45954. }
  45955. ret += name;
  45956. }
  45957. ret += "}";
  45958. }
  45959. return ret;
  45960. };
  45961. /**
  45962. * Add an event to this animation.
  45963. */
  45964. Animation.prototype.addEvent = function (event) {
  45965. this._events.push(event);
  45966. };
  45967. /**
  45968. * Remove all events found at the given frame
  45969. * @param frame
  45970. */
  45971. Animation.prototype.removeEvents = function (frame) {
  45972. for (var index = 0; index < this._events.length; index++) {
  45973. if (this._events[index].frame === frame) {
  45974. this._events.splice(index, 1);
  45975. index--;
  45976. }
  45977. }
  45978. };
  45979. Animation.prototype.getEvents = function () {
  45980. return this._events;
  45981. };
  45982. Animation.prototype.createRange = function (name, from, to) {
  45983. // check name not already in use; could happen for bones after serialized
  45984. if (!this._ranges[name]) {
  45985. this._ranges[name] = new AnimationRange(name, from, to);
  45986. }
  45987. };
  45988. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45989. if (deleteFrames === void 0) { deleteFrames = true; }
  45990. var range = this._ranges[name];
  45991. if (!range) {
  45992. return;
  45993. }
  45994. if (deleteFrames) {
  45995. var from = range.from;
  45996. var to = range.to;
  45997. // this loop MUST go high to low for multiple splices to work
  45998. for (var key = this._keys.length - 1; key >= 0; key--) {
  45999. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46000. this._keys.splice(key, 1);
  46001. }
  46002. }
  46003. }
  46004. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46005. };
  46006. Animation.prototype.getRange = function (name) {
  46007. return this._ranges[name];
  46008. };
  46009. Animation.prototype.getKeys = function () {
  46010. return this._keys;
  46011. };
  46012. Animation.prototype.getHighestFrame = function () {
  46013. var ret = 0;
  46014. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46015. if (ret < this._keys[key].frame) {
  46016. ret = this._keys[key].frame;
  46017. }
  46018. }
  46019. return ret;
  46020. };
  46021. Animation.prototype.getEasingFunction = function () {
  46022. return this._easingFunction;
  46023. };
  46024. Animation.prototype.setEasingFunction = function (easingFunction) {
  46025. this._easingFunction = easingFunction;
  46026. };
  46027. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46028. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46029. };
  46030. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46031. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46032. };
  46033. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46034. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46035. };
  46036. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46037. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46038. };
  46039. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46040. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46041. };
  46042. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46043. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46044. };
  46045. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46046. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46047. };
  46048. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46049. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46050. };
  46051. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46052. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46053. };
  46054. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46055. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46056. };
  46057. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46058. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46059. };
  46060. Animation.prototype.clone = function () {
  46061. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46062. clone.enableBlending = this.enableBlending;
  46063. clone.blendingSpeed = this.blendingSpeed;
  46064. if (this._keys) {
  46065. clone.setKeys(this._keys);
  46066. }
  46067. if (this._ranges) {
  46068. clone._ranges = {};
  46069. for (var name in this._ranges) {
  46070. var range = this._ranges[name];
  46071. if (!range) {
  46072. continue;
  46073. }
  46074. clone._ranges[name] = range.clone();
  46075. }
  46076. }
  46077. return clone;
  46078. };
  46079. Animation.prototype.setKeys = function (values) {
  46080. this._keys = values.slice(0);
  46081. };
  46082. Animation.prototype.serialize = function () {
  46083. var serializationObject = {};
  46084. serializationObject.name = this.name;
  46085. serializationObject.property = this.targetProperty;
  46086. serializationObject.framePerSecond = this.framePerSecond;
  46087. serializationObject.dataType = this.dataType;
  46088. serializationObject.loopBehavior = this.loopMode;
  46089. serializationObject.enableBlending = this.enableBlending;
  46090. serializationObject.blendingSpeed = this.blendingSpeed;
  46091. var dataType = this.dataType;
  46092. serializationObject.keys = [];
  46093. var keys = this.getKeys();
  46094. for (var index = 0; index < keys.length; index++) {
  46095. var animationKey = keys[index];
  46096. var key = {};
  46097. key.frame = animationKey.frame;
  46098. switch (dataType) {
  46099. case Animation.ANIMATIONTYPE_FLOAT:
  46100. key.values = [animationKey.value];
  46101. break;
  46102. case Animation.ANIMATIONTYPE_QUATERNION:
  46103. case Animation.ANIMATIONTYPE_MATRIX:
  46104. case Animation.ANIMATIONTYPE_VECTOR3:
  46105. case Animation.ANIMATIONTYPE_COLOR3:
  46106. key.values = animationKey.value.asArray();
  46107. break;
  46108. }
  46109. serializationObject.keys.push(key);
  46110. }
  46111. serializationObject.ranges = [];
  46112. for (var name in this._ranges) {
  46113. var source = this._ranges[name];
  46114. if (!source) {
  46115. continue;
  46116. }
  46117. var range = {};
  46118. range.name = name;
  46119. range.from = source.from;
  46120. range.to = source.to;
  46121. serializationObject.ranges.push(range);
  46122. }
  46123. return serializationObject;
  46124. };
  46125. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46126. get: function () {
  46127. return Animation._ANIMATIONTYPE_FLOAT;
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46133. get: function () {
  46134. return Animation._ANIMATIONTYPE_VECTOR3;
  46135. },
  46136. enumerable: true,
  46137. configurable: true
  46138. });
  46139. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46140. get: function () {
  46141. return Animation._ANIMATIONTYPE_VECTOR2;
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46147. get: function () {
  46148. return Animation._ANIMATIONTYPE_SIZE;
  46149. },
  46150. enumerable: true,
  46151. configurable: true
  46152. });
  46153. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46154. get: function () {
  46155. return Animation._ANIMATIONTYPE_QUATERNION;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46161. get: function () {
  46162. return Animation._ANIMATIONTYPE_MATRIX;
  46163. },
  46164. enumerable: true,
  46165. configurable: true
  46166. });
  46167. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46168. get: function () {
  46169. return Animation._ANIMATIONTYPE_COLOR3;
  46170. },
  46171. enumerable: true,
  46172. configurable: true
  46173. });
  46174. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46175. get: function () {
  46176. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46177. },
  46178. enumerable: true,
  46179. configurable: true
  46180. });
  46181. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46182. get: function () {
  46183. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46184. },
  46185. enumerable: true,
  46186. configurable: true
  46187. });
  46188. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46189. get: function () {
  46190. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46191. },
  46192. enumerable: true,
  46193. configurable: true
  46194. });
  46195. Animation.Parse = function (parsedAnimation) {
  46196. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46197. var dataType = parsedAnimation.dataType;
  46198. var keys = [];
  46199. var data;
  46200. var index;
  46201. if (parsedAnimation.enableBlending) {
  46202. animation.enableBlending = parsedAnimation.enableBlending;
  46203. }
  46204. if (parsedAnimation.blendingSpeed) {
  46205. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46206. }
  46207. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46208. var key = parsedAnimation.keys[index];
  46209. var inTangent;
  46210. var outTangent;
  46211. switch (dataType) {
  46212. case Animation.ANIMATIONTYPE_FLOAT:
  46213. data = key.values[0];
  46214. if (key.values.length >= 1) {
  46215. inTangent = key.values[1];
  46216. }
  46217. if (key.values.length >= 2) {
  46218. outTangent = key.values[2];
  46219. }
  46220. break;
  46221. case Animation.ANIMATIONTYPE_QUATERNION:
  46222. data = BABYLON.Quaternion.FromArray(key.values);
  46223. if (key.values.length >= 8) {
  46224. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46225. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46226. inTangent = _inTangent;
  46227. }
  46228. }
  46229. if (key.values.length >= 12) {
  46230. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46231. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46232. outTangent = _outTangent;
  46233. }
  46234. }
  46235. break;
  46236. case Animation.ANIMATIONTYPE_MATRIX:
  46237. data = BABYLON.Matrix.FromArray(key.values);
  46238. break;
  46239. case Animation.ANIMATIONTYPE_COLOR3:
  46240. data = BABYLON.Color3.FromArray(key.values);
  46241. break;
  46242. case Animation.ANIMATIONTYPE_VECTOR3:
  46243. default:
  46244. data = BABYLON.Vector3.FromArray(key.values);
  46245. break;
  46246. }
  46247. var keyData = {};
  46248. keyData.frame = key.frame;
  46249. keyData.value = data;
  46250. if (inTangent != undefined) {
  46251. keyData.inTangent = inTangent;
  46252. }
  46253. if (outTangent != undefined) {
  46254. keyData.outTangent = outTangent;
  46255. }
  46256. keys.push(keyData);
  46257. }
  46258. animation.setKeys(keys);
  46259. if (parsedAnimation.ranges) {
  46260. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46261. data = parsedAnimation.ranges[index];
  46262. animation.createRange(data.name, data.from, data.to);
  46263. }
  46264. }
  46265. return animation;
  46266. };
  46267. Animation.AppendSerializedAnimations = function (source, destination) {
  46268. if (source.animations) {
  46269. destination.animations = [];
  46270. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46271. var animation = source.animations[animationIndex];
  46272. destination.animations.push(animation.serialize());
  46273. }
  46274. }
  46275. };
  46276. Animation.AllowMatricesInterpolation = false;
  46277. // Statics
  46278. Animation._ANIMATIONTYPE_FLOAT = 0;
  46279. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46280. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46281. Animation._ANIMATIONTYPE_MATRIX = 3;
  46282. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46283. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46284. Animation._ANIMATIONTYPE_SIZE = 6;
  46285. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46286. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46287. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46288. return Animation;
  46289. }());
  46290. BABYLON.Animation = Animation;
  46291. })(BABYLON || (BABYLON = {}));
  46292. //# sourceMappingURL=babylon.animation.js.map
  46293. var BABYLON;
  46294. (function (BABYLON) {
  46295. /**
  46296. * This class defines the direct association between an animation and a target
  46297. */
  46298. var TargetedAnimation = /** @class */ (function () {
  46299. function TargetedAnimation() {
  46300. }
  46301. return TargetedAnimation;
  46302. }());
  46303. BABYLON.TargetedAnimation = TargetedAnimation;
  46304. /**
  46305. * Use this class to create coordinated animations on multiple targets
  46306. */
  46307. var AnimationGroup = /** @class */ (function () {
  46308. function AnimationGroup(name, scene) {
  46309. if (scene === void 0) { scene = null; }
  46310. this.name = name;
  46311. this._targetedAnimations = new Array();
  46312. this._animatables = new Array();
  46313. this._from = Number.MAX_VALUE;
  46314. this._to = -Number.MAX_VALUE;
  46315. this._speedRatio = 1;
  46316. this.onAnimationEndObservable = new BABYLON.Observable();
  46317. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46318. this._scene.animationGroups.push(this);
  46319. }
  46320. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46321. /**
  46322. * Define if the animations are started
  46323. */
  46324. get: function () {
  46325. return this._isStarted;
  46326. },
  46327. enumerable: true,
  46328. configurable: true
  46329. });
  46330. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46331. /**
  46332. * Gets or sets the speed ratio to use for all animations
  46333. */
  46334. get: function () {
  46335. return this._speedRatio;
  46336. },
  46337. /**
  46338. * Gets or sets the speed ratio to use for all animations
  46339. */
  46340. set: function (value) {
  46341. if (this._speedRatio === value) {
  46342. return;
  46343. }
  46344. this._speedRatio = value;
  46345. for (var index = 0; index < this._animatables.length; index++) {
  46346. var animatable = this._animatables[index];
  46347. animatable.speedRatio = this._speedRatio;
  46348. }
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46354. /**
  46355. * Gets the targeted animations for this animation group
  46356. */
  46357. get: function () {
  46358. return this._targetedAnimations;
  46359. },
  46360. enumerable: true,
  46361. configurable: true
  46362. });
  46363. /**
  46364. * Add an animation (with its target) in the group
  46365. * @param animation defines the animation we want to add
  46366. * @param target defines the target of the animation
  46367. * @returns the {BABYLON.TargetedAnimation} object
  46368. */
  46369. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46370. var targetedAnimation = {
  46371. animation: animation,
  46372. target: target
  46373. };
  46374. var keys = animation.getKeys();
  46375. if (this._from > keys[0].frame) {
  46376. this._from = keys[0].frame;
  46377. }
  46378. if (this._to < keys[keys.length - 1].frame) {
  46379. this._to = keys[keys.length - 1].frame;
  46380. }
  46381. this._targetedAnimations.push(targetedAnimation);
  46382. return targetedAnimation;
  46383. };
  46384. /**
  46385. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46386. * It can add constant keys at begin or end
  46387. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46388. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46389. */
  46390. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46391. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46392. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46393. beginFrame = Math.max(beginFrame, this._from);
  46394. endFrame = Math.min(endFrame, this._to);
  46395. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46396. var targetedAnimation = this._targetedAnimations[index];
  46397. var keys = targetedAnimation.animation.getKeys();
  46398. var startKey = keys[0];
  46399. var endKey = keys[keys.length - 1];
  46400. if (startKey.frame > beginFrame) {
  46401. var newKey = {
  46402. frame: beginFrame,
  46403. value: startKey.value,
  46404. inTangent: startKey.inTangent,
  46405. outTangent: startKey.outTangent,
  46406. interpolation: startKey.interpolation
  46407. };
  46408. keys.splice(0, 0, newKey);
  46409. }
  46410. if (endKey.frame < endFrame) {
  46411. var newKey = {
  46412. frame: endFrame,
  46413. value: endKey.value,
  46414. inTangent: endKey.outTangent,
  46415. outTangent: endKey.outTangent,
  46416. interpolation: endKey.interpolation
  46417. };
  46418. keys.push(newKey);
  46419. }
  46420. }
  46421. return this;
  46422. };
  46423. /**
  46424. * Start all animations on given targets
  46425. * @param loop defines if animations must loop
  46426. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46427. */
  46428. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46429. var _this = this;
  46430. if (loop === void 0) { loop = false; }
  46431. if (speedRatio === void 0) { speedRatio = 1; }
  46432. if (this._isStarted || this._targetedAnimations.length === 0) {
  46433. return this;
  46434. }
  46435. var _loop_1 = function () {
  46436. var targetedAnimation = this_1._targetedAnimations[index];
  46437. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46438. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46439. }));
  46440. };
  46441. var this_1 = this;
  46442. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46443. _loop_1();
  46444. }
  46445. this._speedRatio = speedRatio;
  46446. this._isStarted = true;
  46447. return this;
  46448. };
  46449. /**
  46450. * Pause all animations
  46451. */
  46452. AnimationGroup.prototype.pause = function () {
  46453. if (!this._isStarted) {
  46454. return this;
  46455. }
  46456. for (var index = 0; index < this._animatables.length; index++) {
  46457. var animatable = this._animatables[index];
  46458. animatable.pause();
  46459. }
  46460. return this;
  46461. };
  46462. /**
  46463. * Play all animations to initial state
  46464. * This function will start() the animations if they were not started or will restart() them if they were paused
  46465. * @param loop defines if animations must loop
  46466. */
  46467. AnimationGroup.prototype.play = function (loop) {
  46468. if (this.isStarted) {
  46469. if (loop !== undefined) {
  46470. for (var index = 0; index < this._animatables.length; index++) {
  46471. var animatable = this._animatables[index];
  46472. animatable.loopAnimation = loop;
  46473. }
  46474. }
  46475. this.restart();
  46476. }
  46477. else {
  46478. this.start(loop, this._speedRatio);
  46479. }
  46480. return this;
  46481. };
  46482. /**
  46483. * Reset all animations to initial state
  46484. */
  46485. AnimationGroup.prototype.reset = function () {
  46486. if (!this._isStarted) {
  46487. return this;
  46488. }
  46489. for (var index = 0; index < this._animatables.length; index++) {
  46490. var animatable = this._animatables[index];
  46491. animatable.reset();
  46492. }
  46493. return this;
  46494. };
  46495. /**
  46496. * Restart animations from key 0
  46497. */
  46498. AnimationGroup.prototype.restart = function () {
  46499. if (!this._isStarted) {
  46500. return this;
  46501. }
  46502. for (var index = 0; index < this._animatables.length; index++) {
  46503. var animatable = this._animatables[index];
  46504. animatable.restart();
  46505. }
  46506. return this;
  46507. };
  46508. /**
  46509. * Stop all animations
  46510. */
  46511. AnimationGroup.prototype.stop = function () {
  46512. if (!this._isStarted) {
  46513. return this;
  46514. }
  46515. for (var index = 0; index < this._animatables.length; index++) {
  46516. var animatable = this._animatables[index];
  46517. animatable.stop();
  46518. }
  46519. this._isStarted = false;
  46520. return this;
  46521. };
  46522. /**
  46523. * Dispose all associated resources
  46524. */
  46525. AnimationGroup.prototype.dispose = function () {
  46526. this._targetedAnimations = [];
  46527. this._animatables = [];
  46528. var index = this._scene.animationGroups.indexOf(this);
  46529. if (index > -1) {
  46530. this._scene.animationGroups.splice(index, 1);
  46531. }
  46532. };
  46533. return AnimationGroup;
  46534. }());
  46535. BABYLON.AnimationGroup = AnimationGroup;
  46536. })(BABYLON || (BABYLON = {}));
  46537. //# sourceMappingURL=babylon.animationGroup.js.map
  46538. var BABYLON;
  46539. (function (BABYLON) {
  46540. var RuntimeAnimation = /** @class */ (function () {
  46541. function RuntimeAnimation(target, animation) {
  46542. this._offsetsCache = {};
  46543. this._highLimitsCache = {};
  46544. this._stopped = false;
  46545. this._blendingFactor = 0;
  46546. this._ratioOffset = 0;
  46547. this._animation = animation;
  46548. this._target = target;
  46549. animation._runtimeAnimations.push(this);
  46550. }
  46551. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46552. get: function () {
  46553. return this._animation;
  46554. },
  46555. enumerable: true,
  46556. configurable: true
  46557. });
  46558. RuntimeAnimation.prototype.reset = function () {
  46559. this._offsetsCache = {};
  46560. this._highLimitsCache = {};
  46561. this.currentFrame = 0;
  46562. this._blendingFactor = 0;
  46563. this._originalBlendValue = null;
  46564. };
  46565. RuntimeAnimation.prototype.isStopped = function () {
  46566. return this._stopped;
  46567. };
  46568. RuntimeAnimation.prototype.dispose = function () {
  46569. var index = this._animation.runtimeAnimations.indexOf(this);
  46570. if (index > -1) {
  46571. this._animation.runtimeAnimations.splice(index, 1);
  46572. }
  46573. };
  46574. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46575. if (typeof value === "function") {
  46576. return value();
  46577. }
  46578. return value;
  46579. };
  46580. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46581. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46582. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46583. }
  46584. this.currentFrame = currentFrame;
  46585. var keys = this._animation.getKeys();
  46586. // Try to get a hash to find the right key
  46587. 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));
  46588. if (keys[startKeyIndex].frame >= currentFrame) {
  46589. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46590. startKeyIndex--;
  46591. }
  46592. }
  46593. for (var key = startKeyIndex; key < keys.length; key++) {
  46594. var endKey = keys[key + 1];
  46595. if (endKey.frame >= currentFrame) {
  46596. var startKey = keys[key];
  46597. var startValue = this._getKeyValue(startKey.value);
  46598. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46599. return startValue;
  46600. }
  46601. var endValue = this._getKeyValue(endKey.value);
  46602. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46603. var frameDelta = endKey.frame - startKey.frame;
  46604. // gradient : percent of currentFrame between the frame inf and the frame sup
  46605. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46606. // check for easingFunction and correction of gradient
  46607. var easingFunction = this._animation.getEasingFunction();
  46608. if (easingFunction != null) {
  46609. gradient = easingFunction.ease(gradient);
  46610. }
  46611. switch (this._animation.dataType) {
  46612. // Float
  46613. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46614. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46615. switch (loopMode) {
  46616. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46617. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46618. return floatValue;
  46619. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46620. return offsetValue * repeatCount + floatValue;
  46621. }
  46622. break;
  46623. // Quaternion
  46624. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46625. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46626. switch (loopMode) {
  46627. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46628. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46629. return quatValue;
  46630. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46631. return quatValue.add(offsetValue.scale(repeatCount));
  46632. }
  46633. return quatValue;
  46634. // Vector3
  46635. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46636. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46637. switch (loopMode) {
  46638. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46639. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46640. return vec3Value;
  46641. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46642. return vec3Value.add(offsetValue.scale(repeatCount));
  46643. }
  46644. // Vector2
  46645. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46646. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46647. switch (loopMode) {
  46648. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46649. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46650. return vec2Value;
  46651. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46652. return vec2Value.add(offsetValue.scale(repeatCount));
  46653. }
  46654. // Size
  46655. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46656. switch (loopMode) {
  46657. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46658. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46659. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46660. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46661. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46662. }
  46663. // Color3
  46664. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46665. switch (loopMode) {
  46666. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46667. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46668. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46669. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46670. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46671. }
  46672. // Matrix
  46673. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46674. switch (loopMode) {
  46675. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46676. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46677. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46678. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46679. }
  46680. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46681. return startValue;
  46682. }
  46683. default:
  46684. break;
  46685. }
  46686. break;
  46687. }
  46688. }
  46689. return this._getKeyValue(keys[keys.length - 1].value);
  46690. };
  46691. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46692. if (blend === void 0) { blend = false; }
  46693. // Set value
  46694. var path;
  46695. var destination;
  46696. var targetPropertyPath = this._animation.targetPropertyPath;
  46697. if (targetPropertyPath.length > 1) {
  46698. var property = this._target[targetPropertyPath[0]];
  46699. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46700. property = property[targetPropertyPath[index]];
  46701. }
  46702. path = targetPropertyPath[targetPropertyPath.length - 1];
  46703. destination = property;
  46704. }
  46705. else {
  46706. path = targetPropertyPath[0];
  46707. destination = this._target;
  46708. }
  46709. // Blending
  46710. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46711. if (!this._originalBlendValue) {
  46712. if (destination[path].clone) {
  46713. this._originalBlendValue = destination[path].clone();
  46714. }
  46715. else {
  46716. this._originalBlendValue = destination[path];
  46717. }
  46718. }
  46719. if (this._originalBlendValue.prototype) {
  46720. if (this._originalBlendValue.prototype.Lerp) {
  46721. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46722. }
  46723. else {
  46724. destination[path] = currentValue;
  46725. }
  46726. }
  46727. else if (this._originalBlendValue.m) {
  46728. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46729. }
  46730. else {
  46731. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46732. }
  46733. this._blendingFactor += this._animation.blendingSpeed;
  46734. }
  46735. else {
  46736. destination[path] = currentValue;
  46737. }
  46738. if (this._target.markAsDirty) {
  46739. this._target.markAsDirty(this._animation.targetProperty);
  46740. }
  46741. };
  46742. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46743. var keys = this._animation.getKeys();
  46744. if (frame < keys[0].frame) {
  46745. frame = keys[0].frame;
  46746. }
  46747. else if (frame > keys[keys.length - 1].frame) {
  46748. frame = keys[keys.length - 1].frame;
  46749. }
  46750. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46751. this.setValue(currentValue);
  46752. };
  46753. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46754. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46755. this._ratioOffset = this._previousRatio - newRatio;
  46756. };
  46757. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46758. if (blend === void 0) { blend = false; }
  46759. var targetPropertyPath = this._animation.targetPropertyPath;
  46760. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46761. this._stopped = true;
  46762. return false;
  46763. }
  46764. var returnValue = true;
  46765. var keys = this._animation.getKeys();
  46766. // Adding a start key at frame 0 if missing
  46767. if (keys[0].frame !== 0) {
  46768. var newKey = { frame: 0, value: keys[0].value };
  46769. keys.splice(0, 0, newKey);
  46770. }
  46771. // Check limits
  46772. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46773. from = keys[0].frame;
  46774. }
  46775. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46776. to = keys[keys.length - 1].frame;
  46777. }
  46778. //to and from cannot be the same key
  46779. if (from === to) {
  46780. if (from > keys[0].frame) {
  46781. from--;
  46782. }
  46783. else if (to < keys[keys.length - 1].frame) {
  46784. to++;
  46785. }
  46786. }
  46787. // Compute ratio
  46788. var range = to - from;
  46789. var offsetValue;
  46790. // ratio represents the frame delta between from and to
  46791. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46792. var highLimitValue = 0;
  46793. this._previousDelay = delay;
  46794. this._previousRatio = ratio;
  46795. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46796. returnValue = false;
  46797. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46798. }
  46799. else {
  46800. // Get max value if required
  46801. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46802. var keyOffset = to.toString() + from.toString();
  46803. if (!this._offsetsCache[keyOffset]) {
  46804. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46805. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46806. switch (this._animation.dataType) {
  46807. // Float
  46808. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46809. this._offsetsCache[keyOffset] = toValue - fromValue;
  46810. break;
  46811. // Quaternion
  46812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46813. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46814. break;
  46815. // Vector3
  46816. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46817. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46818. // Vector2
  46819. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46820. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46821. // Size
  46822. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46823. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46824. // Color3
  46825. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46826. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46827. default:
  46828. break;
  46829. }
  46830. this._highLimitsCache[keyOffset] = toValue;
  46831. }
  46832. highLimitValue = this._highLimitsCache[keyOffset];
  46833. offsetValue = this._offsetsCache[keyOffset];
  46834. }
  46835. }
  46836. if (offsetValue === undefined) {
  46837. switch (this._animation.dataType) {
  46838. // Float
  46839. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46840. offsetValue = 0;
  46841. break;
  46842. // Quaternion
  46843. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46844. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46845. break;
  46846. // Vector3
  46847. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46848. offsetValue = BABYLON.Vector3.Zero();
  46849. break;
  46850. // Vector2
  46851. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46852. offsetValue = BABYLON.Vector2.Zero();
  46853. break;
  46854. // Size
  46855. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46856. offsetValue = BABYLON.Size.Zero();
  46857. break;
  46858. // Color3
  46859. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46860. offsetValue = BABYLON.Color3.Black();
  46861. }
  46862. }
  46863. // Compute value
  46864. var repeatCount = (ratio / range) >> 0;
  46865. var currentFrame = returnValue ? from + ratio % range : to;
  46866. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46867. // Set value
  46868. this.setValue(currentValue);
  46869. // Check events
  46870. var events = this._animation.getEvents();
  46871. for (var index = 0; index < events.length; index++) {
  46872. // Make sure current frame has passed event frame and that event frame is within the current range
  46873. // Also, handle both forward and reverse animations
  46874. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46875. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46876. var event = events[index];
  46877. if (!event.isDone) {
  46878. // If event should be done only once, remove it.
  46879. if (event.onlyOnce) {
  46880. events.splice(index, 1);
  46881. index--;
  46882. }
  46883. event.isDone = true;
  46884. event.action();
  46885. } // Don't do anything if the event has already be done.
  46886. }
  46887. else if (events[index].isDone && !events[index].onlyOnce) {
  46888. // reset event, the animation is looping
  46889. events[index].isDone = false;
  46890. }
  46891. }
  46892. if (!returnValue) {
  46893. this._stopped = true;
  46894. }
  46895. return returnValue;
  46896. };
  46897. return RuntimeAnimation;
  46898. }());
  46899. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46900. })(BABYLON || (BABYLON = {}));
  46901. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46902. var BABYLON;
  46903. (function (BABYLON) {
  46904. var Animatable = /** @class */ (function () {
  46905. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46906. if (fromFrame === void 0) { fromFrame = 0; }
  46907. if (toFrame === void 0) { toFrame = 100; }
  46908. if (loopAnimation === void 0) { loopAnimation = false; }
  46909. if (speedRatio === void 0) { speedRatio = 1.0; }
  46910. this.target = target;
  46911. this.fromFrame = fromFrame;
  46912. this.toFrame = toFrame;
  46913. this.loopAnimation = loopAnimation;
  46914. this.onAnimationEnd = onAnimationEnd;
  46915. this._localDelayOffset = null;
  46916. this._pausedDelay = null;
  46917. this._runtimeAnimations = new Array();
  46918. this._paused = false;
  46919. this._speedRatio = 1;
  46920. this.animationStarted = false;
  46921. if (animations) {
  46922. this.appendAnimations(target, animations);
  46923. }
  46924. this._speedRatio = speedRatio;
  46925. this._scene = scene;
  46926. scene._activeAnimatables.push(this);
  46927. }
  46928. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46929. get: function () {
  46930. return this._speedRatio;
  46931. },
  46932. set: function (value) {
  46933. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46934. var animation = this._runtimeAnimations[index];
  46935. animation._prepareForSpeedRatioChange(value);
  46936. }
  46937. this._speedRatio = value;
  46938. },
  46939. enumerable: true,
  46940. configurable: true
  46941. });
  46942. // Methods
  46943. Animatable.prototype.getAnimations = function () {
  46944. return this._runtimeAnimations;
  46945. };
  46946. Animatable.prototype.appendAnimations = function (target, animations) {
  46947. for (var index = 0; index < animations.length; index++) {
  46948. var animation = animations[index];
  46949. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46950. }
  46951. };
  46952. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46953. var runtimeAnimations = this._runtimeAnimations;
  46954. for (var index = 0; index < runtimeAnimations.length; index++) {
  46955. if (runtimeAnimations[index].animation.targetProperty === property) {
  46956. return runtimeAnimations[index].animation;
  46957. }
  46958. }
  46959. return null;
  46960. };
  46961. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46962. var runtimeAnimations = this._runtimeAnimations;
  46963. for (var index = 0; index < runtimeAnimations.length; index++) {
  46964. if (runtimeAnimations[index].animation.targetProperty === property) {
  46965. return runtimeAnimations[index];
  46966. }
  46967. }
  46968. return null;
  46969. };
  46970. Animatable.prototype.reset = function () {
  46971. var runtimeAnimations = this._runtimeAnimations;
  46972. for (var index = 0; index < runtimeAnimations.length; index++) {
  46973. runtimeAnimations[index].reset();
  46974. }
  46975. // Reset to original value
  46976. for (index = 0; index < runtimeAnimations.length; index++) {
  46977. var animation = runtimeAnimations[index];
  46978. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46979. }
  46980. this._localDelayOffset = null;
  46981. this._pausedDelay = null;
  46982. };
  46983. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46984. var runtimeAnimations = this._runtimeAnimations;
  46985. for (var index = 0; index < runtimeAnimations.length; index++) {
  46986. runtimeAnimations[index].animation.enableBlending = true;
  46987. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46988. }
  46989. };
  46990. Animatable.prototype.disableBlending = function () {
  46991. var runtimeAnimations = this._runtimeAnimations;
  46992. for (var index = 0; index < runtimeAnimations.length; index++) {
  46993. runtimeAnimations[index].animation.enableBlending = false;
  46994. }
  46995. };
  46996. Animatable.prototype.goToFrame = function (frame) {
  46997. var runtimeAnimations = this._runtimeAnimations;
  46998. if (runtimeAnimations[0]) {
  46999. var fps = runtimeAnimations[0].animation.framePerSecond;
  47000. var currentFrame = runtimeAnimations[0].currentFrame;
  47001. var adjustTime = frame - currentFrame;
  47002. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47003. if (this._localDelayOffset === null) {
  47004. this._localDelayOffset = 0;
  47005. }
  47006. this._localDelayOffset -= delay;
  47007. }
  47008. for (var index = 0; index < runtimeAnimations.length; index++) {
  47009. runtimeAnimations[index].goToFrame(frame);
  47010. }
  47011. };
  47012. Animatable.prototype.pause = function () {
  47013. if (this._paused) {
  47014. return;
  47015. }
  47016. this._paused = true;
  47017. };
  47018. Animatable.prototype.restart = function () {
  47019. this._paused = false;
  47020. };
  47021. Animatable.prototype.stop = function (animationName) {
  47022. if (animationName) {
  47023. var idx = this._scene._activeAnimatables.indexOf(this);
  47024. if (idx > -1) {
  47025. var runtimeAnimations = this._runtimeAnimations;
  47026. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47027. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47028. continue;
  47029. }
  47030. runtimeAnimations[index].dispose();
  47031. runtimeAnimations.splice(index, 1);
  47032. }
  47033. if (runtimeAnimations.length == 0) {
  47034. this._scene._activeAnimatables.splice(idx, 1);
  47035. if (this.onAnimationEnd) {
  47036. this.onAnimationEnd();
  47037. }
  47038. }
  47039. }
  47040. }
  47041. else {
  47042. var index = this._scene._activeAnimatables.indexOf(this);
  47043. if (index > -1) {
  47044. this._scene._activeAnimatables.splice(index, 1);
  47045. var runtimeAnimations = this._runtimeAnimations;
  47046. for (var index = 0; index < runtimeAnimations.length; index++) {
  47047. runtimeAnimations[index].dispose();
  47048. }
  47049. if (this.onAnimationEnd) {
  47050. this.onAnimationEnd();
  47051. }
  47052. }
  47053. }
  47054. };
  47055. Animatable.prototype._animate = function (delay) {
  47056. if (this._paused) {
  47057. this.animationStarted = false;
  47058. if (this._pausedDelay === null) {
  47059. this._pausedDelay = delay;
  47060. }
  47061. return true;
  47062. }
  47063. if (this._localDelayOffset === null) {
  47064. this._localDelayOffset = delay;
  47065. this._pausedDelay = null;
  47066. }
  47067. else if (this._pausedDelay !== null) {
  47068. this._localDelayOffset += delay - this._pausedDelay;
  47069. this._pausedDelay = null;
  47070. }
  47071. // Animating
  47072. var running = false;
  47073. var runtimeAnimations = this._runtimeAnimations;
  47074. var index;
  47075. for (index = 0; index < runtimeAnimations.length; index++) {
  47076. var animation = runtimeAnimations[index];
  47077. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47078. running = running || isRunning;
  47079. }
  47080. this.animationStarted = running;
  47081. if (!running) {
  47082. // Remove from active animatables
  47083. index = this._scene._activeAnimatables.indexOf(this);
  47084. this._scene._activeAnimatables.splice(index, 1);
  47085. // Dispose all runtime animations
  47086. for (index = 0; index < runtimeAnimations.length; index++) {
  47087. runtimeAnimations[index].dispose();
  47088. }
  47089. }
  47090. if (!running && this.onAnimationEnd) {
  47091. this.onAnimationEnd();
  47092. this.onAnimationEnd = null;
  47093. }
  47094. return running;
  47095. };
  47096. return Animatable;
  47097. }());
  47098. BABYLON.Animatable = Animatable;
  47099. })(BABYLON || (BABYLON = {}));
  47100. //# sourceMappingURL=babylon.animatable.js.map
  47101. var BABYLON;
  47102. (function (BABYLON) {
  47103. var EasingFunction = /** @class */ (function () {
  47104. function EasingFunction() {
  47105. // Properties
  47106. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47107. }
  47108. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47109. get: function () {
  47110. return EasingFunction._EASINGMODE_EASEIN;
  47111. },
  47112. enumerable: true,
  47113. configurable: true
  47114. });
  47115. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47116. get: function () {
  47117. return EasingFunction._EASINGMODE_EASEOUT;
  47118. },
  47119. enumerable: true,
  47120. configurable: true
  47121. });
  47122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47123. get: function () {
  47124. return EasingFunction._EASINGMODE_EASEINOUT;
  47125. },
  47126. enumerable: true,
  47127. configurable: true
  47128. });
  47129. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47130. var n = Math.min(Math.max(easingMode, 0), 2);
  47131. this._easingMode = n;
  47132. };
  47133. EasingFunction.prototype.getEasingMode = function () {
  47134. return this._easingMode;
  47135. };
  47136. EasingFunction.prototype.easeInCore = function (gradient) {
  47137. throw new Error('You must implement this method');
  47138. };
  47139. EasingFunction.prototype.ease = function (gradient) {
  47140. switch (this._easingMode) {
  47141. case EasingFunction.EASINGMODE_EASEIN:
  47142. return this.easeInCore(gradient);
  47143. case EasingFunction.EASINGMODE_EASEOUT:
  47144. return (1 - this.easeInCore(1 - gradient));
  47145. }
  47146. if (gradient >= 0.5) {
  47147. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47148. }
  47149. return (this.easeInCore(gradient * 2) * 0.5);
  47150. };
  47151. //Statics
  47152. EasingFunction._EASINGMODE_EASEIN = 0;
  47153. EasingFunction._EASINGMODE_EASEOUT = 1;
  47154. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47155. return EasingFunction;
  47156. }());
  47157. BABYLON.EasingFunction = EasingFunction;
  47158. var CircleEase = /** @class */ (function (_super) {
  47159. __extends(CircleEase, _super);
  47160. function CircleEase() {
  47161. return _super !== null && _super.apply(this, arguments) || this;
  47162. }
  47163. CircleEase.prototype.easeInCore = function (gradient) {
  47164. gradient = Math.max(0, Math.min(1, gradient));
  47165. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47166. };
  47167. return CircleEase;
  47168. }(EasingFunction));
  47169. BABYLON.CircleEase = CircleEase;
  47170. var BackEase = /** @class */ (function (_super) {
  47171. __extends(BackEase, _super);
  47172. function BackEase(amplitude) {
  47173. if (amplitude === void 0) { amplitude = 1; }
  47174. var _this = _super.call(this) || this;
  47175. _this.amplitude = amplitude;
  47176. return _this;
  47177. }
  47178. BackEase.prototype.easeInCore = function (gradient) {
  47179. var num = Math.max(0, this.amplitude);
  47180. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47181. };
  47182. return BackEase;
  47183. }(EasingFunction));
  47184. BABYLON.BackEase = BackEase;
  47185. var BounceEase = /** @class */ (function (_super) {
  47186. __extends(BounceEase, _super);
  47187. function BounceEase(bounces, bounciness) {
  47188. if (bounces === void 0) { bounces = 3; }
  47189. if (bounciness === void 0) { bounciness = 2; }
  47190. var _this = _super.call(this) || this;
  47191. _this.bounces = bounces;
  47192. _this.bounciness = bounciness;
  47193. return _this;
  47194. }
  47195. BounceEase.prototype.easeInCore = function (gradient) {
  47196. var y = Math.max(0.0, this.bounces);
  47197. var bounciness = this.bounciness;
  47198. if (bounciness <= 1.0) {
  47199. bounciness = 1.001;
  47200. }
  47201. var num9 = Math.pow(bounciness, y);
  47202. var num5 = 1.0 - bounciness;
  47203. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47204. var num15 = gradient * num4;
  47205. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47206. var num3 = Math.floor(num65);
  47207. var num13 = num3 + 1.0;
  47208. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47209. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47210. var num7 = (num8 + num12) * 0.5;
  47211. var num6 = gradient - num7;
  47212. var num2 = num7 - num8;
  47213. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47214. };
  47215. return BounceEase;
  47216. }(EasingFunction));
  47217. BABYLON.BounceEase = BounceEase;
  47218. var CubicEase = /** @class */ (function (_super) {
  47219. __extends(CubicEase, _super);
  47220. function CubicEase() {
  47221. return _super !== null && _super.apply(this, arguments) || this;
  47222. }
  47223. CubicEase.prototype.easeInCore = function (gradient) {
  47224. return (gradient * gradient * gradient);
  47225. };
  47226. return CubicEase;
  47227. }(EasingFunction));
  47228. BABYLON.CubicEase = CubicEase;
  47229. var ElasticEase = /** @class */ (function (_super) {
  47230. __extends(ElasticEase, _super);
  47231. function ElasticEase(oscillations, springiness) {
  47232. if (oscillations === void 0) { oscillations = 3; }
  47233. if (springiness === void 0) { springiness = 3; }
  47234. var _this = _super.call(this) || this;
  47235. _this.oscillations = oscillations;
  47236. _this.springiness = springiness;
  47237. return _this;
  47238. }
  47239. ElasticEase.prototype.easeInCore = function (gradient) {
  47240. var num2;
  47241. var num3 = Math.max(0.0, this.oscillations);
  47242. var num = Math.max(0.0, this.springiness);
  47243. if (num == 0) {
  47244. num2 = gradient;
  47245. }
  47246. else {
  47247. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47248. }
  47249. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47250. };
  47251. return ElasticEase;
  47252. }(EasingFunction));
  47253. BABYLON.ElasticEase = ElasticEase;
  47254. var ExponentialEase = /** @class */ (function (_super) {
  47255. __extends(ExponentialEase, _super);
  47256. function ExponentialEase(exponent) {
  47257. if (exponent === void 0) { exponent = 2; }
  47258. var _this = _super.call(this) || this;
  47259. _this.exponent = exponent;
  47260. return _this;
  47261. }
  47262. ExponentialEase.prototype.easeInCore = function (gradient) {
  47263. if (this.exponent <= 0) {
  47264. return gradient;
  47265. }
  47266. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47267. };
  47268. return ExponentialEase;
  47269. }(EasingFunction));
  47270. BABYLON.ExponentialEase = ExponentialEase;
  47271. var PowerEase = /** @class */ (function (_super) {
  47272. __extends(PowerEase, _super);
  47273. function PowerEase(power) {
  47274. if (power === void 0) { power = 2; }
  47275. var _this = _super.call(this) || this;
  47276. _this.power = power;
  47277. return _this;
  47278. }
  47279. PowerEase.prototype.easeInCore = function (gradient) {
  47280. var y = Math.max(0.0, this.power);
  47281. return Math.pow(gradient, y);
  47282. };
  47283. return PowerEase;
  47284. }(EasingFunction));
  47285. BABYLON.PowerEase = PowerEase;
  47286. var QuadraticEase = /** @class */ (function (_super) {
  47287. __extends(QuadraticEase, _super);
  47288. function QuadraticEase() {
  47289. return _super !== null && _super.apply(this, arguments) || this;
  47290. }
  47291. QuadraticEase.prototype.easeInCore = function (gradient) {
  47292. return (gradient * gradient);
  47293. };
  47294. return QuadraticEase;
  47295. }(EasingFunction));
  47296. BABYLON.QuadraticEase = QuadraticEase;
  47297. var QuarticEase = /** @class */ (function (_super) {
  47298. __extends(QuarticEase, _super);
  47299. function QuarticEase() {
  47300. return _super !== null && _super.apply(this, arguments) || this;
  47301. }
  47302. QuarticEase.prototype.easeInCore = function (gradient) {
  47303. return (gradient * gradient * gradient * gradient);
  47304. };
  47305. return QuarticEase;
  47306. }(EasingFunction));
  47307. BABYLON.QuarticEase = QuarticEase;
  47308. var QuinticEase = /** @class */ (function (_super) {
  47309. __extends(QuinticEase, _super);
  47310. function QuinticEase() {
  47311. return _super !== null && _super.apply(this, arguments) || this;
  47312. }
  47313. QuinticEase.prototype.easeInCore = function (gradient) {
  47314. return (gradient * gradient * gradient * gradient * gradient);
  47315. };
  47316. return QuinticEase;
  47317. }(EasingFunction));
  47318. BABYLON.QuinticEase = QuinticEase;
  47319. var SineEase = /** @class */ (function (_super) {
  47320. __extends(SineEase, _super);
  47321. function SineEase() {
  47322. return _super !== null && _super.apply(this, arguments) || this;
  47323. }
  47324. SineEase.prototype.easeInCore = function (gradient) {
  47325. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47326. };
  47327. return SineEase;
  47328. }(EasingFunction));
  47329. BABYLON.SineEase = SineEase;
  47330. var BezierCurveEase = /** @class */ (function (_super) {
  47331. __extends(BezierCurveEase, _super);
  47332. function BezierCurveEase(x1, y1, x2, y2) {
  47333. if (x1 === void 0) { x1 = 0; }
  47334. if (y1 === void 0) { y1 = 0; }
  47335. if (x2 === void 0) { x2 = 1; }
  47336. if (y2 === void 0) { y2 = 1; }
  47337. var _this = _super.call(this) || this;
  47338. _this.x1 = x1;
  47339. _this.y1 = y1;
  47340. _this.x2 = x2;
  47341. _this.y2 = y2;
  47342. return _this;
  47343. }
  47344. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47345. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47346. };
  47347. return BezierCurveEase;
  47348. }(EasingFunction));
  47349. BABYLON.BezierCurveEase = BezierCurveEase;
  47350. })(BABYLON || (BABYLON = {}));
  47351. //# sourceMappingURL=babylon.easing.js.map
  47352. var BABYLON;
  47353. (function (BABYLON) {
  47354. var Condition = /** @class */ (function () {
  47355. function Condition(actionManager) {
  47356. this._actionManager = actionManager;
  47357. }
  47358. Condition.prototype.isValid = function () {
  47359. return true;
  47360. };
  47361. Condition.prototype._getProperty = function (propertyPath) {
  47362. return this._actionManager._getProperty(propertyPath);
  47363. };
  47364. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47365. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47366. };
  47367. Condition.prototype.serialize = function () {
  47368. };
  47369. Condition.prototype._serialize = function (serializedCondition) {
  47370. return {
  47371. type: 2,
  47372. children: [],
  47373. name: serializedCondition.name,
  47374. properties: serializedCondition.properties
  47375. };
  47376. };
  47377. return Condition;
  47378. }());
  47379. BABYLON.Condition = Condition;
  47380. var ValueCondition = /** @class */ (function (_super) {
  47381. __extends(ValueCondition, _super);
  47382. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47383. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47384. var _this = _super.call(this, actionManager) || this;
  47385. _this.propertyPath = propertyPath;
  47386. _this.value = value;
  47387. _this.operator = operator;
  47388. _this._target = target;
  47389. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47390. _this._property = _this._getProperty(_this.propertyPath);
  47391. return _this;
  47392. }
  47393. Object.defineProperty(ValueCondition, "IsEqual", {
  47394. get: function () {
  47395. return ValueCondition._IsEqual;
  47396. },
  47397. enumerable: true,
  47398. configurable: true
  47399. });
  47400. Object.defineProperty(ValueCondition, "IsDifferent", {
  47401. get: function () {
  47402. return ValueCondition._IsDifferent;
  47403. },
  47404. enumerable: true,
  47405. configurable: true
  47406. });
  47407. Object.defineProperty(ValueCondition, "IsGreater", {
  47408. get: function () {
  47409. return ValueCondition._IsGreater;
  47410. },
  47411. enumerable: true,
  47412. configurable: true
  47413. });
  47414. Object.defineProperty(ValueCondition, "IsLesser", {
  47415. get: function () {
  47416. return ValueCondition._IsLesser;
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. // Methods
  47422. ValueCondition.prototype.isValid = function () {
  47423. switch (this.operator) {
  47424. case ValueCondition.IsGreater:
  47425. return this._effectiveTarget[this._property] > this.value;
  47426. case ValueCondition.IsLesser:
  47427. return this._effectiveTarget[this._property] < this.value;
  47428. case ValueCondition.IsEqual:
  47429. case ValueCondition.IsDifferent:
  47430. var check;
  47431. if (this.value.equals) {
  47432. check = this.value.equals(this._effectiveTarget[this._property]);
  47433. }
  47434. else {
  47435. check = this.value === this._effectiveTarget[this._property];
  47436. }
  47437. return this.operator === ValueCondition.IsEqual ? check : !check;
  47438. }
  47439. return false;
  47440. };
  47441. ValueCondition.prototype.serialize = function () {
  47442. return this._serialize({
  47443. name: "ValueCondition",
  47444. properties: [
  47445. BABYLON.Action._GetTargetProperty(this._target),
  47446. { name: "propertyPath", value: this.propertyPath },
  47447. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47448. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47449. ]
  47450. });
  47451. };
  47452. ValueCondition.GetOperatorName = function (operator) {
  47453. switch (operator) {
  47454. case ValueCondition._IsEqual: return "IsEqual";
  47455. case ValueCondition._IsDifferent: return "IsDifferent";
  47456. case ValueCondition._IsGreater: return "IsGreater";
  47457. case ValueCondition._IsLesser: return "IsLesser";
  47458. default: return "";
  47459. }
  47460. };
  47461. // Statics
  47462. ValueCondition._IsEqual = 0;
  47463. ValueCondition._IsDifferent = 1;
  47464. ValueCondition._IsGreater = 2;
  47465. ValueCondition._IsLesser = 3;
  47466. return ValueCondition;
  47467. }(Condition));
  47468. BABYLON.ValueCondition = ValueCondition;
  47469. var PredicateCondition = /** @class */ (function (_super) {
  47470. __extends(PredicateCondition, _super);
  47471. function PredicateCondition(actionManager, predicate) {
  47472. var _this = _super.call(this, actionManager) || this;
  47473. _this.predicate = predicate;
  47474. return _this;
  47475. }
  47476. PredicateCondition.prototype.isValid = function () {
  47477. return this.predicate();
  47478. };
  47479. return PredicateCondition;
  47480. }(Condition));
  47481. BABYLON.PredicateCondition = PredicateCondition;
  47482. var StateCondition = /** @class */ (function (_super) {
  47483. __extends(StateCondition, _super);
  47484. function StateCondition(actionManager, target, value) {
  47485. var _this = _super.call(this, actionManager) || this;
  47486. _this.value = value;
  47487. _this._target = target;
  47488. return _this;
  47489. }
  47490. // Methods
  47491. StateCondition.prototype.isValid = function () {
  47492. return this._target.state === this.value;
  47493. };
  47494. StateCondition.prototype.serialize = function () {
  47495. return this._serialize({
  47496. name: "StateCondition",
  47497. properties: [
  47498. BABYLON.Action._GetTargetProperty(this._target),
  47499. { name: "value", value: this.value }
  47500. ]
  47501. });
  47502. };
  47503. return StateCondition;
  47504. }(Condition));
  47505. BABYLON.StateCondition = StateCondition;
  47506. })(BABYLON || (BABYLON = {}));
  47507. //# sourceMappingURL=babylon.condition.js.map
  47508. var BABYLON;
  47509. (function (BABYLON) {
  47510. var Action = /** @class */ (function () {
  47511. function Action(triggerOptions, condition) {
  47512. this.triggerOptions = triggerOptions;
  47513. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47514. if (triggerOptions.parameter) {
  47515. this.trigger = triggerOptions.trigger;
  47516. this._triggerParameter = triggerOptions.parameter;
  47517. }
  47518. else {
  47519. this.trigger = triggerOptions;
  47520. }
  47521. this._nextActiveAction = this;
  47522. this._condition = condition;
  47523. }
  47524. // Methods
  47525. Action.prototype._prepare = function () {
  47526. };
  47527. Action.prototype.getTriggerParameter = function () {
  47528. return this._triggerParameter;
  47529. };
  47530. Action.prototype._executeCurrent = function (evt) {
  47531. if (this._nextActiveAction._condition) {
  47532. var condition = this._nextActiveAction._condition;
  47533. var currentRenderId = this._actionManager.getScene().getRenderId();
  47534. // We cache the current evaluation for the current frame
  47535. if (condition._evaluationId === currentRenderId) {
  47536. if (!condition._currentResult) {
  47537. return;
  47538. }
  47539. }
  47540. else {
  47541. condition._evaluationId = currentRenderId;
  47542. if (!condition.isValid()) {
  47543. condition._currentResult = false;
  47544. return;
  47545. }
  47546. condition._currentResult = true;
  47547. }
  47548. }
  47549. this.onBeforeExecuteObservable.notifyObservers(this);
  47550. this._nextActiveAction.execute(evt);
  47551. this.skipToNextActiveAction();
  47552. };
  47553. Action.prototype.execute = function (evt) {
  47554. };
  47555. Action.prototype.skipToNextActiveAction = function () {
  47556. if (this._nextActiveAction._child) {
  47557. if (!this._nextActiveAction._child._actionManager) {
  47558. this._nextActiveAction._child._actionManager = this._actionManager;
  47559. }
  47560. this._nextActiveAction = this._nextActiveAction._child;
  47561. }
  47562. else {
  47563. this._nextActiveAction = this;
  47564. }
  47565. };
  47566. Action.prototype.then = function (action) {
  47567. this._child = action;
  47568. action._actionManager = this._actionManager;
  47569. action._prepare();
  47570. return action;
  47571. };
  47572. Action.prototype._getProperty = function (propertyPath) {
  47573. return this._actionManager._getProperty(propertyPath);
  47574. };
  47575. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47576. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47577. };
  47578. Action.prototype.serialize = function (parent) {
  47579. };
  47580. // Called by BABYLON.Action objects in serialize(...). Internal use
  47581. Action.prototype._serialize = function (serializedAction, parent) {
  47582. var serializationObject = {
  47583. type: 1,
  47584. children: [],
  47585. name: serializedAction.name,
  47586. properties: serializedAction.properties || []
  47587. };
  47588. // Serialize child
  47589. if (this._child) {
  47590. this._child.serialize(serializationObject);
  47591. }
  47592. // Check if "this" has a condition
  47593. if (this._condition) {
  47594. var serializedCondition = this._condition.serialize();
  47595. serializedCondition.children.push(serializationObject);
  47596. if (parent) {
  47597. parent.children.push(serializedCondition);
  47598. }
  47599. return serializedCondition;
  47600. }
  47601. if (parent) {
  47602. parent.children.push(serializationObject);
  47603. }
  47604. return serializationObject;
  47605. };
  47606. Action._SerializeValueAsString = function (value) {
  47607. if (typeof value === "number") {
  47608. return value.toString();
  47609. }
  47610. if (typeof value === "boolean") {
  47611. return value ? "true" : "false";
  47612. }
  47613. if (value instanceof BABYLON.Vector2) {
  47614. return value.x + ", " + value.y;
  47615. }
  47616. if (value instanceof BABYLON.Vector3) {
  47617. return value.x + ", " + value.y + ", " + value.z;
  47618. }
  47619. if (value instanceof BABYLON.Color3) {
  47620. return value.r + ", " + value.g + ", " + value.b;
  47621. }
  47622. if (value instanceof BABYLON.Color4) {
  47623. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47624. }
  47625. return value; // string
  47626. };
  47627. Action._GetTargetProperty = function (target) {
  47628. return {
  47629. name: "target",
  47630. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47631. : target instanceof BABYLON.Light ? "LightProperties"
  47632. : target instanceof BABYLON.Camera ? "CameraProperties"
  47633. : "SceneProperties",
  47634. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47635. };
  47636. };
  47637. return Action;
  47638. }());
  47639. BABYLON.Action = Action;
  47640. })(BABYLON || (BABYLON = {}));
  47641. //# sourceMappingURL=babylon.action.js.map
  47642. var BABYLON;
  47643. (function (BABYLON) {
  47644. /**
  47645. * ActionEvent is the event beint sent when an action is triggered.
  47646. */
  47647. var ActionEvent = /** @class */ (function () {
  47648. /**
  47649. * @param source The mesh or sprite that triggered the action.
  47650. * @param pointerX The X mouse cursor position at the time of the event
  47651. * @param pointerY The Y mouse cursor position at the time of the event
  47652. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47653. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47654. */
  47655. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47656. this.source = source;
  47657. this.pointerX = pointerX;
  47658. this.pointerY = pointerY;
  47659. this.meshUnderPointer = meshUnderPointer;
  47660. this.sourceEvent = sourceEvent;
  47661. this.additionalData = additionalData;
  47662. }
  47663. /**
  47664. * Helper function to auto-create an ActionEvent from a source mesh.
  47665. * @param source The source mesh that triggered the event
  47666. * @param evt {Event} The original (browser) event
  47667. */
  47668. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47669. var scene = source.getScene();
  47670. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47671. };
  47672. /**
  47673. * Helper function to auto-create an ActionEvent from a source mesh.
  47674. * @param source The source sprite that triggered the event
  47675. * @param scene Scene associated with the sprite
  47676. * @param evt {Event} The original (browser) event
  47677. */
  47678. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47679. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47680. };
  47681. /**
  47682. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47683. * @param scene the scene where the event occurred
  47684. * @param evt {Event} The original (browser) event
  47685. */
  47686. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47687. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47688. };
  47689. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47690. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47691. };
  47692. return ActionEvent;
  47693. }());
  47694. BABYLON.ActionEvent = ActionEvent;
  47695. /**
  47696. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47697. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47698. */
  47699. var ActionManager = /** @class */ (function () {
  47700. function ActionManager(scene) {
  47701. // Members
  47702. this.actions = new Array();
  47703. this.hoverCursor = '';
  47704. this._scene = scene;
  47705. scene._actionManagers.push(this);
  47706. }
  47707. Object.defineProperty(ActionManager, "NothingTrigger", {
  47708. get: function () {
  47709. return ActionManager._NothingTrigger;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47715. get: function () {
  47716. return ActionManager._OnPickTrigger;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47722. get: function () {
  47723. return ActionManager._OnLeftPickTrigger;
  47724. },
  47725. enumerable: true,
  47726. configurable: true
  47727. });
  47728. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47729. get: function () {
  47730. return ActionManager._OnRightPickTrigger;
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47736. get: function () {
  47737. return ActionManager._OnCenterPickTrigger;
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47743. get: function () {
  47744. return ActionManager._OnPickDownTrigger;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47750. get: function () {
  47751. return ActionManager._OnDoublePickTrigger;
  47752. },
  47753. enumerable: true,
  47754. configurable: true
  47755. });
  47756. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47757. get: function () {
  47758. return ActionManager._OnPickUpTrigger;
  47759. },
  47760. enumerable: true,
  47761. configurable: true
  47762. });
  47763. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47764. /// This trigger will only be raised if you also declared a OnPickDown
  47765. get: function () {
  47766. return ActionManager._OnPickOutTrigger;
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47772. get: function () {
  47773. return ActionManager._OnLongPressTrigger;
  47774. },
  47775. enumerable: true,
  47776. configurable: true
  47777. });
  47778. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47779. get: function () {
  47780. return ActionManager._OnPointerOverTrigger;
  47781. },
  47782. enumerable: true,
  47783. configurable: true
  47784. });
  47785. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47786. get: function () {
  47787. return ActionManager._OnPointerOutTrigger;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47793. get: function () {
  47794. return ActionManager._OnEveryFrameTrigger;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47800. get: function () {
  47801. return ActionManager._OnIntersectionEnterTrigger;
  47802. },
  47803. enumerable: true,
  47804. configurable: true
  47805. });
  47806. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47807. get: function () {
  47808. return ActionManager._OnIntersectionExitTrigger;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47814. get: function () {
  47815. return ActionManager._OnKeyDownTrigger;
  47816. },
  47817. enumerable: true,
  47818. configurable: true
  47819. });
  47820. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47821. get: function () {
  47822. return ActionManager._OnKeyUpTrigger;
  47823. },
  47824. enumerable: true,
  47825. configurable: true
  47826. });
  47827. // Methods
  47828. ActionManager.prototype.dispose = function () {
  47829. var index = this._scene._actionManagers.indexOf(this);
  47830. for (var i = 0; i < this.actions.length; i++) {
  47831. var action = this.actions[i];
  47832. ActionManager.Triggers[action.trigger]--;
  47833. if (ActionManager.Triggers[action.trigger] === 0) {
  47834. delete ActionManager.Triggers[action.trigger];
  47835. }
  47836. }
  47837. if (index > -1) {
  47838. this._scene._actionManagers.splice(index, 1);
  47839. }
  47840. };
  47841. ActionManager.prototype.getScene = function () {
  47842. return this._scene;
  47843. };
  47844. /**
  47845. * Does this action manager handles actions of any of the given triggers
  47846. * @param {number[]} triggers - the triggers to be tested
  47847. * @return {boolean} whether one (or more) of the triggers is handeled
  47848. */
  47849. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47850. for (var index = 0; index < this.actions.length; index++) {
  47851. var action = this.actions[index];
  47852. if (triggers.indexOf(action.trigger) > -1) {
  47853. return true;
  47854. }
  47855. }
  47856. return false;
  47857. };
  47858. /**
  47859. * Does this action manager handles actions of a given trigger
  47860. * @param {number} trigger - the trigger to be tested
  47861. * @return {boolean} whether the trigger is handeled
  47862. */
  47863. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47864. for (var index = 0; index < this.actions.length; index++) {
  47865. var action = this.actions[index];
  47866. if (action.trigger === trigger) {
  47867. return true;
  47868. }
  47869. }
  47870. return false;
  47871. };
  47872. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47873. /**
  47874. * Does this action manager has pointer triggers
  47875. * @return {boolean} whether or not it has pointer triggers
  47876. */
  47877. get: function () {
  47878. for (var index = 0; index < this.actions.length; index++) {
  47879. var action = this.actions[index];
  47880. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47881. return true;
  47882. }
  47883. }
  47884. return false;
  47885. },
  47886. enumerable: true,
  47887. configurable: true
  47888. });
  47889. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47890. /**
  47891. * Does this action manager has pick triggers
  47892. * @return {boolean} whether or not it has pick triggers
  47893. */
  47894. get: function () {
  47895. for (var index = 0; index < this.actions.length; index++) {
  47896. var action = this.actions[index];
  47897. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47898. return true;
  47899. }
  47900. }
  47901. return false;
  47902. },
  47903. enumerable: true,
  47904. configurable: true
  47905. });
  47906. Object.defineProperty(ActionManager, "HasTriggers", {
  47907. /**
  47908. * Does exist one action manager with at least one trigger
  47909. * @return {boolean} whether or not it exists one action manager with one trigger
  47910. **/
  47911. get: function () {
  47912. for (var t in ActionManager.Triggers) {
  47913. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47914. return true;
  47915. }
  47916. }
  47917. return false;
  47918. },
  47919. enumerable: true,
  47920. configurable: true
  47921. });
  47922. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47923. /**
  47924. * Does exist one action manager with at least one pick trigger
  47925. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47926. **/
  47927. get: function () {
  47928. for (var t in ActionManager.Triggers) {
  47929. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47930. var t_int = parseInt(t);
  47931. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47932. return true;
  47933. }
  47934. }
  47935. }
  47936. return false;
  47937. },
  47938. enumerable: true,
  47939. configurable: true
  47940. });
  47941. /**
  47942. * Does exist one action manager that handles actions of a given trigger
  47943. * @param {number} trigger - the trigger to be tested
  47944. * @return {boolean} whether the trigger is handeled by at least one action manager
  47945. **/
  47946. ActionManager.HasSpecificTrigger = function (trigger) {
  47947. for (var t in ActionManager.Triggers) {
  47948. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47949. var t_int = parseInt(t);
  47950. if (t_int === trigger) {
  47951. return true;
  47952. }
  47953. }
  47954. }
  47955. return false;
  47956. };
  47957. /**
  47958. * Registers an action to this action manager
  47959. * @param {BABYLON.Action} action - the action to be registered
  47960. * @return {BABYLON.Action} the action amended (prepared) after registration
  47961. */
  47962. ActionManager.prototype.registerAction = function (action) {
  47963. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47964. if (this.getScene().actionManager !== this) {
  47965. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47966. return null;
  47967. }
  47968. }
  47969. this.actions.push(action);
  47970. if (ActionManager.Triggers[action.trigger]) {
  47971. ActionManager.Triggers[action.trigger]++;
  47972. }
  47973. else {
  47974. ActionManager.Triggers[action.trigger] = 1;
  47975. }
  47976. action._actionManager = this;
  47977. action._prepare();
  47978. return action;
  47979. };
  47980. /**
  47981. * Unregisters an action to this action manager
  47982. * @param action The action to be unregistered
  47983. * @return whether the action has been unregistered
  47984. */
  47985. ActionManager.prototype.unregisterAction = function (action) {
  47986. var index = this.actions.indexOf(action);
  47987. if (index !== -1) {
  47988. this.actions.splice(index, 1);
  47989. ActionManager.Triggers[action.trigger] -= 1;
  47990. if (ActionManager.Triggers[action.trigger] === 0) {
  47991. delete ActionManager.Triggers[action.trigger];
  47992. }
  47993. delete action._actionManager;
  47994. return true;
  47995. }
  47996. return false;
  47997. };
  47998. /**
  47999. * Process a specific trigger
  48000. * @param {number} trigger - the trigger to process
  48001. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48002. */
  48003. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48004. for (var index = 0; index < this.actions.length; index++) {
  48005. var action = this.actions[index];
  48006. if (action.trigger === trigger) {
  48007. if (evt) {
  48008. if (trigger === ActionManager.OnKeyUpTrigger
  48009. || trigger === ActionManager.OnKeyDownTrigger) {
  48010. var parameter = action.getTriggerParameter();
  48011. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48012. if (!parameter.toLowerCase) {
  48013. continue;
  48014. }
  48015. var lowerCase = parameter.toLowerCase();
  48016. if (lowerCase !== evt.sourceEvent.key) {
  48017. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48018. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48019. if (actualkey !== lowerCase) {
  48020. continue;
  48021. }
  48022. }
  48023. }
  48024. }
  48025. }
  48026. action._executeCurrent(evt);
  48027. }
  48028. }
  48029. };
  48030. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48031. var properties = propertyPath.split(".");
  48032. for (var index = 0; index < properties.length - 1; index++) {
  48033. target = target[properties[index]];
  48034. }
  48035. return target;
  48036. };
  48037. ActionManager.prototype._getProperty = function (propertyPath) {
  48038. var properties = propertyPath.split(".");
  48039. return properties[properties.length - 1];
  48040. };
  48041. ActionManager.prototype.serialize = function (name) {
  48042. var root = {
  48043. children: new Array(),
  48044. name: name,
  48045. type: 3,
  48046. properties: new Array() // Empty for root but required
  48047. };
  48048. for (var i = 0; i < this.actions.length; i++) {
  48049. var triggerObject = {
  48050. type: 0,
  48051. children: new Array(),
  48052. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48053. properties: new Array()
  48054. };
  48055. var triggerOptions = this.actions[i].triggerOptions;
  48056. if (triggerOptions && typeof triggerOptions !== "number") {
  48057. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48058. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48059. }
  48060. else {
  48061. var parameter = {};
  48062. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48063. if (triggerOptions.parameter.mesh) {
  48064. parameter._meshId = triggerOptions.parameter.mesh.id;
  48065. }
  48066. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48067. }
  48068. }
  48069. // Serialize child action, recursively
  48070. this.actions[i].serialize(triggerObject);
  48071. // Add serialized trigger
  48072. root.children.push(triggerObject);
  48073. }
  48074. return root;
  48075. };
  48076. ActionManager.Parse = function (parsedActions, object, scene) {
  48077. var actionManager = new ActionManager(scene);
  48078. if (object === null)
  48079. scene.actionManager = actionManager;
  48080. else
  48081. object.actionManager = actionManager;
  48082. // instanciate a new object
  48083. var instanciate = function (name, params) {
  48084. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48085. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48086. newInstance.constructor.apply(newInstance, params);
  48087. return newInstance;
  48088. };
  48089. var parseParameter = function (name, value, target, propertyPath) {
  48090. if (propertyPath === null) {
  48091. // String, boolean or float
  48092. var floatValue = parseFloat(value);
  48093. if (value === "true" || value === "false")
  48094. return value === "true";
  48095. else
  48096. return isNaN(floatValue) ? value : floatValue;
  48097. }
  48098. var effectiveTarget = propertyPath.split(".");
  48099. var values = value.split(",");
  48100. // Get effective Target
  48101. for (var i = 0; i < effectiveTarget.length; i++) {
  48102. target = target[effectiveTarget[i]];
  48103. }
  48104. // Return appropriate value with its type
  48105. if (typeof (target) === "boolean")
  48106. return values[0] === "true";
  48107. if (typeof (target) === "string")
  48108. return values[0];
  48109. // Parameters with multiple values such as Vector3 etc.
  48110. var split = new Array();
  48111. for (var i = 0; i < values.length; i++)
  48112. split.push(parseFloat(values[i]));
  48113. if (target instanceof BABYLON.Vector3)
  48114. return BABYLON.Vector3.FromArray(split);
  48115. if (target instanceof BABYLON.Vector4)
  48116. return BABYLON.Vector4.FromArray(split);
  48117. if (target instanceof BABYLON.Color3)
  48118. return BABYLON.Color3.FromArray(split);
  48119. if (target instanceof BABYLON.Color4)
  48120. return BABYLON.Color4.FromArray(split);
  48121. return parseFloat(values[0]);
  48122. };
  48123. // traverse graph per trigger
  48124. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48125. if (combineArray === void 0) { combineArray = null; }
  48126. if (parsedAction.detached)
  48127. return;
  48128. var parameters = new Array();
  48129. var target = null;
  48130. var propertyPath = null;
  48131. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48132. // Parameters
  48133. if (parsedAction.type === 2)
  48134. parameters.push(actionManager);
  48135. else
  48136. parameters.push(trigger);
  48137. if (combine) {
  48138. var actions = new Array();
  48139. for (var j = 0; j < parsedAction.combine.length; j++) {
  48140. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48141. }
  48142. parameters.push(actions);
  48143. }
  48144. else {
  48145. for (var i = 0; i < parsedAction.properties.length; i++) {
  48146. var value = parsedAction.properties[i].value;
  48147. var name = parsedAction.properties[i].name;
  48148. var targetType = parsedAction.properties[i].targetType;
  48149. if (name === "target")
  48150. if (targetType !== null && targetType === "SceneProperties")
  48151. value = target = scene;
  48152. else
  48153. value = target = scene.getNodeByName(value);
  48154. else if (name === "parent")
  48155. value = scene.getNodeByName(value);
  48156. else if (name === "sound")
  48157. value = scene.getSoundByName(value);
  48158. else if (name !== "propertyPath") {
  48159. if (parsedAction.type === 2 && name === "operator")
  48160. value = BABYLON.ValueCondition[value];
  48161. else
  48162. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48163. }
  48164. else {
  48165. propertyPath = value;
  48166. }
  48167. parameters.push(value);
  48168. }
  48169. }
  48170. if (combineArray === null) {
  48171. parameters.push(condition);
  48172. }
  48173. else {
  48174. parameters.push(null);
  48175. }
  48176. // If interpolate value action
  48177. if (parsedAction.name === "InterpolateValueAction") {
  48178. var param = parameters[parameters.length - 2];
  48179. parameters[parameters.length - 1] = param;
  48180. parameters[parameters.length - 2] = condition;
  48181. }
  48182. // Action or condition(s) and not CombineAction
  48183. var newAction = instanciate(parsedAction.name, parameters);
  48184. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48185. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48186. if (action)
  48187. action.then(nothing);
  48188. else
  48189. actionManager.registerAction(nothing);
  48190. action = nothing;
  48191. }
  48192. if (combineArray === null) {
  48193. if (newAction instanceof BABYLON.Condition) {
  48194. condition = newAction;
  48195. newAction = action;
  48196. }
  48197. else {
  48198. condition = null;
  48199. if (action)
  48200. action.then(newAction);
  48201. else
  48202. actionManager.registerAction(newAction);
  48203. }
  48204. }
  48205. else {
  48206. combineArray.push(newAction);
  48207. }
  48208. for (var i = 0; i < parsedAction.children.length; i++)
  48209. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48210. };
  48211. // triggers
  48212. for (var i = 0; i < parsedActions.children.length; i++) {
  48213. var triggerParams;
  48214. var trigger = parsedActions.children[i];
  48215. if (trigger.properties.length > 0) {
  48216. var param = trigger.properties[0].value;
  48217. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48218. if (value._meshId) {
  48219. value.mesh = scene.getMeshByID(value._meshId);
  48220. }
  48221. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48222. }
  48223. else
  48224. triggerParams = ActionManager[trigger.name];
  48225. for (var j = 0; j < trigger.children.length; j++) {
  48226. if (!trigger.detached)
  48227. traverse(trigger.children[j], triggerParams, null, null);
  48228. }
  48229. }
  48230. };
  48231. ActionManager.GetTriggerName = function (trigger) {
  48232. switch (trigger) {
  48233. case 0: return "NothingTrigger";
  48234. case 1: return "OnPickTrigger";
  48235. case 2: return "OnLeftPickTrigger";
  48236. case 3: return "OnRightPickTrigger";
  48237. case 4: return "OnCenterPickTrigger";
  48238. case 5: return "OnPickDownTrigger";
  48239. case 6: return "OnPickUpTrigger";
  48240. case 7: return "OnLongPressTrigger";
  48241. case 8: return "OnPointerOverTrigger";
  48242. case 9: return "OnPointerOutTrigger";
  48243. case 10: return "OnEveryFrameTrigger";
  48244. case 11: return "OnIntersectionEnterTrigger";
  48245. case 12: return "OnIntersectionExitTrigger";
  48246. case 13: return "OnKeyDownTrigger";
  48247. case 14: return "OnKeyUpTrigger";
  48248. case 15: return "OnPickOutTrigger";
  48249. default: return "";
  48250. }
  48251. };
  48252. // Statics
  48253. ActionManager._NothingTrigger = 0;
  48254. ActionManager._OnPickTrigger = 1;
  48255. ActionManager._OnLeftPickTrigger = 2;
  48256. ActionManager._OnRightPickTrigger = 3;
  48257. ActionManager._OnCenterPickTrigger = 4;
  48258. ActionManager._OnPickDownTrigger = 5;
  48259. ActionManager._OnDoublePickTrigger = 6;
  48260. ActionManager._OnPickUpTrigger = 7;
  48261. ActionManager._OnLongPressTrigger = 8;
  48262. ActionManager._OnPointerOverTrigger = 9;
  48263. ActionManager._OnPointerOutTrigger = 10;
  48264. ActionManager._OnEveryFrameTrigger = 11;
  48265. ActionManager._OnIntersectionEnterTrigger = 12;
  48266. ActionManager._OnIntersectionExitTrigger = 13;
  48267. ActionManager._OnKeyDownTrigger = 14;
  48268. ActionManager._OnKeyUpTrigger = 15;
  48269. ActionManager._OnPickOutTrigger = 16;
  48270. ActionManager.Triggers = {};
  48271. return ActionManager;
  48272. }());
  48273. BABYLON.ActionManager = ActionManager;
  48274. })(BABYLON || (BABYLON = {}));
  48275. //# sourceMappingURL=babylon.actionManager.js.map
  48276. var BABYLON;
  48277. (function (BABYLON) {
  48278. var InterpolateValueAction = /** @class */ (function (_super) {
  48279. __extends(InterpolateValueAction, _super);
  48280. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48281. if (duration === void 0) { duration = 1000; }
  48282. var _this = _super.call(this, triggerOptions, condition) || this;
  48283. _this.propertyPath = propertyPath;
  48284. _this.value = value;
  48285. _this.duration = duration;
  48286. _this.stopOtherAnimations = stopOtherAnimations;
  48287. _this.onInterpolationDone = onInterpolationDone;
  48288. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48289. _this._target = _this._effectiveTarget = target;
  48290. return _this;
  48291. }
  48292. InterpolateValueAction.prototype._prepare = function () {
  48293. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48294. this._property = this._getProperty(this.propertyPath);
  48295. };
  48296. InterpolateValueAction.prototype.execute = function () {
  48297. var _this = this;
  48298. var scene = this._actionManager.getScene();
  48299. var keys = [
  48300. {
  48301. frame: 0,
  48302. value: this._effectiveTarget[this._property]
  48303. }, {
  48304. frame: 100,
  48305. value: this.value
  48306. }
  48307. ];
  48308. var dataType;
  48309. if (typeof this.value === "number") {
  48310. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48311. }
  48312. else if (this.value instanceof BABYLON.Color3) {
  48313. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48314. }
  48315. else if (this.value instanceof BABYLON.Vector3) {
  48316. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48317. }
  48318. else if (this.value instanceof BABYLON.Matrix) {
  48319. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48320. }
  48321. else if (this.value instanceof BABYLON.Quaternion) {
  48322. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48323. }
  48324. else {
  48325. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48326. return;
  48327. }
  48328. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48329. animation.setKeys(keys);
  48330. if (this.stopOtherAnimations) {
  48331. scene.stopAnimation(this._effectiveTarget);
  48332. }
  48333. var wrapper = function () {
  48334. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48335. if (_this.onInterpolationDone) {
  48336. _this.onInterpolationDone();
  48337. }
  48338. };
  48339. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48340. };
  48341. InterpolateValueAction.prototype.serialize = function (parent) {
  48342. return _super.prototype._serialize.call(this, {
  48343. name: "InterpolateValueAction",
  48344. properties: [
  48345. BABYLON.Action._GetTargetProperty(this._target),
  48346. { name: "propertyPath", value: this.propertyPath },
  48347. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48348. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48349. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48350. ]
  48351. }, parent);
  48352. };
  48353. return InterpolateValueAction;
  48354. }(BABYLON.Action));
  48355. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48356. })(BABYLON || (BABYLON = {}));
  48357. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48358. var BABYLON;
  48359. (function (BABYLON) {
  48360. var SwitchBooleanAction = /** @class */ (function (_super) {
  48361. __extends(SwitchBooleanAction, _super);
  48362. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48363. var _this = _super.call(this, triggerOptions, condition) || this;
  48364. _this.propertyPath = propertyPath;
  48365. _this._target = _this._effectiveTarget = target;
  48366. return _this;
  48367. }
  48368. SwitchBooleanAction.prototype._prepare = function () {
  48369. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48370. this._property = this._getProperty(this.propertyPath);
  48371. };
  48372. SwitchBooleanAction.prototype.execute = function () {
  48373. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48374. };
  48375. SwitchBooleanAction.prototype.serialize = function (parent) {
  48376. return _super.prototype._serialize.call(this, {
  48377. name: "SwitchBooleanAction",
  48378. properties: [
  48379. BABYLON.Action._GetTargetProperty(this._target),
  48380. { name: "propertyPath", value: this.propertyPath }
  48381. ]
  48382. }, parent);
  48383. };
  48384. return SwitchBooleanAction;
  48385. }(BABYLON.Action));
  48386. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48387. var SetStateAction = /** @class */ (function (_super) {
  48388. __extends(SetStateAction, _super);
  48389. function SetStateAction(triggerOptions, target, value, condition) {
  48390. var _this = _super.call(this, triggerOptions, condition) || this;
  48391. _this.value = value;
  48392. _this._target = target;
  48393. return _this;
  48394. }
  48395. SetStateAction.prototype.execute = function () {
  48396. this._target.state = this.value;
  48397. };
  48398. SetStateAction.prototype.serialize = function (parent) {
  48399. return _super.prototype._serialize.call(this, {
  48400. name: "SetStateAction",
  48401. properties: [
  48402. BABYLON.Action._GetTargetProperty(this._target),
  48403. { name: "value", value: this.value }
  48404. ]
  48405. }, parent);
  48406. };
  48407. return SetStateAction;
  48408. }(BABYLON.Action));
  48409. BABYLON.SetStateAction = SetStateAction;
  48410. var SetValueAction = /** @class */ (function (_super) {
  48411. __extends(SetValueAction, _super);
  48412. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48413. var _this = _super.call(this, triggerOptions, condition) || this;
  48414. _this.propertyPath = propertyPath;
  48415. _this.value = value;
  48416. _this._target = _this._effectiveTarget = target;
  48417. return _this;
  48418. }
  48419. SetValueAction.prototype._prepare = function () {
  48420. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48421. this._property = this._getProperty(this.propertyPath);
  48422. };
  48423. SetValueAction.prototype.execute = function () {
  48424. this._effectiveTarget[this._property] = this.value;
  48425. if (this._target.markAsDirty) {
  48426. this._target.markAsDirty(this._property);
  48427. }
  48428. };
  48429. SetValueAction.prototype.serialize = function (parent) {
  48430. return _super.prototype._serialize.call(this, {
  48431. name: "SetValueAction",
  48432. properties: [
  48433. BABYLON.Action._GetTargetProperty(this._target),
  48434. { name: "propertyPath", value: this.propertyPath },
  48435. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48436. ]
  48437. }, parent);
  48438. };
  48439. return SetValueAction;
  48440. }(BABYLON.Action));
  48441. BABYLON.SetValueAction = SetValueAction;
  48442. var IncrementValueAction = /** @class */ (function (_super) {
  48443. __extends(IncrementValueAction, _super);
  48444. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48445. var _this = _super.call(this, triggerOptions, condition) || this;
  48446. _this.propertyPath = propertyPath;
  48447. _this.value = value;
  48448. _this._target = _this._effectiveTarget = target;
  48449. return _this;
  48450. }
  48451. IncrementValueAction.prototype._prepare = function () {
  48452. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48453. this._property = this._getProperty(this.propertyPath);
  48454. if (typeof this._effectiveTarget[this._property] !== "number") {
  48455. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48456. }
  48457. };
  48458. IncrementValueAction.prototype.execute = function () {
  48459. this._effectiveTarget[this._property] += this.value;
  48460. if (this._target.markAsDirty) {
  48461. this._target.markAsDirty(this._property);
  48462. }
  48463. };
  48464. IncrementValueAction.prototype.serialize = function (parent) {
  48465. return _super.prototype._serialize.call(this, {
  48466. name: "IncrementValueAction",
  48467. properties: [
  48468. BABYLON.Action._GetTargetProperty(this._target),
  48469. { name: "propertyPath", value: this.propertyPath },
  48470. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48471. ]
  48472. }, parent);
  48473. };
  48474. return IncrementValueAction;
  48475. }(BABYLON.Action));
  48476. BABYLON.IncrementValueAction = IncrementValueAction;
  48477. var PlayAnimationAction = /** @class */ (function (_super) {
  48478. __extends(PlayAnimationAction, _super);
  48479. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48480. var _this = _super.call(this, triggerOptions, condition) || this;
  48481. _this.from = from;
  48482. _this.to = to;
  48483. _this.loop = loop;
  48484. _this._target = target;
  48485. return _this;
  48486. }
  48487. PlayAnimationAction.prototype._prepare = function () {
  48488. };
  48489. PlayAnimationAction.prototype.execute = function () {
  48490. var scene = this._actionManager.getScene();
  48491. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48492. };
  48493. PlayAnimationAction.prototype.serialize = function (parent) {
  48494. return _super.prototype._serialize.call(this, {
  48495. name: "PlayAnimationAction",
  48496. properties: [
  48497. BABYLON.Action._GetTargetProperty(this._target),
  48498. { name: "from", value: String(this.from) },
  48499. { name: "to", value: String(this.to) },
  48500. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48501. ]
  48502. }, parent);
  48503. };
  48504. return PlayAnimationAction;
  48505. }(BABYLON.Action));
  48506. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48507. var StopAnimationAction = /** @class */ (function (_super) {
  48508. __extends(StopAnimationAction, _super);
  48509. function StopAnimationAction(triggerOptions, target, condition) {
  48510. var _this = _super.call(this, triggerOptions, condition) || this;
  48511. _this._target = target;
  48512. return _this;
  48513. }
  48514. StopAnimationAction.prototype._prepare = function () {
  48515. };
  48516. StopAnimationAction.prototype.execute = function () {
  48517. var scene = this._actionManager.getScene();
  48518. scene.stopAnimation(this._target);
  48519. };
  48520. StopAnimationAction.prototype.serialize = function (parent) {
  48521. return _super.prototype._serialize.call(this, {
  48522. name: "StopAnimationAction",
  48523. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48524. }, parent);
  48525. };
  48526. return StopAnimationAction;
  48527. }(BABYLON.Action));
  48528. BABYLON.StopAnimationAction = StopAnimationAction;
  48529. var DoNothingAction = /** @class */ (function (_super) {
  48530. __extends(DoNothingAction, _super);
  48531. function DoNothingAction(triggerOptions, condition) {
  48532. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48533. return _super.call(this, triggerOptions, condition) || this;
  48534. }
  48535. DoNothingAction.prototype.execute = function () {
  48536. };
  48537. DoNothingAction.prototype.serialize = function (parent) {
  48538. return _super.prototype._serialize.call(this, {
  48539. name: "DoNothingAction",
  48540. properties: []
  48541. }, parent);
  48542. };
  48543. return DoNothingAction;
  48544. }(BABYLON.Action));
  48545. BABYLON.DoNothingAction = DoNothingAction;
  48546. var CombineAction = /** @class */ (function (_super) {
  48547. __extends(CombineAction, _super);
  48548. function CombineAction(triggerOptions, children, condition) {
  48549. var _this = _super.call(this, triggerOptions, condition) || this;
  48550. _this.children = children;
  48551. return _this;
  48552. }
  48553. CombineAction.prototype._prepare = function () {
  48554. for (var index = 0; index < this.children.length; index++) {
  48555. this.children[index]._actionManager = this._actionManager;
  48556. this.children[index]._prepare();
  48557. }
  48558. };
  48559. CombineAction.prototype.execute = function (evt) {
  48560. for (var index = 0; index < this.children.length; index++) {
  48561. this.children[index].execute(evt);
  48562. }
  48563. };
  48564. CombineAction.prototype.serialize = function (parent) {
  48565. var serializationObject = _super.prototype._serialize.call(this, {
  48566. name: "CombineAction",
  48567. properties: [],
  48568. combine: []
  48569. }, parent);
  48570. for (var i = 0; i < this.children.length; i++) {
  48571. serializationObject.combine.push(this.children[i].serialize(null));
  48572. }
  48573. return serializationObject;
  48574. };
  48575. return CombineAction;
  48576. }(BABYLON.Action));
  48577. BABYLON.CombineAction = CombineAction;
  48578. var ExecuteCodeAction = /** @class */ (function (_super) {
  48579. __extends(ExecuteCodeAction, _super);
  48580. function ExecuteCodeAction(triggerOptions, func, condition) {
  48581. var _this = _super.call(this, triggerOptions, condition) || this;
  48582. _this.func = func;
  48583. return _this;
  48584. }
  48585. ExecuteCodeAction.prototype.execute = function (evt) {
  48586. this.func(evt);
  48587. };
  48588. return ExecuteCodeAction;
  48589. }(BABYLON.Action));
  48590. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48591. var SetParentAction = /** @class */ (function (_super) {
  48592. __extends(SetParentAction, _super);
  48593. function SetParentAction(triggerOptions, target, parent, condition) {
  48594. var _this = _super.call(this, triggerOptions, condition) || this;
  48595. _this._target = target;
  48596. _this._parent = parent;
  48597. return _this;
  48598. }
  48599. SetParentAction.prototype._prepare = function () {
  48600. };
  48601. SetParentAction.prototype.execute = function () {
  48602. if (this._target.parent === this._parent) {
  48603. return;
  48604. }
  48605. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48606. invertParentWorldMatrix.invert();
  48607. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48608. this._target.parent = this._parent;
  48609. };
  48610. SetParentAction.prototype.serialize = function (parent) {
  48611. return _super.prototype._serialize.call(this, {
  48612. name: "SetParentAction",
  48613. properties: [
  48614. BABYLON.Action._GetTargetProperty(this._target),
  48615. BABYLON.Action._GetTargetProperty(this._parent),
  48616. ]
  48617. }, parent);
  48618. };
  48619. return SetParentAction;
  48620. }(BABYLON.Action));
  48621. BABYLON.SetParentAction = SetParentAction;
  48622. var PlaySoundAction = /** @class */ (function (_super) {
  48623. __extends(PlaySoundAction, _super);
  48624. function PlaySoundAction(triggerOptions, sound, condition) {
  48625. var _this = _super.call(this, triggerOptions, condition) || this;
  48626. _this._sound = sound;
  48627. return _this;
  48628. }
  48629. PlaySoundAction.prototype._prepare = function () {
  48630. };
  48631. PlaySoundAction.prototype.execute = function () {
  48632. if (this._sound !== undefined)
  48633. this._sound.play();
  48634. };
  48635. PlaySoundAction.prototype.serialize = function (parent) {
  48636. return _super.prototype._serialize.call(this, {
  48637. name: "PlaySoundAction",
  48638. properties: [{ name: "sound", value: this._sound.name }]
  48639. }, parent);
  48640. };
  48641. return PlaySoundAction;
  48642. }(BABYLON.Action));
  48643. BABYLON.PlaySoundAction = PlaySoundAction;
  48644. var StopSoundAction = /** @class */ (function (_super) {
  48645. __extends(StopSoundAction, _super);
  48646. function StopSoundAction(triggerOptions, sound, condition) {
  48647. var _this = _super.call(this, triggerOptions, condition) || this;
  48648. _this._sound = sound;
  48649. return _this;
  48650. }
  48651. StopSoundAction.prototype._prepare = function () {
  48652. };
  48653. StopSoundAction.prototype.execute = function () {
  48654. if (this._sound !== undefined)
  48655. this._sound.stop();
  48656. };
  48657. StopSoundAction.prototype.serialize = function (parent) {
  48658. return _super.prototype._serialize.call(this, {
  48659. name: "StopSoundAction",
  48660. properties: [{ name: "sound", value: this._sound.name }]
  48661. }, parent);
  48662. };
  48663. return StopSoundAction;
  48664. }(BABYLON.Action));
  48665. BABYLON.StopSoundAction = StopSoundAction;
  48666. })(BABYLON || (BABYLON = {}));
  48667. //# sourceMappingURL=babylon.directActions.js.map
  48668. var BABYLON;
  48669. (function (BABYLON) {
  48670. var SpriteManager = /** @class */ (function () {
  48671. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48672. if (epsilon === void 0) { epsilon = 0.01; }
  48673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48674. this.name = name;
  48675. this.sprites = new Array();
  48676. this.renderingGroupId = 0;
  48677. this.layerMask = 0x0FFFFFFF;
  48678. this.fogEnabled = true;
  48679. this.isPickable = false;
  48680. /**
  48681. * An event triggered when the manager is disposed.
  48682. * @type {BABYLON.Observable}
  48683. */
  48684. this.onDisposeObservable = new BABYLON.Observable();
  48685. this._vertexBuffers = {};
  48686. this._capacity = capacity;
  48687. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48688. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48689. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48690. if (cellSize.width && cellSize.height) {
  48691. this.cellWidth = cellSize.width;
  48692. this.cellHeight = cellSize.height;
  48693. }
  48694. else if (cellSize !== undefined) {
  48695. this.cellWidth = cellSize;
  48696. this.cellHeight = cellSize;
  48697. }
  48698. else {
  48699. return;
  48700. }
  48701. this._epsilon = epsilon;
  48702. this._scene = scene;
  48703. this._scene.spriteManagers.push(this);
  48704. var indices = [];
  48705. var index = 0;
  48706. for (var count = 0; count < capacity; count++) {
  48707. indices.push(index);
  48708. indices.push(index + 1);
  48709. indices.push(index + 2);
  48710. indices.push(index);
  48711. indices.push(index + 2);
  48712. indices.push(index + 3);
  48713. index += 4;
  48714. }
  48715. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48716. // VBO
  48717. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48718. this._vertexData = new Float32Array(capacity * 16 * 4);
  48719. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48720. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48721. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48722. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48723. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48725. this._vertexBuffers["options"] = options;
  48726. this._vertexBuffers["cellInfo"] = cellInfo;
  48727. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48728. // Effects
  48729. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48730. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48731. }
  48732. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48733. set: function (callback) {
  48734. if (this._onDisposeObserver) {
  48735. this.onDisposeObservable.remove(this._onDisposeObserver);
  48736. }
  48737. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48738. },
  48739. enumerable: true,
  48740. configurable: true
  48741. });
  48742. Object.defineProperty(SpriteManager.prototype, "texture", {
  48743. get: function () {
  48744. return this._spriteTexture;
  48745. },
  48746. set: function (value) {
  48747. this._spriteTexture = value;
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48753. var arrayOffset = index * 16;
  48754. if (offsetX === 0)
  48755. offsetX = this._epsilon;
  48756. else if (offsetX === 1)
  48757. offsetX = 1 - this._epsilon;
  48758. if (offsetY === 0)
  48759. offsetY = this._epsilon;
  48760. else if (offsetY === 1)
  48761. offsetY = 1 - this._epsilon;
  48762. this._vertexData[arrayOffset] = sprite.position.x;
  48763. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48764. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48765. this._vertexData[arrayOffset + 3] = sprite.angle;
  48766. this._vertexData[arrayOffset + 4] = sprite.width;
  48767. this._vertexData[arrayOffset + 5] = sprite.height;
  48768. this._vertexData[arrayOffset + 6] = offsetX;
  48769. this._vertexData[arrayOffset + 7] = offsetY;
  48770. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48771. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48772. var offset = (sprite.cellIndex / rowSize) >> 0;
  48773. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48774. this._vertexData[arrayOffset + 11] = offset;
  48775. // Color
  48776. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48777. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48778. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48779. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48780. };
  48781. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48782. var count = Math.min(this._capacity, this.sprites.length);
  48783. var min = BABYLON.Vector3.Zero();
  48784. var max = BABYLON.Vector3.Zero();
  48785. var distance = Number.MAX_VALUE;
  48786. var currentSprite = null;
  48787. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48788. var cameraView = camera.getViewMatrix();
  48789. for (var index = 0; index < count; index++) {
  48790. var sprite = this.sprites[index];
  48791. if (!sprite) {
  48792. continue;
  48793. }
  48794. if (predicate) {
  48795. if (!predicate(sprite)) {
  48796. continue;
  48797. }
  48798. }
  48799. else if (!sprite.isPickable) {
  48800. continue;
  48801. }
  48802. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48803. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48804. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48805. if (ray.intersectsBoxMinMax(min, max)) {
  48806. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48807. if (distance > currentDistance) {
  48808. distance = currentDistance;
  48809. currentSprite = sprite;
  48810. if (fastCheck) {
  48811. break;
  48812. }
  48813. }
  48814. }
  48815. }
  48816. if (currentSprite) {
  48817. var result = new BABYLON.PickingInfo();
  48818. result.hit = true;
  48819. result.pickedSprite = currentSprite;
  48820. result.distance = distance;
  48821. return result;
  48822. }
  48823. return null;
  48824. };
  48825. SpriteManager.prototype.render = function () {
  48826. // Check
  48827. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48828. return;
  48829. var engine = this._scene.getEngine();
  48830. var baseSize = this._spriteTexture.getBaseSize();
  48831. // Sprites
  48832. var deltaTime = engine.getDeltaTime();
  48833. var max = Math.min(this._capacity, this.sprites.length);
  48834. var rowSize = baseSize.width / this.cellWidth;
  48835. var offset = 0;
  48836. for (var index = 0; index < max; index++) {
  48837. var sprite = this.sprites[index];
  48838. if (!sprite) {
  48839. continue;
  48840. }
  48841. sprite._animate(deltaTime);
  48842. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48843. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48844. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48845. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48846. }
  48847. this._buffer.update(this._vertexData);
  48848. // Render
  48849. var effect = this._effectBase;
  48850. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48851. effect = this._effectFog;
  48852. }
  48853. engine.enableEffect(effect);
  48854. var viewMatrix = this._scene.getViewMatrix();
  48855. effect.setTexture("diffuseSampler", this._spriteTexture);
  48856. effect.setMatrix("view", viewMatrix);
  48857. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48858. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48859. // Fog
  48860. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48861. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48862. effect.setColor3("vFogColor", this._scene.fogColor);
  48863. }
  48864. // VBOs
  48865. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48866. // Draw order
  48867. engine.setDepthFunctionToLessOrEqual();
  48868. effect.setBool("alphaTest", true);
  48869. engine.setColorWrite(false);
  48870. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48871. engine.setColorWrite(true);
  48872. effect.setBool("alphaTest", false);
  48873. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48874. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48876. };
  48877. SpriteManager.prototype.dispose = function () {
  48878. if (this._buffer) {
  48879. this._buffer.dispose();
  48880. this._buffer = null;
  48881. }
  48882. if (this._indexBuffer) {
  48883. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48884. this._indexBuffer = null;
  48885. }
  48886. if (this._spriteTexture) {
  48887. this._spriteTexture.dispose();
  48888. this._spriteTexture = null;
  48889. }
  48890. // Remove from scene
  48891. var index = this._scene.spriteManagers.indexOf(this);
  48892. this._scene.spriteManagers.splice(index, 1);
  48893. // Callback
  48894. this.onDisposeObservable.notifyObservers(this);
  48895. this.onDisposeObservable.clear();
  48896. };
  48897. return SpriteManager;
  48898. }());
  48899. BABYLON.SpriteManager = SpriteManager;
  48900. })(BABYLON || (BABYLON = {}));
  48901. //# sourceMappingURL=babylon.spriteManager.js.map
  48902. var BABYLON;
  48903. (function (BABYLON) {
  48904. var Sprite = /** @class */ (function () {
  48905. function Sprite(name, manager) {
  48906. this.name = name;
  48907. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48908. this.width = 1.0;
  48909. this.height = 1.0;
  48910. this.angle = 0;
  48911. this.cellIndex = 0;
  48912. this.invertU = 0;
  48913. this.invertV = 0;
  48914. this.animations = new Array();
  48915. this.isPickable = false;
  48916. this._animationStarted = false;
  48917. this._loopAnimation = false;
  48918. this._fromIndex = 0;
  48919. this._toIndex = 0;
  48920. this._delay = 0;
  48921. this._direction = 1;
  48922. this._time = 0;
  48923. this._manager = manager;
  48924. this._manager.sprites.push(this);
  48925. this.position = BABYLON.Vector3.Zero();
  48926. }
  48927. Object.defineProperty(Sprite.prototype, "size", {
  48928. get: function () {
  48929. return this.width;
  48930. },
  48931. set: function (value) {
  48932. this.width = value;
  48933. this.height = value;
  48934. },
  48935. enumerable: true,
  48936. configurable: true
  48937. });
  48938. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48939. this._fromIndex = from;
  48940. this._toIndex = to;
  48941. this._loopAnimation = loop;
  48942. this._delay = delay;
  48943. this._animationStarted = true;
  48944. this._direction = from < to ? 1 : -1;
  48945. this.cellIndex = from;
  48946. this._time = 0;
  48947. this._onAnimationEnd = onAnimationEnd;
  48948. };
  48949. Sprite.prototype.stopAnimation = function () {
  48950. this._animationStarted = false;
  48951. };
  48952. Sprite.prototype._animate = function (deltaTime) {
  48953. if (!this._animationStarted)
  48954. return;
  48955. this._time += deltaTime;
  48956. if (this._time > this._delay) {
  48957. this._time = this._time % this._delay;
  48958. this.cellIndex += this._direction;
  48959. if (this.cellIndex > this._toIndex) {
  48960. if (this._loopAnimation) {
  48961. this.cellIndex = this._fromIndex;
  48962. }
  48963. else {
  48964. this.cellIndex = this._toIndex;
  48965. this._animationStarted = false;
  48966. if (this._onAnimationEnd) {
  48967. this._onAnimationEnd();
  48968. }
  48969. if (this.disposeWhenFinishedAnimating) {
  48970. this.dispose();
  48971. }
  48972. }
  48973. }
  48974. }
  48975. };
  48976. Sprite.prototype.dispose = function () {
  48977. for (var i = 0; i < this._manager.sprites.length; i++) {
  48978. if (this._manager.sprites[i] == this) {
  48979. this._manager.sprites.splice(i, 1);
  48980. }
  48981. }
  48982. };
  48983. return Sprite;
  48984. }());
  48985. BABYLON.Sprite = Sprite;
  48986. })(BABYLON || (BABYLON = {}));
  48987. //# sourceMappingURL=babylon.sprite.js.map
  48988. var BABYLON;
  48989. (function (BABYLON) {
  48990. var IntersectionInfo = /** @class */ (function () {
  48991. function IntersectionInfo(bu, bv, distance) {
  48992. this.bu = bu;
  48993. this.bv = bv;
  48994. this.distance = distance;
  48995. this.faceId = 0;
  48996. this.subMeshId = 0;
  48997. }
  48998. return IntersectionInfo;
  48999. }());
  49000. BABYLON.IntersectionInfo = IntersectionInfo;
  49001. var PickingInfo = /** @class */ (function () {
  49002. function PickingInfo() {
  49003. this.hit = false;
  49004. this.distance = 0;
  49005. this.pickedPoint = null;
  49006. this.pickedMesh = null;
  49007. this.bu = 0;
  49008. this.bv = 0;
  49009. this.faceId = -1;
  49010. this.subMeshId = 0;
  49011. this.pickedSprite = null;
  49012. }
  49013. // Methods
  49014. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49015. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49016. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49017. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49018. return null;
  49019. }
  49020. var indices = this.pickedMesh.getIndices();
  49021. if (!indices) {
  49022. return null;
  49023. }
  49024. var result;
  49025. if (useVerticesNormals) {
  49026. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49027. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49028. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49029. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49030. normal0 = normal0.scale(this.bu);
  49031. normal1 = normal1.scale(this.bv);
  49032. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49033. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49034. }
  49035. else {
  49036. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49037. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49038. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49039. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49040. var p1p2 = vertex1.subtract(vertex2);
  49041. var p3p2 = vertex3.subtract(vertex2);
  49042. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49043. }
  49044. if (useWorldCoordinates) {
  49045. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49046. }
  49047. return BABYLON.Vector3.Normalize(result);
  49048. };
  49049. PickingInfo.prototype.getTextureCoordinates = function () {
  49050. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49051. return null;
  49052. }
  49053. var indices = this.pickedMesh.getIndices();
  49054. if (!indices) {
  49055. return null;
  49056. }
  49057. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49058. if (!uvs) {
  49059. return null;
  49060. }
  49061. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49062. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49063. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49064. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49065. uv1 = uv1.scale(this.bu);
  49066. uv2 = uv2.scale(this.bv);
  49067. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49068. };
  49069. return PickingInfo;
  49070. }());
  49071. BABYLON.PickingInfo = PickingInfo;
  49072. })(BABYLON || (BABYLON = {}));
  49073. //# sourceMappingURL=babylon.pickingInfo.js.map
  49074. var BABYLON;
  49075. (function (BABYLON) {
  49076. var Ray = /** @class */ (function () {
  49077. function Ray(origin, direction, length) {
  49078. if (length === void 0) { length = Number.MAX_VALUE; }
  49079. this.origin = origin;
  49080. this.direction = direction;
  49081. this.length = length;
  49082. }
  49083. // Methods
  49084. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49085. var d = 0.0;
  49086. var maxValue = Number.MAX_VALUE;
  49087. var inv;
  49088. var min;
  49089. var max;
  49090. var temp;
  49091. if (Math.abs(this.direction.x) < 0.0000001) {
  49092. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49093. return false;
  49094. }
  49095. }
  49096. else {
  49097. inv = 1.0 / this.direction.x;
  49098. min = (minimum.x - this.origin.x) * inv;
  49099. max = (maximum.x - this.origin.x) * inv;
  49100. if (max === -Infinity) {
  49101. max = Infinity;
  49102. }
  49103. if (min > max) {
  49104. temp = min;
  49105. min = max;
  49106. max = temp;
  49107. }
  49108. d = Math.max(min, d);
  49109. maxValue = Math.min(max, maxValue);
  49110. if (d > maxValue) {
  49111. return false;
  49112. }
  49113. }
  49114. if (Math.abs(this.direction.y) < 0.0000001) {
  49115. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49116. return false;
  49117. }
  49118. }
  49119. else {
  49120. inv = 1.0 / this.direction.y;
  49121. min = (minimum.y - this.origin.y) * inv;
  49122. max = (maximum.y - this.origin.y) * inv;
  49123. if (max === -Infinity) {
  49124. max = Infinity;
  49125. }
  49126. if (min > max) {
  49127. temp = min;
  49128. min = max;
  49129. max = temp;
  49130. }
  49131. d = Math.max(min, d);
  49132. maxValue = Math.min(max, maxValue);
  49133. if (d > maxValue) {
  49134. return false;
  49135. }
  49136. }
  49137. if (Math.abs(this.direction.z) < 0.0000001) {
  49138. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49139. return false;
  49140. }
  49141. }
  49142. else {
  49143. inv = 1.0 / this.direction.z;
  49144. min = (minimum.z - this.origin.z) * inv;
  49145. max = (maximum.z - this.origin.z) * inv;
  49146. if (max === -Infinity) {
  49147. max = Infinity;
  49148. }
  49149. if (min > max) {
  49150. temp = min;
  49151. min = max;
  49152. max = temp;
  49153. }
  49154. d = Math.max(min, d);
  49155. maxValue = Math.min(max, maxValue);
  49156. if (d > maxValue) {
  49157. return false;
  49158. }
  49159. }
  49160. return true;
  49161. };
  49162. Ray.prototype.intersectsBox = function (box) {
  49163. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49164. };
  49165. Ray.prototype.intersectsSphere = function (sphere) {
  49166. var x = sphere.center.x - this.origin.x;
  49167. var y = sphere.center.y - this.origin.y;
  49168. var z = sphere.center.z - this.origin.z;
  49169. var pyth = (x * x) + (y * y) + (z * z);
  49170. var rr = sphere.radius * sphere.radius;
  49171. if (pyth <= rr) {
  49172. return true;
  49173. }
  49174. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49175. if (dot < 0.0) {
  49176. return false;
  49177. }
  49178. var temp = pyth - (dot * dot);
  49179. return temp <= rr;
  49180. };
  49181. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49182. if (!this._edge1) {
  49183. this._edge1 = BABYLON.Vector3.Zero();
  49184. this._edge2 = BABYLON.Vector3.Zero();
  49185. this._pvec = BABYLON.Vector3.Zero();
  49186. this._tvec = BABYLON.Vector3.Zero();
  49187. this._qvec = BABYLON.Vector3.Zero();
  49188. }
  49189. vertex1.subtractToRef(vertex0, this._edge1);
  49190. vertex2.subtractToRef(vertex0, this._edge2);
  49191. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49192. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49193. if (det === 0) {
  49194. return null;
  49195. }
  49196. var invdet = 1 / det;
  49197. this.origin.subtractToRef(vertex0, this._tvec);
  49198. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49199. if (bu < 0 || bu > 1.0) {
  49200. return null;
  49201. }
  49202. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49203. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49204. if (bv < 0 || bu + bv > 1.0) {
  49205. return null;
  49206. }
  49207. //check if the distance is longer than the predefined length.
  49208. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49209. if (distance > this.length) {
  49210. return null;
  49211. }
  49212. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49213. };
  49214. Ray.prototype.intersectsPlane = function (plane) {
  49215. var distance;
  49216. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49217. if (Math.abs(result1) < 9.99999997475243E-07) {
  49218. return null;
  49219. }
  49220. else {
  49221. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49222. distance = (-plane.d - result2) / result1;
  49223. if (distance < 0.0) {
  49224. if (distance < -9.99999997475243E-07) {
  49225. return null;
  49226. }
  49227. else {
  49228. return 0;
  49229. }
  49230. }
  49231. return distance;
  49232. }
  49233. };
  49234. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49235. var tm = BABYLON.Tmp.Matrix[0];
  49236. mesh.getWorldMatrix().invertToRef(tm);
  49237. if (this._tmpRay) {
  49238. Ray.TransformToRef(this, tm, this._tmpRay);
  49239. }
  49240. else {
  49241. this._tmpRay = Ray.Transform(this, tm);
  49242. }
  49243. return mesh.intersects(this._tmpRay, fastCheck);
  49244. };
  49245. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49246. if (results) {
  49247. results.length = 0;
  49248. }
  49249. else {
  49250. results = [];
  49251. }
  49252. for (var i = 0; i < meshes.length; i++) {
  49253. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49254. if (pickInfo.hit) {
  49255. results.push(pickInfo);
  49256. }
  49257. }
  49258. results.sort(this._comparePickingInfo);
  49259. return results;
  49260. };
  49261. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49262. if (pickingInfoA.distance < pickingInfoB.distance) {
  49263. return -1;
  49264. }
  49265. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49266. return 1;
  49267. }
  49268. else {
  49269. return 0;
  49270. }
  49271. };
  49272. /**
  49273. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49274. * @param sega the first point of the segment to test the intersection against
  49275. * @param segb the second point of the segment to test the intersection against
  49276. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49277. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49278. */
  49279. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49280. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49281. var u = segb.subtract(sega);
  49282. var v = rsegb.subtract(this.origin);
  49283. var w = sega.subtract(this.origin);
  49284. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49285. var b = BABYLON.Vector3.Dot(u, v);
  49286. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49287. var d = BABYLON.Vector3.Dot(u, w);
  49288. var e = BABYLON.Vector3.Dot(v, w);
  49289. var D = a * c - b * b; // always >= 0
  49290. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49291. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49292. // compute the line parameters of the two closest points
  49293. if (D < Ray.smallnum) {
  49294. sN = 0.0; // force using point P0 on segment S1
  49295. sD = 1.0; // to prevent possible division by 0.0 later
  49296. tN = e;
  49297. tD = c;
  49298. }
  49299. else {
  49300. sN = (b * e - c * d);
  49301. tN = (a * e - b * d);
  49302. if (sN < 0.0) {
  49303. sN = 0.0;
  49304. tN = e;
  49305. tD = c;
  49306. }
  49307. else if (sN > sD) {
  49308. sN = sD;
  49309. tN = e + b;
  49310. tD = c;
  49311. }
  49312. }
  49313. if (tN < 0.0) {
  49314. tN = 0.0;
  49315. // recompute sc for this edge
  49316. if (-d < 0.0) {
  49317. sN = 0.0;
  49318. }
  49319. else if (-d > a)
  49320. sN = sD;
  49321. else {
  49322. sN = -d;
  49323. sD = a;
  49324. }
  49325. }
  49326. else if (tN > tD) {
  49327. tN = tD;
  49328. // recompute sc for this edge
  49329. if ((-d + b) < 0.0) {
  49330. sN = 0;
  49331. }
  49332. else if ((-d + b) > a) {
  49333. sN = sD;
  49334. }
  49335. else {
  49336. sN = (-d + b);
  49337. sD = a;
  49338. }
  49339. }
  49340. // finally do the division to get sc and tc
  49341. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49342. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49343. // get the difference of the two closest points
  49344. var qtc = v.multiplyByFloats(tc, tc, tc);
  49345. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49346. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49347. if (isIntersected) {
  49348. return qtc.length();
  49349. }
  49350. return -1;
  49351. };
  49352. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49353. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49354. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49355. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49356. this.direction.normalize();
  49357. return this;
  49358. };
  49359. // Statics
  49360. Ray.Zero = function () {
  49361. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49362. };
  49363. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49364. var result = Ray.Zero();
  49365. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49366. };
  49367. /**
  49368. * 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
  49369. * transformed to the given world matrix.
  49370. * @param origin The origin point
  49371. * @param end The end point
  49372. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49373. */
  49374. Ray.CreateNewFromTo = function (origin, end, world) {
  49375. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49376. var direction = end.subtract(origin);
  49377. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49378. direction.normalize();
  49379. return Ray.Transform(new Ray(origin, direction, length), world);
  49380. };
  49381. Ray.Transform = function (ray, matrix) {
  49382. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49383. Ray.TransformToRef(ray, matrix, result);
  49384. return result;
  49385. };
  49386. Ray.TransformToRef = function (ray, matrix, result) {
  49387. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49388. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49389. result.length = ray.length;
  49390. var dir = result.direction;
  49391. var len = dir.length();
  49392. if (!(len === 0 || len === 1)) {
  49393. var num = 1.0 / len;
  49394. dir.x *= num;
  49395. dir.y *= num;
  49396. dir.z *= num;
  49397. result.length *= len;
  49398. }
  49399. };
  49400. Ray.smallnum = 0.00000001;
  49401. Ray.rayl = 10e8;
  49402. return Ray;
  49403. }());
  49404. BABYLON.Ray = Ray;
  49405. })(BABYLON || (BABYLON = {}));
  49406. //# sourceMappingURL=babylon.ray.js.map
  49407. var BABYLON;
  49408. (function (BABYLON) {
  49409. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49410. if (boxMin.x > sphereCenter.x + sphereRadius)
  49411. return false;
  49412. if (sphereCenter.x - sphereRadius > boxMax.x)
  49413. return false;
  49414. if (boxMin.y > sphereCenter.y + sphereRadius)
  49415. return false;
  49416. if (sphereCenter.y - sphereRadius > boxMax.y)
  49417. return false;
  49418. if (boxMin.z > sphereCenter.z + sphereRadius)
  49419. return false;
  49420. if (sphereCenter.z - sphereRadius > boxMax.z)
  49421. return false;
  49422. return true;
  49423. };
  49424. var getLowestRoot = (function () {
  49425. var result = { root: 0, found: false };
  49426. return function (a, b, c, maxR) {
  49427. result.root = 0;
  49428. result.found = false;
  49429. var determinant = b * b - 4.0 * a * c;
  49430. if (determinant < 0)
  49431. return result;
  49432. var sqrtD = Math.sqrt(determinant);
  49433. var r1 = (-b - sqrtD) / (2.0 * a);
  49434. var r2 = (-b + sqrtD) / (2.0 * a);
  49435. if (r1 > r2) {
  49436. var temp = r2;
  49437. r2 = r1;
  49438. r1 = temp;
  49439. }
  49440. if (r1 > 0 && r1 < maxR) {
  49441. result.root = r1;
  49442. result.found = true;
  49443. return result;
  49444. }
  49445. if (r2 > 0 && r2 < maxR) {
  49446. result.root = r2;
  49447. result.found = true;
  49448. return result;
  49449. }
  49450. return result;
  49451. };
  49452. })();
  49453. var Collider = /** @class */ (function () {
  49454. function Collider() {
  49455. this._collisionPoint = BABYLON.Vector3.Zero();
  49456. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49457. this._tempVector = BABYLON.Vector3.Zero();
  49458. this._tempVector2 = BABYLON.Vector3.Zero();
  49459. this._tempVector3 = BABYLON.Vector3.Zero();
  49460. this._tempVector4 = BABYLON.Vector3.Zero();
  49461. this._edge = BABYLON.Vector3.Zero();
  49462. this._baseToVertex = BABYLON.Vector3.Zero();
  49463. this._destinationPoint = BABYLON.Vector3.Zero();
  49464. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49465. this._displacementVector = BABYLON.Vector3.Zero();
  49466. this._radius = BABYLON.Vector3.One();
  49467. this._retry = 0;
  49468. this._basePointWorld = BABYLON.Vector3.Zero();
  49469. this._velocityWorld = BABYLON.Vector3.Zero();
  49470. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49471. this._collisionMask = -1;
  49472. }
  49473. Object.defineProperty(Collider.prototype, "collisionMask", {
  49474. get: function () {
  49475. return this._collisionMask;
  49476. },
  49477. set: function (mask) {
  49478. this._collisionMask = !isNaN(mask) ? mask : -1;
  49479. },
  49480. enumerable: true,
  49481. configurable: true
  49482. });
  49483. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49484. /**
  49485. * Gets the plane normal used to compute the sliding response (in local space)
  49486. */
  49487. get: function () {
  49488. return this._slidePlaneNormal;
  49489. },
  49490. enumerable: true,
  49491. configurable: true
  49492. });
  49493. // Methods
  49494. Collider.prototype._initialize = function (source, dir, e) {
  49495. this._velocity = dir;
  49496. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49497. this._basePoint = source;
  49498. source.multiplyToRef(this._radius, this._basePointWorld);
  49499. dir.multiplyToRef(this._radius, this._velocityWorld);
  49500. this._velocityWorldLength = this._velocityWorld.length();
  49501. this._epsilon = e;
  49502. this.collisionFound = false;
  49503. };
  49504. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49505. pa.subtractToRef(point, this._tempVector);
  49506. pb.subtractToRef(point, this._tempVector2);
  49507. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49508. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49509. if (d < 0)
  49510. return false;
  49511. pc.subtractToRef(point, this._tempVector3);
  49512. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49513. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49514. if (d < 0)
  49515. return false;
  49516. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49517. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49518. return d >= 0;
  49519. };
  49520. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49521. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49522. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49523. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49524. return false;
  49525. }
  49526. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49527. return false;
  49528. return true;
  49529. };
  49530. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49531. var t0;
  49532. var embeddedInPlane = false;
  49533. //defensive programming, actually not needed.
  49534. if (!trianglePlaneArray) {
  49535. trianglePlaneArray = [];
  49536. }
  49537. if (!trianglePlaneArray[faceIndex]) {
  49538. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49539. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49540. }
  49541. var trianglePlane = trianglePlaneArray[faceIndex];
  49542. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49543. return;
  49544. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49545. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49546. if (normalDotVelocity == 0) {
  49547. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49548. return;
  49549. embeddedInPlane = true;
  49550. t0 = 0;
  49551. }
  49552. else {
  49553. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49554. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49555. if (t0 > t1) {
  49556. var temp = t1;
  49557. t1 = t0;
  49558. t0 = temp;
  49559. }
  49560. if (t0 > 1.0 || t1 < 0.0)
  49561. return;
  49562. if (t0 < 0)
  49563. t0 = 0;
  49564. if (t0 > 1.0)
  49565. t0 = 1.0;
  49566. }
  49567. this._collisionPoint.copyFromFloats(0, 0, 0);
  49568. var found = false;
  49569. var t = 1.0;
  49570. if (!embeddedInPlane) {
  49571. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49572. this._velocity.scaleToRef(t0, this._tempVector);
  49573. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49574. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49575. found = true;
  49576. t = t0;
  49577. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49578. }
  49579. }
  49580. if (!found) {
  49581. var velocitySquaredLength = this._velocity.lengthSquared();
  49582. var a = velocitySquaredLength;
  49583. this._basePoint.subtractToRef(p1, this._tempVector);
  49584. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49585. var c = this._tempVector.lengthSquared() - 1.0;
  49586. var lowestRoot = getLowestRoot(a, b, c, t);
  49587. if (lowestRoot.found) {
  49588. t = lowestRoot.root;
  49589. found = true;
  49590. this._collisionPoint.copyFrom(p1);
  49591. }
  49592. this._basePoint.subtractToRef(p2, this._tempVector);
  49593. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49594. c = this._tempVector.lengthSquared() - 1.0;
  49595. lowestRoot = getLowestRoot(a, b, c, t);
  49596. if (lowestRoot.found) {
  49597. t = lowestRoot.root;
  49598. found = true;
  49599. this._collisionPoint.copyFrom(p2);
  49600. }
  49601. this._basePoint.subtractToRef(p3, this._tempVector);
  49602. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49603. c = this._tempVector.lengthSquared() - 1.0;
  49604. lowestRoot = getLowestRoot(a, b, c, t);
  49605. if (lowestRoot.found) {
  49606. t = lowestRoot.root;
  49607. found = true;
  49608. this._collisionPoint.copyFrom(p3);
  49609. }
  49610. p2.subtractToRef(p1, this._edge);
  49611. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49612. var edgeSquaredLength = this._edge.lengthSquared();
  49613. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49614. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49615. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49616. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49617. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49618. lowestRoot = getLowestRoot(a, b, c, t);
  49619. if (lowestRoot.found) {
  49620. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49621. if (f >= 0.0 && f <= 1.0) {
  49622. t = lowestRoot.root;
  49623. found = true;
  49624. this._edge.scaleInPlace(f);
  49625. p1.addToRef(this._edge, this._collisionPoint);
  49626. }
  49627. }
  49628. p3.subtractToRef(p2, this._edge);
  49629. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49630. edgeSquaredLength = this._edge.lengthSquared();
  49631. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49632. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49633. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49634. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49635. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49636. lowestRoot = getLowestRoot(a, b, c, t);
  49637. if (lowestRoot.found) {
  49638. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49639. if (f >= 0.0 && f <= 1.0) {
  49640. t = lowestRoot.root;
  49641. found = true;
  49642. this._edge.scaleInPlace(f);
  49643. p2.addToRef(this._edge, this._collisionPoint);
  49644. }
  49645. }
  49646. p1.subtractToRef(p3, this._edge);
  49647. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49648. edgeSquaredLength = this._edge.lengthSquared();
  49649. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49650. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49651. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49652. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49653. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49654. lowestRoot = getLowestRoot(a, b, c, t);
  49655. if (lowestRoot.found) {
  49656. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49657. if (f >= 0.0 && f <= 1.0) {
  49658. t = lowestRoot.root;
  49659. found = true;
  49660. this._edge.scaleInPlace(f);
  49661. p3.addToRef(this._edge, this._collisionPoint);
  49662. }
  49663. }
  49664. }
  49665. if (found) {
  49666. var distToCollision = t * this._velocity.length();
  49667. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49668. if (!this.intersectionPoint) {
  49669. this.intersectionPoint = this._collisionPoint.clone();
  49670. }
  49671. else {
  49672. this.intersectionPoint.copyFrom(this._collisionPoint);
  49673. }
  49674. this._nearestDistance = distToCollision;
  49675. this.collisionFound = true;
  49676. }
  49677. }
  49678. };
  49679. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49680. for (var i = indexStart; i < indexEnd; i += 3) {
  49681. var p1 = pts[indices[i] - decal];
  49682. var p2 = pts[indices[i + 1] - decal];
  49683. var p3 = pts[indices[i + 2] - decal];
  49684. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49685. }
  49686. };
  49687. Collider.prototype._getResponse = function (pos, vel) {
  49688. pos.addToRef(vel, this._destinationPoint);
  49689. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49690. this._basePoint.addToRef(vel, pos);
  49691. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49692. this._slidePlaneNormal.normalize();
  49693. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49694. pos.addInPlace(this._displacementVector);
  49695. this.intersectionPoint.addInPlace(this._displacementVector);
  49696. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49697. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49698. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49699. };
  49700. return Collider;
  49701. }());
  49702. BABYLON.Collider = Collider;
  49703. })(BABYLON || (BABYLON = {}));
  49704. //# sourceMappingURL=babylon.collider.js.map
  49705. var BABYLON;
  49706. (function (BABYLON) {
  49707. //WebWorker code will be inserted to this variable.
  49708. BABYLON.CollisionWorker = "";
  49709. var WorkerTaskType;
  49710. (function (WorkerTaskType) {
  49711. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49712. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49713. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49714. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49715. var WorkerReplyType;
  49716. (function (WorkerReplyType) {
  49717. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49718. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49719. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49720. var CollisionCoordinatorWorker = /** @class */ (function () {
  49721. function CollisionCoordinatorWorker() {
  49722. var _this = this;
  49723. this._scaledPosition = BABYLON.Vector3.Zero();
  49724. this._scaledVelocity = BABYLON.Vector3.Zero();
  49725. this.onMeshUpdated = function (transformNode) {
  49726. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49727. };
  49728. this.onGeometryUpdated = function (geometry) {
  49729. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49730. };
  49731. this._afterRender = function () {
  49732. if (!_this._init)
  49733. return;
  49734. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49735. return;
  49736. }
  49737. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49738. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49739. if (_this._runningUpdated > 4) {
  49740. return;
  49741. }
  49742. ++_this._runningUpdated;
  49743. var payload = {
  49744. updatedMeshes: _this._addUpdateMeshesList,
  49745. updatedGeometries: _this._addUpdateGeometriesList,
  49746. removedGeometries: _this._toRemoveGeometryArray,
  49747. removedMeshes: _this._toRemoveMeshesArray
  49748. };
  49749. var message = {
  49750. payload: payload,
  49751. taskType: WorkerTaskType.UPDATE
  49752. };
  49753. var serializable = [];
  49754. for (var id in payload.updatedGeometries) {
  49755. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49756. //prepare transferables
  49757. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49758. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49759. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49760. }
  49761. }
  49762. _this._worker.postMessage(message, serializable);
  49763. _this._addUpdateMeshesList = {};
  49764. _this._addUpdateGeometriesList = {};
  49765. _this._toRemoveGeometryArray = [];
  49766. _this._toRemoveMeshesArray = [];
  49767. };
  49768. this._onMessageFromWorker = function (e) {
  49769. var returnData = e.data;
  49770. if (returnData.error != WorkerReplyType.SUCCESS) {
  49771. //TODO what errors can be returned from the worker?
  49772. BABYLON.Tools.Warn("error returned from worker!");
  49773. return;
  49774. }
  49775. switch (returnData.taskType) {
  49776. case WorkerTaskType.INIT:
  49777. _this._init = true;
  49778. //Update the worked with ALL of the scene's current state
  49779. _this._scene.meshes.forEach(function (mesh) {
  49780. _this.onMeshAdded(mesh);
  49781. });
  49782. _this._scene.getGeometries().forEach(function (geometry) {
  49783. _this.onGeometryAdded(geometry);
  49784. });
  49785. break;
  49786. case WorkerTaskType.UPDATE:
  49787. _this._runningUpdated--;
  49788. break;
  49789. case WorkerTaskType.COLLIDE:
  49790. var returnPayload = returnData.payload;
  49791. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49792. return;
  49793. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49794. if (callback) {
  49795. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49796. if (mesh) {
  49797. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49798. }
  49799. }
  49800. //cleanup
  49801. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49802. break;
  49803. }
  49804. };
  49805. this._collisionsCallbackArray = [];
  49806. this._init = false;
  49807. this._runningUpdated = 0;
  49808. this._addUpdateMeshesList = {};
  49809. this._addUpdateGeometriesList = {};
  49810. this._toRemoveGeometryArray = [];
  49811. this._toRemoveMeshesArray = [];
  49812. }
  49813. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49814. if (!this._init)
  49815. return;
  49816. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49817. return;
  49818. position.divideToRef(collider._radius, this._scaledPosition);
  49819. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49820. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49821. var payload = {
  49822. collider: {
  49823. position: this._scaledPosition.asArray(),
  49824. velocity: this._scaledVelocity.asArray(),
  49825. radius: collider._radius.asArray()
  49826. },
  49827. collisionId: collisionIndex,
  49828. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49829. maximumRetry: maximumRetry
  49830. };
  49831. var message = {
  49832. payload: payload,
  49833. taskType: WorkerTaskType.COLLIDE
  49834. };
  49835. this._worker.postMessage(message);
  49836. };
  49837. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49838. this._scene = scene;
  49839. this._scene.registerAfterRender(this._afterRender);
  49840. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49841. this._worker = new Worker(workerUrl);
  49842. this._worker.onmessage = this._onMessageFromWorker;
  49843. var message = {
  49844. payload: {},
  49845. taskType: WorkerTaskType.INIT
  49846. };
  49847. this._worker.postMessage(message);
  49848. };
  49849. CollisionCoordinatorWorker.prototype.destroy = function () {
  49850. this._scene.unregisterAfterRender(this._afterRender);
  49851. this._worker.terminate();
  49852. };
  49853. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49854. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49855. this.onMeshUpdated(mesh);
  49856. };
  49857. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49858. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49859. };
  49860. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49861. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49862. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49863. this.onGeometryUpdated(geometry);
  49864. };
  49865. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49866. this._toRemoveGeometryArray.push(geometry.id);
  49867. };
  49868. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49869. var submeshes = [];
  49870. if (mesh.subMeshes) {
  49871. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49872. var boundingInfo = sm.getBoundingInfo();
  49873. return {
  49874. position: idx,
  49875. verticesStart: sm.verticesStart,
  49876. verticesCount: sm.verticesCount,
  49877. indexStart: sm.indexStart,
  49878. indexCount: sm.indexCount,
  49879. hasMaterial: !!sm.getMaterial(),
  49880. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49881. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49882. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49883. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49884. };
  49885. });
  49886. }
  49887. var geometryId = null;
  49888. if (mesh instanceof BABYLON.Mesh) {
  49889. var geometry = mesh.geometry;
  49890. geometryId = geometry ? geometry.id : null;
  49891. }
  49892. else if (mesh instanceof BABYLON.InstancedMesh) {
  49893. var geometry = mesh.sourceMesh.geometry;
  49894. geometryId = geometry ? geometry.id : null;
  49895. }
  49896. var boundingInfo = mesh.getBoundingInfo();
  49897. return {
  49898. uniqueId: mesh.uniqueId,
  49899. id: mesh.id,
  49900. name: mesh.name,
  49901. geometryId: geometryId,
  49902. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49903. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49904. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49905. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49906. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49907. subMeshes: submeshes,
  49908. checkCollisions: mesh.checkCollisions
  49909. };
  49910. };
  49911. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49912. return {
  49913. id: geometry.id,
  49914. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49915. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49916. indices: new Uint32Array(geometry.getIndices() || []),
  49917. };
  49918. };
  49919. return CollisionCoordinatorWorker;
  49920. }());
  49921. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49922. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49923. function CollisionCoordinatorLegacy() {
  49924. this._scaledPosition = BABYLON.Vector3.Zero();
  49925. this._scaledVelocity = BABYLON.Vector3.Zero();
  49926. this._finalPosition = BABYLON.Vector3.Zero();
  49927. }
  49928. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49929. position.divideToRef(collider._radius, this._scaledPosition);
  49930. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49931. collider.collidedMesh = null;
  49932. collider._retry = 0;
  49933. collider._initialVelocity = this._scaledVelocity;
  49934. collider._initialPosition = this._scaledPosition;
  49935. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49936. this._finalPosition.multiplyInPlace(collider._radius);
  49937. //run the callback
  49938. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49939. };
  49940. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49941. this._scene = scene;
  49942. };
  49943. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49944. //Legacy need no destruction method.
  49945. };
  49946. //No update in legacy mode
  49947. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49948. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49949. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49950. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49951. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49952. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49953. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49954. if (excludedMesh === void 0) { excludedMesh = null; }
  49955. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49956. if (collider._retry >= maximumRetry) {
  49957. finalPosition.copyFrom(position);
  49958. return;
  49959. }
  49960. // Check if this is a mesh else camera or -1
  49961. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49962. collider._initialize(position, velocity, closeDistance);
  49963. // Check all meshes
  49964. for (var index = 0; index < this._scene.meshes.length; index++) {
  49965. var mesh = this._scene.meshes[index];
  49966. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49967. mesh._checkCollision(collider);
  49968. }
  49969. }
  49970. if (!collider.collisionFound) {
  49971. position.addToRef(velocity, finalPosition);
  49972. return;
  49973. }
  49974. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49975. collider._getResponse(position, velocity);
  49976. }
  49977. if (velocity.length() <= closeDistance) {
  49978. finalPosition.copyFrom(position);
  49979. return;
  49980. }
  49981. collider._retry++;
  49982. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49983. };
  49984. return CollisionCoordinatorLegacy;
  49985. }());
  49986. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49987. })(BABYLON || (BABYLON = {}));
  49988. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49989. var BABYLON;
  49990. (function (BABYLON) {
  49991. /**
  49992. * A particle represents one of the element emitted by a particle system.
  49993. * This is mainly define by its coordinates, direction, velocity and age.
  49994. */
  49995. var Particle = /** @class */ (function () {
  49996. /**
  49997. * Creates a new instance of @see Particle
  49998. * @param particleSystem the particle system the particle belongs to
  49999. */
  50000. function Particle(particleSystem) {
  50001. this.particleSystem = particleSystem;
  50002. /**
  50003. * The world position of the particle in the scene.
  50004. */
  50005. this.position = BABYLON.Vector3.Zero();
  50006. /**
  50007. * The world direction of the particle in the scene.
  50008. */
  50009. this.direction = BABYLON.Vector3.Zero();
  50010. /**
  50011. * The color of the particle.
  50012. */
  50013. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50014. /**
  50015. * The color change of the particle per step.
  50016. */
  50017. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50018. /**
  50019. * Defines how long will the life of the particle be.
  50020. */
  50021. this.lifeTime = 1.0;
  50022. /**
  50023. * The current age of the particle.
  50024. */
  50025. this.age = 0;
  50026. /**
  50027. * The current size of the particle.
  50028. */
  50029. this.size = 0;
  50030. /**
  50031. * The current angle of the particle.
  50032. */
  50033. this.angle = 0;
  50034. /**
  50035. * Defines how fast is the angle changing.
  50036. */
  50037. this.angularSpeed = 0;
  50038. /**
  50039. * Defines the cell index used by the particle to be rendered from a sprite.
  50040. */
  50041. this.cellIndex = 0;
  50042. this._currentFrameCounter = 0;
  50043. if (!this.particleSystem.isAnimationSheetEnabled) {
  50044. return;
  50045. }
  50046. this.cellIndex = this.particleSystem.startSpriteCellID;
  50047. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50048. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50049. }
  50050. else {
  50051. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50052. }
  50053. }
  50054. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50055. // (ageOffset / scaledUpdateSpeed) / available cells
  50056. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50057. this._currentFrameCounter += scaledUpdateSpeed;
  50058. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50059. this._currentFrameCounter = 0;
  50060. this.cellIndex++;
  50061. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50062. this.cellIndex = this.particleSystem.endSpriteCellID;
  50063. }
  50064. }
  50065. };
  50066. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50067. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50068. this.cellIndex++;
  50069. this._currentFrameCounter = 0;
  50070. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50071. if (this.particleSystem.spriteCellLoop) {
  50072. this.cellIndex = this.particleSystem.startSpriteCellID;
  50073. }
  50074. else {
  50075. this.cellIndex = this.particleSystem.endSpriteCellID;
  50076. }
  50077. }
  50078. }
  50079. else {
  50080. this._currentFrameCounter++;
  50081. }
  50082. };
  50083. /**
  50084. * Copy the properties of particle to another one.
  50085. * @param other the particle to copy the information to.
  50086. */
  50087. Particle.prototype.copyTo = function (other) {
  50088. other.position.copyFrom(this.position);
  50089. other.direction.copyFrom(this.direction);
  50090. other.color.copyFrom(this.color);
  50091. other.colorStep.copyFrom(this.colorStep);
  50092. other.lifeTime = this.lifeTime;
  50093. other.age = this.age;
  50094. other.size = this.size;
  50095. other.angle = this.angle;
  50096. other.angularSpeed = this.angularSpeed;
  50097. other.particleSystem = this.particleSystem;
  50098. other.cellIndex = this.cellIndex;
  50099. };
  50100. return Particle;
  50101. }());
  50102. BABYLON.Particle = Particle;
  50103. })(BABYLON || (BABYLON = {}));
  50104. //# sourceMappingURL=babylon.particle.js.map
  50105. var BABYLON;
  50106. (function (BABYLON) {
  50107. /**
  50108. * This represents a particle system in Babylon.
  50109. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50110. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50111. * @example https://doc.babylonjs.com/babylon101/particles
  50112. */
  50113. var ParticleSystem = /** @class */ (function () {
  50114. /**
  50115. * Instantiates a particle system.
  50116. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  50117. * @param name The name of the particle system
  50118. * @param capacity The max number of particles alive at the same time
  50119. * @param scene The scene the particle system belongs to
  50120. * @param customEffect a custom effect used to change the way particles are rendered by default
  50121. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50122. * @param epsilon Offset used to render the particles
  50123. */
  50124. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50125. if (customEffect === void 0) { customEffect = null; }
  50126. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50127. if (epsilon === void 0) { epsilon = 0.01; }
  50128. var _this = this;
  50129. /**
  50130. * List of animations used by the particle system.
  50131. */
  50132. this.animations = [];
  50133. /**
  50134. * The rendering group used by the Particle system to chose when to render.
  50135. */
  50136. this.renderingGroupId = 0;
  50137. /**
  50138. * The emitter represents the Mesh or position we are attaching the particle system to.
  50139. */
  50140. this.emitter = null;
  50141. /**
  50142. * The maximum number of particles to emit per frame
  50143. */
  50144. this.emitRate = 10;
  50145. /**
  50146. * If you want to launch only a few particles at once, that can be done, as well.
  50147. */
  50148. this.manualEmitCount = -1;
  50149. /**
  50150. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50151. */
  50152. this.updateSpeed = 0.01;
  50153. /**
  50154. * The amount of time the particle system is running (depends of the overall speed above).
  50155. */
  50156. this.targetStopDuration = 0;
  50157. /**
  50158. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50159. */
  50160. this.disposeOnStop = false;
  50161. /**
  50162. * Minimum power of emitting particles.
  50163. */
  50164. this.minEmitPower = 1;
  50165. /**
  50166. * Maximum power of emitting particles.
  50167. */
  50168. this.maxEmitPower = 1;
  50169. /**
  50170. * Minimum life time of emitting particles.
  50171. */
  50172. this.minLifeTime = 1;
  50173. /**
  50174. * Maximum life time of emitting particles.
  50175. */
  50176. this.maxLifeTime = 1;
  50177. /**
  50178. * Minimum Size of emitting particles.
  50179. */
  50180. this.minSize = 1;
  50181. /**
  50182. * Maximum Size of emitting particles.
  50183. */
  50184. this.maxSize = 1;
  50185. /**
  50186. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50187. */
  50188. this.minAngularSpeed = 0;
  50189. /**
  50190. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50191. */
  50192. this.maxAngularSpeed = 0;
  50193. /**
  50194. * The layer mask we are rendering the particles through.
  50195. */
  50196. this.layerMask = 0x0FFFFFFF;
  50197. /**
  50198. * This can help using your own shader to render the particle system.
  50199. * The according effect will be created
  50200. */
  50201. this.customShader = null;
  50202. /**
  50203. * By default particle system starts as soon as they are created. This prevents the
  50204. * automatic start to happen and let you decide when to start emitting particles.
  50205. */
  50206. this.preventAutoStart = false;
  50207. /**
  50208. * Callback triggered when the particle animation is ending.
  50209. */
  50210. this.onAnimationEnd = null;
  50211. /**
  50212. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50213. */
  50214. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50215. /**
  50216. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50217. * to override the particles.
  50218. */
  50219. this.forceDepthWrite = false;
  50220. /**
  50221. * You can use gravity if you want to give an orientation to your particles.
  50222. */
  50223. this.gravity = BABYLON.Vector3.Zero();
  50224. /**
  50225. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50226. */
  50227. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50228. /**
  50229. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50230. */
  50231. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50232. /**
  50233. * Color the particle will have at the end of its lifetime.
  50234. */
  50235. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50236. /**
  50237. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50238. */
  50239. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50240. /**
  50241. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50242. */
  50243. this.spriteCellLoop = true;
  50244. /**
  50245. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50246. */
  50247. this.spriteCellChangeSpeed = 0;
  50248. /**
  50249. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50250. */
  50251. this.startSpriteCellID = 0;
  50252. /**
  50253. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50254. */
  50255. this.endSpriteCellID = 0;
  50256. /**
  50257. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50258. */
  50259. this.spriteCellWidth = 0;
  50260. /**
  50261. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50262. */
  50263. this.spriteCellHeight = 0;
  50264. /**
  50265. * An event triggered when the system is disposed.
  50266. */
  50267. this.onDisposeObservable = new BABYLON.Observable();
  50268. this._particles = new Array();
  50269. this._stockParticles = new Array();
  50270. this._newPartsExcess = 0;
  50271. this._vertexBuffers = {};
  50272. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50273. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50274. this._scaledDirection = BABYLON.Vector3.Zero();
  50275. this._scaledGravity = BABYLON.Vector3.Zero();
  50276. this._currentRenderId = -1;
  50277. this._started = false;
  50278. this._stopped = false;
  50279. this._actualFrame = 0;
  50280. this._vertexBufferSize = 11;
  50281. this._appendParticleVertexes = null;
  50282. this.id = name;
  50283. this.name = name;
  50284. this._capacity = capacity;
  50285. this._epsilon = epsilon;
  50286. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50287. if (isAnimationSheetEnabled) {
  50288. this._vertexBufferSize = 12;
  50289. }
  50290. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50291. this._customEffect = customEffect;
  50292. scene.particleSystems.push(this);
  50293. this._createIndexBuffer();
  50294. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50295. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50296. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50297. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50298. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50299. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50300. if (this._isAnimationSheetEnabled) {
  50301. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50302. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50303. }
  50304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50305. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50306. this._vertexBuffers["options"] = options;
  50307. // Default emitter type
  50308. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50309. this.updateFunction = function (particles) {
  50310. for (var index = 0; index < particles.length; index++) {
  50311. var particle = particles[index];
  50312. particle.age += _this._scaledUpdateSpeed;
  50313. if (particle.age >= particle.lifeTime) {
  50314. _this.recycleParticle(particle);
  50315. index--;
  50316. continue;
  50317. }
  50318. else {
  50319. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50320. particle.color.addInPlace(_this._scaledColorStep);
  50321. if (particle.color.a < 0)
  50322. particle.color.a = 0;
  50323. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50324. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50325. particle.position.addInPlace(_this._scaledDirection);
  50326. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50327. particle.direction.addInPlace(_this._scaledGravity);
  50328. if (_this._isAnimationSheetEnabled) {
  50329. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50330. }
  50331. }
  50332. }
  50333. };
  50334. }
  50335. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50336. /**
  50337. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50338. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50339. */
  50340. get: function () {
  50341. if (this.particleEmitterType.direction1) {
  50342. return this.particleEmitterType.direction1;
  50343. }
  50344. return BABYLON.Vector3.Zero();
  50345. },
  50346. set: function (value) {
  50347. if (this.particleEmitterType.direction1) {
  50348. this.particleEmitterType.direction1 = value;
  50349. }
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50355. /**
  50356. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50357. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50358. */
  50359. get: function () {
  50360. if (this.particleEmitterType.direction2) {
  50361. return this.particleEmitterType.direction2;
  50362. }
  50363. return BABYLON.Vector3.Zero();
  50364. },
  50365. set: function (value) {
  50366. if (this.particleEmitterType.direction2) {
  50367. this.particleEmitterType.direction2 = value;
  50368. }
  50369. },
  50370. enumerable: true,
  50371. configurable: true
  50372. });
  50373. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50374. /**
  50375. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  50376. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50377. */
  50378. get: function () {
  50379. if (this.particleEmitterType.minEmitBox) {
  50380. return this.particleEmitterType.minEmitBox;
  50381. }
  50382. return BABYLON.Vector3.Zero();
  50383. },
  50384. set: function (value) {
  50385. if (this.particleEmitterType.minEmitBox) {
  50386. this.particleEmitterType.minEmitBox = value;
  50387. }
  50388. },
  50389. enumerable: true,
  50390. configurable: true
  50391. });
  50392. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50393. /**
  50394. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  50395. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50396. */
  50397. get: function () {
  50398. if (this.particleEmitterType.maxEmitBox) {
  50399. return this.particleEmitterType.maxEmitBox;
  50400. }
  50401. return BABYLON.Vector3.Zero();
  50402. },
  50403. set: function (value) {
  50404. if (this.particleEmitterType.maxEmitBox) {
  50405. this.particleEmitterType.maxEmitBox = value;
  50406. }
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50412. /**
  50413. * Sets a callback that will be triggered when the system is disposed.
  50414. */
  50415. set: function (callback) {
  50416. if (this._onDisposeObserver) {
  50417. this.onDisposeObservable.remove(this._onDisposeObserver);
  50418. }
  50419. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50425. /**
  50426. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50427. */
  50428. get: function () {
  50429. return this._isAnimationSheetEnabled;
  50430. },
  50431. enumerable: true,
  50432. configurable: true
  50433. });
  50434. ParticleSystem.prototype._createIndexBuffer = function () {
  50435. var indices = [];
  50436. var index = 0;
  50437. for (var count = 0; count < this._capacity; count++) {
  50438. indices.push(index);
  50439. indices.push(index + 1);
  50440. indices.push(index + 2);
  50441. indices.push(index);
  50442. indices.push(index + 2);
  50443. indices.push(index + 3);
  50444. index += 4;
  50445. }
  50446. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50447. };
  50448. /**
  50449. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50450. * Its lifetime will start back at 0.
  50451. * @param particle The particle to recycle
  50452. */
  50453. ParticleSystem.prototype.recycleParticle = function (particle) {
  50454. var lastParticle = this._particles.pop();
  50455. if (lastParticle !== particle) {
  50456. lastParticle.copyTo(particle);
  50457. this._stockParticles.push(lastParticle);
  50458. }
  50459. };
  50460. /**
  50461. * Gets the maximum number of particles active at the same time.
  50462. * @returns The max number of active particles.
  50463. */
  50464. ParticleSystem.prototype.getCapacity = function () {
  50465. return this._capacity;
  50466. };
  50467. /**
  50468. * Gets Wether there are still active particles in the system.
  50469. * @returns True if it is alive, otherwise false.
  50470. */
  50471. ParticleSystem.prototype.isAlive = function () {
  50472. return this._alive;
  50473. };
  50474. /**
  50475. * Gets Wether the system has been started.
  50476. * @returns True if it has been started, otherwise false.
  50477. */
  50478. ParticleSystem.prototype.isStarted = function () {
  50479. return this._started;
  50480. };
  50481. /**
  50482. * Starts the particle system and begins to emit.
  50483. */
  50484. ParticleSystem.prototype.start = function () {
  50485. this._started = true;
  50486. this._stopped = false;
  50487. this._actualFrame = 0;
  50488. };
  50489. /**
  50490. * Stops the particle system.
  50491. */
  50492. ParticleSystem.prototype.stop = function () {
  50493. this._stopped = true;
  50494. };
  50495. /**
  50496. * Remove all active particles
  50497. */
  50498. ParticleSystem.prototype.reset = function () {
  50499. this._stockParticles = [];
  50500. this._particles = [];
  50501. };
  50502. /**
  50503. * @ignore (for internal use only)
  50504. */
  50505. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50506. var offset = index * this._vertexBufferSize;
  50507. this._vertexData[offset] = particle.position.x;
  50508. this._vertexData[offset + 1] = particle.position.y;
  50509. this._vertexData[offset + 2] = particle.position.z;
  50510. this._vertexData[offset + 3] = particle.color.r;
  50511. this._vertexData[offset + 4] = particle.color.g;
  50512. this._vertexData[offset + 5] = particle.color.b;
  50513. this._vertexData[offset + 6] = particle.color.a;
  50514. this._vertexData[offset + 7] = particle.angle;
  50515. this._vertexData[offset + 8] = particle.size;
  50516. this._vertexData[offset + 9] = offsetX;
  50517. this._vertexData[offset + 10] = offsetY;
  50518. };
  50519. /**
  50520. * @ignore (for internal use only)
  50521. */
  50522. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50523. if (offsetX === 0)
  50524. offsetX = this._epsilon;
  50525. else if (offsetX === 1)
  50526. offsetX = 1 - this._epsilon;
  50527. if (offsetY === 0)
  50528. offsetY = this._epsilon;
  50529. else if (offsetY === 1)
  50530. offsetY = 1 - this._epsilon;
  50531. var offset = index * this._vertexBufferSize;
  50532. this._vertexData[offset] = particle.position.x;
  50533. this._vertexData[offset + 1] = particle.position.y;
  50534. this._vertexData[offset + 2] = particle.position.z;
  50535. this._vertexData[offset + 3] = particle.color.r;
  50536. this._vertexData[offset + 4] = particle.color.g;
  50537. this._vertexData[offset + 5] = particle.color.b;
  50538. this._vertexData[offset + 6] = particle.color.a;
  50539. this._vertexData[offset + 7] = particle.angle;
  50540. this._vertexData[offset + 8] = particle.size;
  50541. this._vertexData[offset + 9] = offsetX;
  50542. this._vertexData[offset + 10] = offsetY;
  50543. this._vertexData[offset + 11] = particle.cellIndex;
  50544. };
  50545. ParticleSystem.prototype._update = function (newParticles) {
  50546. // Update current
  50547. this._alive = this._particles.length > 0;
  50548. this.updateFunction(this._particles);
  50549. // Add new ones
  50550. var worldMatrix;
  50551. if (this.emitter.position) {
  50552. var emitterMesh = this.emitter;
  50553. worldMatrix = emitterMesh.getWorldMatrix();
  50554. }
  50555. else {
  50556. var emitterPosition = this.emitter;
  50557. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50558. }
  50559. var particle;
  50560. for (var index = 0; index < newParticles; index++) {
  50561. if (this._particles.length === this._capacity) {
  50562. break;
  50563. }
  50564. if (this._stockParticles.length !== 0) {
  50565. particle = this._stockParticles.pop();
  50566. particle.age = 0;
  50567. particle.cellIndex = this.startSpriteCellID;
  50568. }
  50569. else {
  50570. particle = new BABYLON.Particle(this);
  50571. }
  50572. this._particles.push(particle);
  50573. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50574. if (this.startPositionFunction) {
  50575. this.startPositionFunction(worldMatrix, particle.position, particle);
  50576. }
  50577. else {
  50578. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50579. }
  50580. if (this.startDirectionFunction) {
  50581. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50582. }
  50583. else {
  50584. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50585. }
  50586. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50587. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50588. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50589. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50590. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50591. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50592. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50593. }
  50594. };
  50595. ParticleSystem.prototype._getEffect = function () {
  50596. if (this._customEffect) {
  50597. return this._customEffect;
  50598. }
  50599. ;
  50600. var defines = [];
  50601. if (this._scene.clipPlane) {
  50602. defines.push("#define CLIPPLANE");
  50603. }
  50604. if (this._isAnimationSheetEnabled) {
  50605. defines.push("#define ANIMATESHEET");
  50606. }
  50607. // Effect
  50608. var join = defines.join("\n");
  50609. if (this._cachedDefines !== join) {
  50610. this._cachedDefines = join;
  50611. var attributesNamesOrOptions;
  50612. var effectCreationOption;
  50613. if (this._isAnimationSheetEnabled) {
  50614. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50615. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50616. }
  50617. else {
  50618. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50619. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50620. }
  50621. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50622. }
  50623. return this._effect;
  50624. };
  50625. /**
  50626. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50627. */
  50628. ParticleSystem.prototype.animate = function () {
  50629. if (!this._started)
  50630. return;
  50631. var effect = this._getEffect();
  50632. // Check
  50633. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50634. return;
  50635. if (this._currentRenderId === this._scene.getRenderId()) {
  50636. return;
  50637. }
  50638. this._currentRenderId = this._scene.getRenderId();
  50639. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50640. // determine the number of particles we need to create
  50641. var newParticles;
  50642. if (this.manualEmitCount > -1) {
  50643. newParticles = this.manualEmitCount;
  50644. this._newPartsExcess = 0;
  50645. this.manualEmitCount = 0;
  50646. }
  50647. else {
  50648. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50649. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50650. }
  50651. if (this._newPartsExcess > 1.0) {
  50652. newParticles += this._newPartsExcess >> 0;
  50653. this._newPartsExcess -= this._newPartsExcess >> 0;
  50654. }
  50655. this._alive = false;
  50656. if (!this._stopped) {
  50657. this._actualFrame += this._scaledUpdateSpeed;
  50658. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50659. this.stop();
  50660. }
  50661. else {
  50662. newParticles = 0;
  50663. }
  50664. this._update(newParticles);
  50665. // Stopped?
  50666. if (this._stopped) {
  50667. if (!this._alive) {
  50668. this._started = false;
  50669. if (this.onAnimationEnd) {
  50670. this.onAnimationEnd();
  50671. }
  50672. if (this.disposeOnStop) {
  50673. this._scene._toBeDisposed.push(this);
  50674. }
  50675. }
  50676. }
  50677. // Animation sheet
  50678. if (this._isAnimationSheetEnabled) {
  50679. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50680. }
  50681. else {
  50682. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50683. }
  50684. // Update VBO
  50685. var offset = 0;
  50686. for (var index = 0; index < this._particles.length; index++) {
  50687. var particle = this._particles[index];
  50688. this._appendParticleVertexes(offset, particle);
  50689. offset += 4;
  50690. }
  50691. if (this._vertexBuffer) {
  50692. this._vertexBuffer.update(this._vertexData);
  50693. }
  50694. };
  50695. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50696. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50697. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50698. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50699. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50700. };
  50701. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50702. this._appendParticleVertex(offset++, particle, 0, 0);
  50703. this._appendParticleVertex(offset++, particle, 1, 0);
  50704. this._appendParticleVertex(offset++, particle, 1, 1);
  50705. this._appendParticleVertex(offset++, particle, 0, 1);
  50706. };
  50707. /**
  50708. * Rebuilds the particle system.
  50709. */
  50710. ParticleSystem.prototype.rebuild = function () {
  50711. this._createIndexBuffer();
  50712. if (this._vertexBuffer) {
  50713. this._vertexBuffer._rebuild();
  50714. }
  50715. };
  50716. /**
  50717. * Renders the particle system in its current state.
  50718. * @returns the current number of particles
  50719. */
  50720. ParticleSystem.prototype.render = function () {
  50721. var effect = this._getEffect();
  50722. // Check
  50723. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  50724. return 0;
  50725. }
  50726. var engine = this._scene.getEngine();
  50727. // Render
  50728. engine.enableEffect(effect);
  50729. engine.setState(false);
  50730. var viewMatrix = this._scene.getViewMatrix();
  50731. effect.setTexture("diffuseSampler", this.particleTexture);
  50732. effect.setMatrix("view", viewMatrix);
  50733. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50734. if (this._isAnimationSheetEnabled) {
  50735. var baseSize = this.particleTexture.getBaseSize();
  50736. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50737. }
  50738. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50739. if (this._scene.clipPlane) {
  50740. var clipPlane = this._scene.clipPlane;
  50741. var invView = viewMatrix.clone();
  50742. invView.invert();
  50743. effect.setMatrix("invView", invView);
  50744. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50745. }
  50746. // VBOs
  50747. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50748. // Draw order
  50749. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50750. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50751. }
  50752. else {
  50753. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50754. }
  50755. if (this.forceDepthWrite) {
  50756. engine.setDepthWrite(true);
  50757. }
  50758. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50759. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50760. return this._particles.length;
  50761. };
  50762. /**
  50763. * Disposes the particle system and free the associated resources.
  50764. */
  50765. ParticleSystem.prototype.dispose = function () {
  50766. if (this._vertexBuffer) {
  50767. this._vertexBuffer.dispose();
  50768. this._vertexBuffer = null;
  50769. }
  50770. if (this._indexBuffer) {
  50771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50772. this._indexBuffer = null;
  50773. }
  50774. if (this.particleTexture) {
  50775. this.particleTexture.dispose();
  50776. this.particleTexture = null;
  50777. }
  50778. // Remove from scene
  50779. var index = this._scene.particleSystems.indexOf(this);
  50780. if (index > -1) {
  50781. this._scene.particleSystems.splice(index, 1);
  50782. }
  50783. // Callback
  50784. this.onDisposeObservable.notifyObservers(this);
  50785. this.onDisposeObservable.clear();
  50786. };
  50787. /**
  50788. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50789. * @param radius The radius of the sphere to emit from
  50790. * @returns the emitter
  50791. */
  50792. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50793. if (radius === void 0) { radius = 1; }
  50794. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50795. this.particleEmitterType = particleEmitter;
  50796. return particleEmitter;
  50797. };
  50798. /**
  50799. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50800. * @param radius The radius of the sphere to emit from
  50801. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50802. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50803. * @returns the emitter
  50804. */
  50805. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50806. if (radius === void 0) { radius = 1; }
  50807. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50808. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50809. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50810. this.particleEmitterType = particleEmitter;
  50811. return particleEmitter;
  50812. };
  50813. /**
  50814. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50815. * @param radius The radius of the cone to emit from
  50816. * @param angle The base angle of the cone
  50817. * @returns the emitter
  50818. */
  50819. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50820. if (radius === void 0) { radius = 1; }
  50821. if (angle === void 0) { angle = Math.PI / 4; }
  50822. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50823. this.particleEmitterType = particleEmitter;
  50824. return particleEmitter;
  50825. };
  50826. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  50827. /**
  50828. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50829. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50830. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50831. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50832. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50833. * @returns the emitter
  50834. */
  50835. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50836. var particleEmitter = new BABYLON.BoxParticleEmitter();
  50837. this.direction1 = direction1;
  50838. this.direction2 = direction2;
  50839. this.minEmitBox = minEmitBox;
  50840. this.maxEmitBox = maxEmitBox;
  50841. this.particleEmitterType = particleEmitter;
  50842. return particleEmitter;
  50843. };
  50844. /**
  50845. * Clones the particle system.
  50846. * @param name The name of the cloned object
  50847. * @param newEmitter The new emitter to use
  50848. * @returns the cloned particle system
  50849. */
  50850. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50851. var custom = null;
  50852. var program = null;
  50853. if (this.customShader != null) {
  50854. program = this.customShader;
  50855. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50856. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50857. }
  50858. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50859. result.customShader = program;
  50860. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50861. if (newEmitter === undefined) {
  50862. newEmitter = this.emitter;
  50863. }
  50864. result.emitter = newEmitter;
  50865. if (this.particleTexture) {
  50866. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50867. }
  50868. if (!this.preventAutoStart) {
  50869. result.start();
  50870. }
  50871. return result;
  50872. };
  50873. /**
  50874. * Serializes the particle system to a JSON object.
  50875. * @returns the JSON object
  50876. */
  50877. ParticleSystem.prototype.serialize = function () {
  50878. var serializationObject = {};
  50879. serializationObject.name = this.name;
  50880. serializationObject.id = this.id;
  50881. // Emitter
  50882. if (this.emitter.position) {
  50883. var emitterMesh = this.emitter;
  50884. serializationObject.emitterId = emitterMesh.id;
  50885. }
  50886. else {
  50887. var emitterPosition = this.emitter;
  50888. serializationObject.emitter = emitterPosition.asArray();
  50889. }
  50890. serializationObject.capacity = this.getCapacity();
  50891. if (this.particleTexture) {
  50892. serializationObject.textureName = this.particleTexture.name;
  50893. }
  50894. // Animations
  50895. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50896. // Particle system
  50897. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50898. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50899. serializationObject.minSize = this.minSize;
  50900. serializationObject.maxSize = this.maxSize;
  50901. serializationObject.minEmitPower = this.minEmitPower;
  50902. serializationObject.maxEmitPower = this.maxEmitPower;
  50903. serializationObject.minLifeTime = this.minLifeTime;
  50904. serializationObject.maxLifeTime = this.maxLifeTime;
  50905. serializationObject.emitRate = this.emitRate;
  50906. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50907. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50908. serializationObject.gravity = this.gravity.asArray();
  50909. serializationObject.direction1 = this.direction1.asArray();
  50910. serializationObject.direction2 = this.direction2.asArray();
  50911. serializationObject.color1 = this.color1.asArray();
  50912. serializationObject.color2 = this.color2.asArray();
  50913. serializationObject.colorDead = this.colorDead.asArray();
  50914. serializationObject.updateSpeed = this.updateSpeed;
  50915. serializationObject.targetStopDuration = this.targetStopDuration;
  50916. serializationObject.textureMask = this.textureMask.asArray();
  50917. serializationObject.blendMode = this.blendMode;
  50918. serializationObject.customShader = this.customShader;
  50919. serializationObject.preventAutoStart = this.preventAutoStart;
  50920. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50921. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50922. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50923. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50924. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50925. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50926. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50927. return serializationObject;
  50928. };
  50929. /**
  50930. * Parses a JSON object to create a particle system.
  50931. * @param parsedParticleSystem The JSON object to parse
  50932. * @param scene The scene to create the particle system in
  50933. * @param rootUrl The root url to use to load external dependencies like texture
  50934. * @returns the Parsed particle system
  50935. */
  50936. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50937. var name = parsedParticleSystem.name;
  50938. var custom = null;
  50939. var program = null;
  50940. if (parsedParticleSystem.customShader) {
  50941. program = parsedParticleSystem.customShader;
  50942. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50943. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50944. }
  50945. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50946. particleSystem.customShader = program;
  50947. if (parsedParticleSystem.id) {
  50948. particleSystem.id = parsedParticleSystem.id;
  50949. }
  50950. // Auto start
  50951. if (parsedParticleSystem.preventAutoStart) {
  50952. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50953. }
  50954. // Texture
  50955. if (parsedParticleSystem.textureName) {
  50956. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50957. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50958. }
  50959. // Emitter
  50960. if (parsedParticleSystem.emitterId) {
  50961. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50962. }
  50963. else {
  50964. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50965. }
  50966. // Animations
  50967. if (parsedParticleSystem.animations) {
  50968. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50969. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50970. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50971. }
  50972. }
  50973. if (parsedParticleSystem.autoAnimate) {
  50974. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50975. }
  50976. // Particle system
  50977. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50978. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50979. particleSystem.minSize = parsedParticleSystem.minSize;
  50980. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50981. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50982. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50983. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50984. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50985. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50986. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50987. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50988. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50989. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50990. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50991. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50992. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50993. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50994. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50995. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50996. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50997. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50998. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50999. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51000. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51001. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51002. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51003. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51004. if (!particleSystem.preventAutoStart) {
  51005. particleSystem.start();
  51006. }
  51007. return particleSystem;
  51008. };
  51009. /**
  51010. * Source color is added to the destination color without alpha affecting the result.
  51011. */
  51012. ParticleSystem.BLENDMODE_ONEONE = 0;
  51013. /**
  51014. * Blend current color and particle color using particle’s alpha.
  51015. */
  51016. ParticleSystem.BLENDMODE_STANDARD = 1;
  51017. return ParticleSystem;
  51018. }());
  51019. BABYLON.ParticleSystem = ParticleSystem;
  51020. })(BABYLON || (BABYLON = {}));
  51021. //# sourceMappingURL=babylon.particleSystem.js.map
  51022. var BABYLON;
  51023. (function (BABYLON) {
  51024. /**
  51025. * Particle emitter emitting particles from the inside of a box.
  51026. * It emits the particles randomly between 2 given directions.
  51027. */
  51028. var BoxParticleEmitter = /** @class */ (function () {
  51029. // to be updated like the rest of emitters when breaking changes.
  51030. // all property should be come public variables and passed through constructor.
  51031. /**
  51032. * Creates a new instance of @see BoxParticleEmitter
  51033. */
  51034. function BoxParticleEmitter() {
  51035. /**
  51036. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51037. */
  51038. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51039. /**
  51040. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51041. */
  51042. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51043. /**
  51044. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51045. */
  51046. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51047. /**
  51048. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51049. */
  51050. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51051. }
  51052. /**
  51053. * Called by the particle System when the direction is computed for the created particle.
  51054. * @param emitPower is the power of the particle (speed)
  51055. * @param worldMatrix is the world matrix of the particle system
  51056. * @param directionToUpdate is the direction vector to update with the result
  51057. * @param particle is the particle we are computed the direction for
  51058. */
  51059. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51060. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51061. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51062. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51063. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51064. };
  51065. /**
  51066. * Called by the particle System when the position is computed for the created particle.
  51067. * @param worldMatrix is the world matrix of the particle system
  51068. * @param positionToUpdate is the position vector to update with the result
  51069. * @param particle is the particle we are computed the position for
  51070. */
  51071. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51072. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51073. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51074. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51076. };
  51077. /**
  51078. * Clones the current emitter and returns a copy of it
  51079. * @returns the new emitter
  51080. */
  51081. BoxParticleEmitter.prototype.clone = function () {
  51082. var newOne = new BoxParticleEmitter();
  51083. BABYLON.Tools.DeepCopy(this, newOne);
  51084. return newOne;
  51085. };
  51086. /**
  51087. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51088. * @param effect defines the update shader
  51089. */
  51090. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51091. };
  51092. return BoxParticleEmitter;
  51093. }());
  51094. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51095. })(BABYLON || (BABYLON = {}));
  51096. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51097. var BABYLON;
  51098. (function (BABYLON) {
  51099. /**
  51100. * Particle emitter emitting particles from the inside of a cone.
  51101. * It emits the particles alongside the cone volume from the base to the particle.
  51102. * The emission direction might be randomized.
  51103. */
  51104. var ConeParticleEmitter = /** @class */ (function () {
  51105. /**
  51106. * Creates a new instance of @see ConeParticleEmitter
  51107. * @param radius the radius of the emission cone
  51108. * @param angles the cone base angle
  51109. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51110. */
  51111. function ConeParticleEmitter(radius,
  51112. /**
  51113. * The radius of the emission cone.
  51114. */
  51115. angle,
  51116. /**
  51117. * The cone base angle.
  51118. */
  51119. directionRandomizer) {
  51120. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51121. this.angle = angle;
  51122. this.directionRandomizer = directionRandomizer;
  51123. this.radius = radius;
  51124. }
  51125. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51126. /**
  51127. * Gets the radius of the emission cone.
  51128. */
  51129. get: function () {
  51130. return this._radius;
  51131. },
  51132. /**
  51133. * Sets the radius of the emission cone.
  51134. */
  51135. set: function (value) {
  51136. this._radius = value;
  51137. if (this.angle !== 0) {
  51138. this._height = value / Math.tan(this.angle / 2);
  51139. }
  51140. else {
  51141. this._height = 1;
  51142. }
  51143. },
  51144. enumerable: true,
  51145. configurable: true
  51146. });
  51147. /**
  51148. * Called by the particle System when the direction is computed for the created particle.
  51149. * @param emitPower is the power of the particle (speed)
  51150. * @param worldMatrix is the world matrix of the particle system
  51151. * @param directionToUpdate is the direction vector to update with the result
  51152. * @param particle is the particle we are computed the direction for
  51153. */
  51154. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51155. if (this.angle === 0) {
  51156. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51157. }
  51158. else {
  51159. // measure the direction Vector from the emitter to the particle.
  51160. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51161. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51162. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51163. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51164. direction.x += randX;
  51165. direction.y += randY;
  51166. direction.z += randZ;
  51167. direction.normalize();
  51168. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51169. }
  51170. };
  51171. /**
  51172. * Called by the particle System when the position is computed for the created particle.
  51173. * @param worldMatrix is the world matrix of the particle system
  51174. * @param positionToUpdate is the position vector to update with the result
  51175. * @param particle is the particle we are computed the position for
  51176. */
  51177. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51178. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51179. var h = BABYLON.Scalar.RandomRange(0, 1);
  51180. // Better distribution in a cone at normal angles.
  51181. h = 1 - h * h;
  51182. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51183. radius = radius * h / this._height;
  51184. var randX = radius * Math.sin(s);
  51185. var randZ = radius * Math.cos(s);
  51186. var randY = h;
  51187. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51188. };
  51189. /**
  51190. * Clones the current emitter and returns a copy of it
  51191. * @returns the new emitter
  51192. */
  51193. ConeParticleEmitter.prototype.clone = function () {
  51194. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51195. BABYLON.Tools.DeepCopy(this, newOne);
  51196. return newOne;
  51197. };
  51198. /**
  51199. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51200. * @param effect defines the update shader
  51201. */
  51202. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51203. };
  51204. return ConeParticleEmitter;
  51205. }());
  51206. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51207. })(BABYLON || (BABYLON = {}));
  51208. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51209. var BABYLON;
  51210. (function (BABYLON) {
  51211. /**
  51212. * Particle emitter emitting particles from the inside of a sphere.
  51213. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51214. */
  51215. var SphereParticleEmitter = /** @class */ (function () {
  51216. /**
  51217. * Creates a new instance of @see SphereParticleEmitter
  51218. * @param radius the radius of the emission sphere
  51219. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51220. */
  51221. function SphereParticleEmitter(
  51222. /**
  51223. * The radius of the emission sphere.
  51224. */
  51225. radius,
  51226. /**
  51227. * How much to randomize the particle direction [0-1].
  51228. */
  51229. directionRandomizer) {
  51230. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51231. this.radius = radius;
  51232. this.directionRandomizer = directionRandomizer;
  51233. }
  51234. /**
  51235. * Called by the particle System when the direction is computed for the created particle.
  51236. * @param emitPower is the power of the particle (speed)
  51237. * @param worldMatrix is the world matrix of the particle system
  51238. * @param directionToUpdate is the direction vector to update with the result
  51239. * @param particle is the particle we are computed the direction for
  51240. */
  51241. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51242. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51243. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51244. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51245. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51246. direction.x += randX;
  51247. direction.y += randY;
  51248. direction.z += randZ;
  51249. direction.normalize();
  51250. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51251. };
  51252. /**
  51253. * Called by the particle System when the position is computed for the created particle.
  51254. * @param worldMatrix is the world matrix of the particle system
  51255. * @param positionToUpdate is the position vector to update with the result
  51256. * @param particle is the particle we are computed the position for
  51257. */
  51258. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51259. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51260. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51261. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51262. var randY = this.radius * Math.cos(theta);
  51263. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51264. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51265. };
  51266. /**
  51267. * Clones the current emitter and returns a copy of it
  51268. * @returns the new emitter
  51269. */
  51270. SphereParticleEmitter.prototype.clone = function () {
  51271. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51272. BABYLON.Tools.DeepCopy(this, newOne);
  51273. return newOne;
  51274. };
  51275. /**
  51276. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51277. * @param effect defines the update shader
  51278. */
  51279. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51280. };
  51281. return SphereParticleEmitter;
  51282. }());
  51283. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51284. /**
  51285. * Particle emitter emitting particles from the inside of a sphere.
  51286. * It emits the particles randomly between two vectors.
  51287. */
  51288. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51289. __extends(SphereDirectedParticleEmitter, _super);
  51290. /**
  51291. * Creates a new instance of @see SphereDirectedParticleEmitter
  51292. * @param radius the radius of the emission sphere
  51293. * @param direction1 the min limit of the emission direction
  51294. * @param direction2 the max limit of the emission direction
  51295. */
  51296. function SphereDirectedParticleEmitter(radius,
  51297. /**
  51298. * The min limit of the emission direction.
  51299. */
  51300. direction1,
  51301. /**
  51302. * The max limit of the emission direction.
  51303. */
  51304. direction2) {
  51305. var _this = _super.call(this, radius) || this;
  51306. _this.direction1 = direction1;
  51307. _this.direction2 = direction2;
  51308. return _this;
  51309. }
  51310. /**
  51311. * Called by the particle System when the direction is computed for the created particle.
  51312. * @param emitPower is the power of the particle (speed)
  51313. * @param worldMatrix is the world matrix of the particle system
  51314. * @param directionToUpdate is the direction vector to update with the result
  51315. * @param particle is the particle we are computed the direction for
  51316. */
  51317. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51318. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51319. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51320. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51321. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51322. };
  51323. /**
  51324. * Clones the current emitter and returns a copy of it
  51325. * @returns the new emitter
  51326. */
  51327. SphereDirectedParticleEmitter.prototype.clone = function () {
  51328. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51329. BABYLON.Tools.DeepCopy(this, newOne);
  51330. return newOne;
  51331. };
  51332. /**
  51333. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51334. * @param effect defines the update shader
  51335. */
  51336. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51337. };
  51338. return SphereDirectedParticleEmitter;
  51339. }(SphereParticleEmitter));
  51340. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51341. })(BABYLON || (BABYLON = {}));
  51342. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51343. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51344. var BABYLON;
  51345. (function (BABYLON) {
  51346. /**
  51347. * Represents one particle of a solid particle system.
  51348. * @see SolidParticleSystem
  51349. */
  51350. var SolidParticle = /** @class */ (function () {
  51351. /**
  51352. * Creates a Solid Particle object.
  51353. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51354. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51355. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51356. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51357. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51358. * @param shapeId (integer) is the model shape identifier in the SPS.
  51359. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51360. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51361. */
  51362. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51363. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51364. /**
  51365. * particle global index
  51366. */
  51367. this.idx = 0;
  51368. /**
  51369. * The color of the particle
  51370. */
  51371. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51372. /**
  51373. * The world space position of the particle.
  51374. */
  51375. this.position = BABYLON.Vector3.Zero();
  51376. /**
  51377. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51378. */
  51379. this.rotation = BABYLON.Vector3.Zero();
  51380. /**
  51381. * The scaling of the particle.
  51382. */
  51383. this.scaling = BABYLON.Vector3.One();
  51384. /**
  51385. * The uvs of the particle.
  51386. */
  51387. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51388. /**
  51389. * The current speed of the particle.
  51390. */
  51391. this.velocity = BABYLON.Vector3.Zero();
  51392. /**
  51393. * The pivot point in the particle local space.
  51394. */
  51395. this.pivot = BABYLON.Vector3.Zero();
  51396. /**
  51397. * Must the particle be translated from its pivot point in its local space ?
  51398. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51399. * Default : false
  51400. */
  51401. this.translateFromPivot = false;
  51402. /**
  51403. * Is the particle active or not ?
  51404. */
  51405. this.alive = true;
  51406. /**
  51407. * Is the particle visible or not ?
  51408. */
  51409. this.isVisible = true;
  51410. /**
  51411. * Index of this particle in the global "positions" array (Internal use)
  51412. */
  51413. this._pos = 0;
  51414. /**
  51415. * Index of this particle in the global "indices" array (Internal use)
  51416. */
  51417. this._ind = 0;
  51418. /**
  51419. * ModelShape id of this particle
  51420. */
  51421. this.shapeId = 0;
  51422. /**
  51423. * Index of the particle in its shape id (Internal use)
  51424. */
  51425. this.idxInShape = 0;
  51426. /**
  51427. * Still set as invisible in order to skip useless computations (Internal use)
  51428. */
  51429. this._stillInvisible = false;
  51430. /**
  51431. * Last computed particle rotation matrix
  51432. */
  51433. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51434. /**
  51435. * Parent particle Id, if any.
  51436. * Default null.
  51437. */
  51438. this.parentId = null;
  51439. /**
  51440. * Internal global position in the SPS.
  51441. */
  51442. this._globalPosition = BABYLON.Vector3.Zero();
  51443. this.idx = particleIndex;
  51444. this._pos = positionIndex;
  51445. this._ind = indiceIndex;
  51446. this._model = model;
  51447. this.shapeId = shapeId;
  51448. this.idxInShape = idxInShape;
  51449. this._sps = sps;
  51450. if (modelBoundingInfo) {
  51451. this._modelBoundingInfo = modelBoundingInfo;
  51452. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51453. }
  51454. }
  51455. Object.defineProperty(SolidParticle.prototype, "scale", {
  51456. /**
  51457. * Legacy support, changed scale to scaling
  51458. */
  51459. get: function () {
  51460. return this.scaling;
  51461. },
  51462. /**
  51463. * Legacy support, changed scale to scaling
  51464. */
  51465. set: function (scale) {
  51466. this.scaling = scale;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51472. /**
  51473. * Legacy support, changed quaternion to rotationQuaternion
  51474. */
  51475. get: function () {
  51476. return this.rotationQuaternion;
  51477. },
  51478. /**
  51479. * Legacy support, changed quaternion to rotationQuaternion
  51480. */
  51481. set: function (q) {
  51482. this.rotationQuaternion = q;
  51483. },
  51484. enumerable: true,
  51485. configurable: true
  51486. });
  51487. /**
  51488. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51489. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51490. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51491. * @returns true if it intersects
  51492. */
  51493. SolidParticle.prototype.intersectsMesh = function (target) {
  51494. if (!this._boundingInfo || !target._boundingInfo) {
  51495. return false;
  51496. }
  51497. if (this._sps._bSphereOnly) {
  51498. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51499. }
  51500. return this._boundingInfo.intersects(target._boundingInfo, false);
  51501. };
  51502. return SolidParticle;
  51503. }());
  51504. BABYLON.SolidParticle = SolidParticle;
  51505. /**
  51506. * Represents the shape of the model used by one particle of a solid particle system.
  51507. * SPS internal tool, don't use it manually.
  51508. * @see SolidParticleSystem
  51509. */
  51510. var ModelShape = /** @class */ (function () {
  51511. /**
  51512. * 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.
  51513. * SPS internal tool, don't use it manually.
  51514. * @ignore
  51515. */
  51516. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51517. /**
  51518. * length of the shape in the model indices array (internal use)
  51519. */
  51520. this._indicesLength = 0;
  51521. this.shapeID = id;
  51522. this._shape = shape;
  51523. this._indicesLength = indicesLength;
  51524. this._shapeUV = shapeUV;
  51525. this._positionFunction = posFunction;
  51526. this._vertexFunction = vtxFunction;
  51527. }
  51528. return ModelShape;
  51529. }());
  51530. BABYLON.ModelShape = ModelShape;
  51531. /**
  51532. * Represents a Depth Sorted Particle in the solid particle system.
  51533. * @see SolidParticleSystem
  51534. */
  51535. var DepthSortedParticle = /** @class */ (function () {
  51536. function DepthSortedParticle() {
  51537. /**
  51538. * Index of the particle in the "indices" array
  51539. */
  51540. this.ind = 0;
  51541. /**
  51542. * Length of the particle shape in the "indices" array
  51543. */
  51544. this.indicesLength = 0;
  51545. /**
  51546. * Squared distance from the particle to the camera
  51547. */
  51548. this.sqDistance = 0.0;
  51549. }
  51550. return DepthSortedParticle;
  51551. }());
  51552. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51553. })(BABYLON || (BABYLON = {}));
  51554. //# sourceMappingURL=babylon.solidParticle.js.map
  51555. var BABYLON;
  51556. (function (BABYLON) {
  51557. /**
  51558. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51559. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  51560. * The SPS is also a particle system. It provides some methods to manage the particles.
  51561. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51562. *
  51563. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51564. */
  51565. var SolidParticleSystem = /** @class */ (function () {
  51566. /**
  51567. * Creates a SPS (Solid Particle System) object.
  51568. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51569. * @param scene (Scene) is the scene in which the SPS is added.
  51570. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51571. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51572. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51573. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51574. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51575. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51576. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51577. */
  51578. function SolidParticleSystem(name, scene, options) {
  51579. /**
  51580. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51581. * Example : var p = SPS.particles[i];
  51582. */
  51583. this.particles = new Array();
  51584. /**
  51585. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51586. */
  51587. this.nbParticles = 0;
  51588. /**
  51589. * If the particles must ever face the camera (default false). Useful for planar particles.
  51590. */
  51591. this.billboard = false;
  51592. /**
  51593. * Recompute normals when adding a shape
  51594. */
  51595. this.recomputeNormals = true;
  51596. /**
  51597. * This a counter ofr your own usage. It's not set by any SPS functions.
  51598. */
  51599. this.counter = 0;
  51600. /**
  51601. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51602. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51603. */
  51604. this.vars = {};
  51605. /**
  51606. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51607. */
  51608. this._bSphereOnly = false;
  51609. /**
  51610. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51611. */
  51612. this._bSphereRadiusFactor = 1.0;
  51613. this._positions = new Array();
  51614. this._indices = new Array();
  51615. this._normals = new Array();
  51616. this._colors = new Array();
  51617. this._uvs = new Array();
  51618. this._index = 0; // indices index
  51619. this._updatable = true;
  51620. this._pickable = false;
  51621. this._isVisibilityBoxLocked = false;
  51622. this._alwaysVisible = false;
  51623. this._depthSort = false;
  51624. this._shapeCounter = 0;
  51625. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51626. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51627. this._computeParticleColor = true;
  51628. this._computeParticleTexture = true;
  51629. this._computeParticleRotation = true;
  51630. this._computeParticleVertex = false;
  51631. this._computeBoundingBox = false;
  51632. this._depthSortParticles = true;
  51633. this._cam_axisZ = BABYLON.Vector3.Zero();
  51634. this._cam_axisY = BABYLON.Vector3.Zero();
  51635. this._cam_axisX = BABYLON.Vector3.Zero();
  51636. this._axisZ = BABYLON.Axis.Z;
  51637. this._camDir = BABYLON.Vector3.Zero();
  51638. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51639. this._rotMatrix = new BABYLON.Matrix();
  51640. this._invertMatrix = new BABYLON.Matrix();
  51641. this._rotated = BABYLON.Vector3.Zero();
  51642. this._quaternion = new BABYLON.Quaternion();
  51643. this._vertex = BABYLON.Vector3.Zero();
  51644. this._normal = BABYLON.Vector3.Zero();
  51645. this._yaw = 0.0;
  51646. this._pitch = 0.0;
  51647. this._roll = 0.0;
  51648. this._halfroll = 0.0;
  51649. this._halfpitch = 0.0;
  51650. this._halfyaw = 0.0;
  51651. this._sinRoll = 0.0;
  51652. this._cosRoll = 0.0;
  51653. this._sinPitch = 0.0;
  51654. this._cosPitch = 0.0;
  51655. this._sinYaw = 0.0;
  51656. this._cosYaw = 0.0;
  51657. this._mustUnrotateFixedNormals = false;
  51658. this._minimum = BABYLON.Vector3.Zero();
  51659. this._maximum = BABYLON.Vector3.Zero();
  51660. this._minBbox = BABYLON.Vector3.Zero();
  51661. this._maxBbox = BABYLON.Vector3.Zero();
  51662. this._particlesIntersect = false;
  51663. this._depthSortFunction = function (p1, p2) {
  51664. return (p2.sqDistance - p1.sqDistance);
  51665. };
  51666. this._needs32Bits = false;
  51667. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51668. this._scaledPivot = BABYLON.Vector3.Zero();
  51669. this._particleHasParent = false;
  51670. this.name = name;
  51671. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51672. this._camera = scene.activeCamera;
  51673. this._pickable = options ? options.isPickable : false;
  51674. this._depthSort = options ? options.enableDepthSort : false;
  51675. this._particlesIntersect = options ? options.particleIntersection : false;
  51676. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51677. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51678. if (options && options.updatable) {
  51679. this._updatable = options.updatable;
  51680. }
  51681. else {
  51682. this._updatable = true;
  51683. }
  51684. if (this._pickable) {
  51685. this.pickedParticles = [];
  51686. }
  51687. if (this._depthSort) {
  51688. this.depthSortedParticles = [];
  51689. }
  51690. }
  51691. /**
  51692. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51693. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51694. * @returns the created mesh
  51695. */
  51696. SolidParticleSystem.prototype.buildMesh = function () {
  51697. if (this.nbParticles === 0) {
  51698. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51699. this.addShape(triangle, 1);
  51700. triangle.dispose();
  51701. }
  51702. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51703. this._positions32 = new Float32Array(this._positions);
  51704. this._uvs32 = new Float32Array(this._uvs);
  51705. this._colors32 = new Float32Array(this._colors);
  51706. if (this.recomputeNormals) {
  51707. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51708. }
  51709. this._normals32 = new Float32Array(this._normals);
  51710. this._fixedNormal32 = new Float32Array(this._normals);
  51711. if (this._mustUnrotateFixedNormals) {
  51712. this._unrotateFixedNormals();
  51713. }
  51714. var vertexData = new BABYLON.VertexData();
  51715. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51716. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51717. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51718. if (this._uvs32) {
  51719. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51720. ;
  51721. }
  51722. if (this._colors32) {
  51723. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51724. }
  51725. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51726. vertexData.applyToMesh(mesh, this._updatable);
  51727. this.mesh = mesh;
  51728. this.mesh.isPickable = this._pickable;
  51729. // free memory
  51730. if (!this._depthSort) {
  51731. this._indices = null;
  51732. }
  51733. this._positions = null;
  51734. this._normals = null;
  51735. this._uvs = null;
  51736. this._colors = null;
  51737. if (!this._updatable) {
  51738. this.particles.length = 0;
  51739. }
  51740. return mesh;
  51741. };
  51742. /**
  51743. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51744. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51745. * Thus the particles generated from `digest()` have their property `position` set yet.
  51746. * @param mesh ( Mesh ) is the mesh to be digested
  51747. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  51748. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51749. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51750. * @returns the current SPS
  51751. */
  51752. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51753. var size = (options && options.facetNb) || 1;
  51754. var number = (options && options.number) || 0;
  51755. var delta = (options && options.delta) || 0;
  51756. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51757. var meshInd = mesh.getIndices();
  51758. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51759. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51760. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51761. var f = 0; // facet counter
  51762. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51763. // compute size from number
  51764. if (number) {
  51765. number = (number > totalFacets) ? totalFacets : number;
  51766. size = Math.round(totalFacets / number);
  51767. delta = 0;
  51768. }
  51769. else {
  51770. size = (size > totalFacets) ? totalFacets : size;
  51771. }
  51772. var facetPos = []; // submesh positions
  51773. var facetInd = []; // submesh indices
  51774. var facetUV = []; // submesh UV
  51775. var facetCol = []; // submesh colors
  51776. var barycenter = BABYLON.Vector3.Zero();
  51777. var sizeO = size;
  51778. while (f < totalFacets) {
  51779. size = sizeO + Math.floor((1 + delta) * Math.random());
  51780. if (f > totalFacets - size) {
  51781. size = totalFacets - f;
  51782. }
  51783. // reset temp arrays
  51784. facetPos.length = 0;
  51785. facetInd.length = 0;
  51786. facetUV.length = 0;
  51787. facetCol.length = 0;
  51788. // iterate over "size" facets
  51789. var fi = 0;
  51790. for (var j = f * 3; j < (f + size) * 3; j++) {
  51791. facetInd.push(fi);
  51792. var i = meshInd[j];
  51793. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51794. if (meshUV) {
  51795. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51796. }
  51797. if (meshCol) {
  51798. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51799. }
  51800. fi++;
  51801. }
  51802. // create a model shape for each single particle
  51803. var idx = this.nbParticles;
  51804. var shape = this._posToShape(facetPos);
  51805. var shapeUV = this._uvsToShapeUV(facetUV);
  51806. // compute the barycenter of the shape
  51807. var v;
  51808. for (v = 0; v < shape.length; v++) {
  51809. barycenter.addInPlace(shape[v]);
  51810. }
  51811. barycenter.scaleInPlace(1 / shape.length);
  51812. // shift the shape from its barycenter to the origin
  51813. for (v = 0; v < shape.length; v++) {
  51814. shape[v].subtractInPlace(barycenter);
  51815. }
  51816. var bInfo;
  51817. if (this._particlesIntersect) {
  51818. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51819. }
  51820. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51821. // add the particle in the SPS
  51822. var currentPos = this._positions.length;
  51823. var currentInd = this._indices.length;
  51824. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51825. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51826. // initialize the particle position
  51827. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51828. this._index += shape.length;
  51829. idx++;
  51830. this.nbParticles++;
  51831. this._shapeCounter++;
  51832. f += size;
  51833. }
  51834. return this;
  51835. };
  51836. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51837. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51838. var index = 0;
  51839. var idx = 0;
  51840. for (var p = 0; p < this.particles.length; p++) {
  51841. this._particle = this.particles[p];
  51842. this._shape = this._particle._model._shape;
  51843. if (this._particle.rotationQuaternion) {
  51844. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51845. }
  51846. else {
  51847. this._yaw = this._particle.rotation.y;
  51848. this._pitch = this._particle.rotation.x;
  51849. this._roll = this._particle.rotation.z;
  51850. this._quaternionRotationYPR();
  51851. }
  51852. this._quaternionToRotationMatrix();
  51853. this._rotMatrix.invertToRef(this._invertMatrix);
  51854. for (var pt = 0; pt < this._shape.length; pt++) {
  51855. idx = index + pt * 3;
  51856. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51857. this._fixedNormal32[idx] = this._normal.x;
  51858. this._fixedNormal32[idx + 1] = this._normal.y;
  51859. this._fixedNormal32[idx + 2] = this._normal.z;
  51860. }
  51861. index = idx + 3;
  51862. }
  51863. };
  51864. //reset copy
  51865. SolidParticleSystem.prototype._resetCopy = function () {
  51866. this._copy.position.x = 0;
  51867. this._copy.position.y = 0;
  51868. this._copy.position.z = 0;
  51869. this._copy.rotation.x = 0;
  51870. this._copy.rotation.y = 0;
  51871. this._copy.rotation.z = 0;
  51872. this._copy.rotationQuaternion = null;
  51873. this._copy.scaling.x = 1.0;
  51874. this._copy.scaling.y = 1.0;
  51875. this._copy.scaling.z = 1.0;
  51876. this._copy.uvs.x = 0;
  51877. this._copy.uvs.y = 0;
  51878. this._copy.uvs.z = 1.0;
  51879. this._copy.uvs.w = 1.0;
  51880. this._copy.color = null;
  51881. this._copy.translateFromPivot = false;
  51882. };
  51883. // _meshBuilder : inserts the shape model in the global SPS mesh
  51884. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51885. var i;
  51886. var u = 0;
  51887. var c = 0;
  51888. var n = 0;
  51889. this._resetCopy();
  51890. if (options && options.positionFunction) {
  51891. options.positionFunction(this._copy, idx, idxInShape);
  51892. this._mustUnrotateFixedNormals = true;
  51893. }
  51894. if (this._copy.rotationQuaternion) {
  51895. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51896. }
  51897. else {
  51898. this._yaw = this._copy.rotation.y;
  51899. this._pitch = this._copy.rotation.x;
  51900. this._roll = this._copy.rotation.z;
  51901. this._quaternionRotationYPR();
  51902. }
  51903. this._quaternionToRotationMatrix();
  51904. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  51905. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  51906. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  51907. if (this._copy.translateFromPivot) {
  51908. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51909. }
  51910. else {
  51911. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51912. }
  51913. for (i = 0; i < shape.length; i++) {
  51914. this._vertex.x = shape[i].x;
  51915. this._vertex.y = shape[i].y;
  51916. this._vertex.z = shape[i].z;
  51917. if (options && options.vertexFunction) {
  51918. options.vertexFunction(this._copy, this._vertex, i);
  51919. }
  51920. this._vertex.x *= this._copy.scaling.x;
  51921. this._vertex.y *= this._copy.scaling.y;
  51922. this._vertex.z *= this._copy.scaling.z;
  51923. this._vertex.x -= this._scaledPivot.x;
  51924. this._vertex.y -= this._scaledPivot.y;
  51925. this._vertex.z -= this._scaledPivot.z;
  51926. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51927. this._rotated.addInPlace(this._pivotBackTranslation);
  51928. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51929. if (meshUV) {
  51930. 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);
  51931. u += 2;
  51932. }
  51933. if (this._copy.color) {
  51934. this._color = this._copy.color;
  51935. }
  51936. else if (meshCol && meshCol[c] !== undefined) {
  51937. this._color.r = meshCol[c];
  51938. this._color.g = meshCol[c + 1];
  51939. this._color.b = meshCol[c + 2];
  51940. this._color.a = meshCol[c + 3];
  51941. }
  51942. else {
  51943. this._color.r = 1.0;
  51944. this._color.g = 1.0;
  51945. this._color.b = 1.0;
  51946. this._color.a = 1.0;
  51947. }
  51948. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51949. c += 4;
  51950. if (!this.recomputeNormals && meshNor) {
  51951. this._normal.x = meshNor[n];
  51952. this._normal.y = meshNor[n + 1];
  51953. this._normal.z = meshNor[n + 2];
  51954. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51955. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51956. n += 3;
  51957. }
  51958. }
  51959. for (i = 0; i < meshInd.length; i++) {
  51960. var current_ind = p + meshInd[i];
  51961. indices.push(current_ind);
  51962. if (current_ind > 65535) {
  51963. this._needs32Bits = true;
  51964. }
  51965. }
  51966. if (this._pickable) {
  51967. var nbfaces = meshInd.length / 3;
  51968. for (i = 0; i < nbfaces; i++) {
  51969. this.pickedParticles.push({ idx: idx, faceId: i });
  51970. }
  51971. }
  51972. if (this._depthSort) {
  51973. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51974. }
  51975. return this._copy;
  51976. };
  51977. // returns a shape array from positions array
  51978. SolidParticleSystem.prototype._posToShape = function (positions) {
  51979. var shape = [];
  51980. for (var i = 0; i < positions.length; i += 3) {
  51981. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51982. }
  51983. return shape;
  51984. };
  51985. // returns a shapeUV array from a Vector4 uvs
  51986. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51987. var shapeUV = [];
  51988. if (uvs) {
  51989. for (var i = 0; i < uvs.length; i++)
  51990. shapeUV.push(uvs[i]);
  51991. }
  51992. return shapeUV;
  51993. };
  51994. // adds a new particle object in the particles array
  51995. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51996. if (bInfo === void 0) { bInfo = null; }
  51997. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51998. this.particles.push(sp);
  51999. return sp;
  52000. };
  52001. /**
  52002. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52003. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52004. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52005. * @param nb (positive integer) the number of particles to be created from this model
  52006. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52007. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52008. * @returns the number of shapes in the system
  52009. */
  52010. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52011. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52012. var meshInd = mesh.getIndices();
  52013. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52014. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52015. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52016. var bbInfo;
  52017. if (this._particlesIntersect) {
  52018. bbInfo = mesh.getBoundingInfo();
  52019. }
  52020. var shape = this._posToShape(meshPos);
  52021. var shapeUV = this._uvsToShapeUV(meshUV);
  52022. var posfunc = options ? options.positionFunction : null;
  52023. var vtxfunc = options ? options.vertexFunction : null;
  52024. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52025. // particles
  52026. var sp;
  52027. var currentCopy;
  52028. var idx = this.nbParticles;
  52029. for (var i = 0; i < nb; i++) {
  52030. var currentPos = this._positions.length;
  52031. var currentInd = this._indices.length;
  52032. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52033. if (this._updatable) {
  52034. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52035. sp.position.copyFrom(currentCopy.position);
  52036. sp.rotation.copyFrom(currentCopy.rotation);
  52037. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52038. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52039. }
  52040. if (currentCopy.color && sp.color) {
  52041. sp.color.copyFrom(currentCopy.color);
  52042. }
  52043. sp.scaling.copyFrom(currentCopy.scaling);
  52044. sp.uvs.copyFrom(currentCopy.uvs);
  52045. }
  52046. this._index += shape.length;
  52047. idx++;
  52048. }
  52049. this.nbParticles += nb;
  52050. this._shapeCounter++;
  52051. return this._shapeCounter - 1;
  52052. };
  52053. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52054. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52055. this._resetCopy();
  52056. if (particle._model._positionFunction) {
  52057. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52058. }
  52059. if (this._copy.rotationQuaternion) {
  52060. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52061. }
  52062. else {
  52063. this._yaw = this._copy.rotation.y;
  52064. this._pitch = this._copy.rotation.x;
  52065. this._roll = this._copy.rotation.z;
  52066. this._quaternionRotationYPR();
  52067. }
  52068. this._quaternionToRotationMatrix();
  52069. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52070. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52071. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52072. if (this._copy.translateFromPivot) {
  52073. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52074. }
  52075. else {
  52076. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52077. }
  52078. this._shape = particle._model._shape;
  52079. for (var pt = 0; pt < this._shape.length; pt++) {
  52080. this._vertex.x = this._shape[pt].x;
  52081. this._vertex.y = this._shape[pt].y;
  52082. this._vertex.z = this._shape[pt].z;
  52083. if (particle._model._vertexFunction) {
  52084. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52085. }
  52086. this._vertex.x *= this._copy.scaling.x;
  52087. this._vertex.y *= this._copy.scaling.y;
  52088. this._vertex.z *= this._copy.scaling.z;
  52089. this._vertex.x -= this._scaledPivot.x;
  52090. this._vertex.y -= this._scaledPivot.y;
  52091. this._vertex.z -= this._scaledPivot.z;
  52092. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52093. this._rotated.addInPlace(this._pivotBackTranslation);
  52094. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52095. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52096. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52097. }
  52098. particle.position.x = 0.0;
  52099. particle.position.y = 0.0;
  52100. particle.position.z = 0.0;
  52101. particle.rotation.x = 0.0;
  52102. particle.rotation.y = 0.0;
  52103. particle.rotation.z = 0.0;
  52104. particle.rotationQuaternion = null;
  52105. particle.scaling.x = 1.0;
  52106. particle.scaling.y = 1.0;
  52107. particle.scaling.z = 1.0;
  52108. particle.uvs.x = 0.0;
  52109. particle.uvs.y = 0.0;
  52110. particle.uvs.z = 1.0;
  52111. particle.uvs.w = 1.0;
  52112. particle.pivot.x = 0.0;
  52113. particle.pivot.y = 0.0;
  52114. particle.pivot.z = 0.0;
  52115. particle.translateFromPivot = false;
  52116. particle.parentId = null;
  52117. };
  52118. /**
  52119. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52120. * @returns the SPS.
  52121. */
  52122. SolidParticleSystem.prototype.rebuildMesh = function () {
  52123. for (var p = 0; p < this.particles.length; p++) {
  52124. this._rebuildParticle(this.particles[p]);
  52125. }
  52126. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52127. return this;
  52128. };
  52129. /**
  52130. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52131. * This method calls `updateParticle()` for each particle of the SPS.
  52132. * For an animated SPS, it is usually called within the render loop.
  52133. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52134. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52135. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52136. * @returns the SPS.
  52137. */
  52138. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52139. if (start === void 0) { start = 0; }
  52140. if (end === void 0) { end = this.nbParticles - 1; }
  52141. if (update === void 0) { update = true; }
  52142. if (!this._updatable) {
  52143. return this;
  52144. }
  52145. // custom beforeUpdate
  52146. this.beforeUpdateParticles(start, end, update);
  52147. this._cam_axisX.x = 1.0;
  52148. this._cam_axisX.y = 0.0;
  52149. this._cam_axisX.z = 0.0;
  52150. this._cam_axisY.x = 0.0;
  52151. this._cam_axisY.y = 1.0;
  52152. this._cam_axisY.z = 0.0;
  52153. this._cam_axisZ.x = 0.0;
  52154. this._cam_axisZ.y = 0.0;
  52155. this._cam_axisZ.z = 1.0;
  52156. // cases when the World Matrix is to be computed first
  52157. if (this.billboard || this._depthSort) {
  52158. this.mesh.computeWorldMatrix(true);
  52159. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52160. }
  52161. // if the particles will always face the camera
  52162. if (this.billboard) {
  52163. // compute the camera position and un-rotate it by the current mesh rotation
  52164. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52165. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52166. this._cam_axisZ.normalize();
  52167. // same for camera up vector extracted from the cam view matrix
  52168. var view = this._camera.getViewMatrix(true);
  52169. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52170. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52171. this._cam_axisY.normalize();
  52172. this._cam_axisX.normalize();
  52173. }
  52174. // if depthSort, compute the camera global position in the mesh local system
  52175. if (this._depthSort) {
  52176. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52177. }
  52178. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52179. var idx = 0; // current position index in the global array positions32
  52180. var index = 0; // position start index in the global array positions32 of the current particle
  52181. var colidx = 0; // current color index in the global array colors32
  52182. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52183. var uvidx = 0; // current uv index in the global array uvs32
  52184. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52185. var pt = 0; // current index in the particle model shape
  52186. if (this.mesh.isFacetDataEnabled) {
  52187. this._computeBoundingBox = true;
  52188. }
  52189. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52190. if (this._computeBoundingBox) {
  52191. if (start == 0 && end == this.nbParticles - 1) {
  52192. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52193. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52194. }
  52195. else {
  52196. if (this.mesh._boundingInfo) {
  52197. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52198. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52199. }
  52200. }
  52201. }
  52202. // particle loop
  52203. index = this.particles[start]._pos;
  52204. var vpos = (index / 3) | 0;
  52205. colorIndex = vpos * 4;
  52206. uvIndex = vpos * 2;
  52207. for (var p = start; p <= end; p++) {
  52208. this._particle = this.particles[p];
  52209. this._shape = this._particle._model._shape;
  52210. this._shapeUV = this._particle._model._shapeUV;
  52211. // call to custom user function to update the particle properties
  52212. this.updateParticle(this._particle);
  52213. // camera-particle distance for depth sorting
  52214. if (this._depthSort && this._depthSortParticles) {
  52215. var dsp = this.depthSortedParticles[p];
  52216. dsp.ind = this._particle._ind;
  52217. dsp.indicesLength = this._particle._model._indicesLength;
  52218. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52219. }
  52220. // skip the computations for inactive or already invisible particles
  52221. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52222. // increment indexes for the next particle
  52223. pt = this._shape.length;
  52224. index += pt * 3;
  52225. colorIndex += pt * 4;
  52226. uvIndex += pt * 2;
  52227. continue;
  52228. }
  52229. if (this._particle.isVisible) {
  52230. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52231. this._particleHasParent = (this._particle.parentId !== null);
  52232. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52233. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52234. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52235. // particle rotation matrix
  52236. if (this.billboard) {
  52237. this._particle.rotation.x = 0.0;
  52238. this._particle.rotation.y = 0.0;
  52239. }
  52240. if (this._computeParticleRotation || this.billboard) {
  52241. if (this._particle.rotationQuaternion) {
  52242. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52243. }
  52244. else {
  52245. this._yaw = this._particle.rotation.y;
  52246. this._pitch = this._particle.rotation.x;
  52247. this._roll = this._particle.rotation.z;
  52248. this._quaternionRotationYPR();
  52249. }
  52250. this._quaternionToRotationMatrix();
  52251. }
  52252. if (this._particleHasParent) {
  52253. this._parent = this.particles[this._particle.parentId];
  52254. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  52255. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  52256. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  52257. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52258. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52259. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52260. if (this._computeParticleRotation || this.billboard) {
  52261. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  52262. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  52263. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  52264. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  52265. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  52266. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  52267. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  52268. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  52269. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  52270. }
  52271. }
  52272. else {
  52273. this._particle._globalPosition.x = this._particle.position.x;
  52274. this._particle._globalPosition.y = this._particle.position.y;
  52275. this._particle._globalPosition.z = this._particle.position.z;
  52276. if (this._computeParticleRotation || this.billboard) {
  52277. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52278. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52279. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52280. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52281. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52282. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52283. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52284. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52285. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52286. }
  52287. }
  52288. if (this._particle.translateFromPivot) {
  52289. this._pivotBackTranslation.x = 0.0;
  52290. this._pivotBackTranslation.y = 0.0;
  52291. this._pivotBackTranslation.z = 0.0;
  52292. }
  52293. else {
  52294. this._pivotBackTranslation.x = this._scaledPivot.x;
  52295. this._pivotBackTranslation.y = this._scaledPivot.y;
  52296. this._pivotBackTranslation.z = this._scaledPivot.z;
  52297. }
  52298. // particle vertex loop
  52299. for (pt = 0; pt < this._shape.length; pt++) {
  52300. idx = index + pt * 3;
  52301. colidx = colorIndex + pt * 4;
  52302. uvidx = uvIndex + pt * 2;
  52303. this._vertex.x = this._shape[pt].x;
  52304. this._vertex.y = this._shape[pt].y;
  52305. this._vertex.z = this._shape[pt].z;
  52306. if (this._computeParticleVertex) {
  52307. this.updateParticleVertex(this._particle, this._vertex, pt);
  52308. }
  52309. // positions
  52310. this._vertex.x *= this._particle.scaling.x;
  52311. this._vertex.y *= this._particle.scaling.y;
  52312. this._vertex.z *= this._particle.scaling.z;
  52313. this._vertex.x -= this._scaledPivot.x;
  52314. this._vertex.y -= this._scaledPivot.y;
  52315. this._vertex.z -= this._scaledPivot.z;
  52316. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52317. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52318. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52319. this._rotated.x += this._pivotBackTranslation.x;
  52320. this._rotated.y += this._pivotBackTranslation.y;
  52321. this._rotated.z += this._pivotBackTranslation.z;
  52322. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52323. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  52324. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  52325. if (this._computeBoundingBox) {
  52326. if (this._positions32[idx] < this._minimum.x) {
  52327. this._minimum.x = this._positions32[idx];
  52328. }
  52329. if (this._positions32[idx] > this._maximum.x) {
  52330. this._maximum.x = this._positions32[idx];
  52331. }
  52332. if (this._positions32[idx + 1] < this._minimum.y) {
  52333. this._minimum.y = this._positions32[idx + 1];
  52334. }
  52335. if (this._positions32[idx + 1] > this._maximum.y) {
  52336. this._maximum.y = this._positions32[idx + 1];
  52337. }
  52338. if (this._positions32[idx + 2] < this._minimum.z) {
  52339. this._minimum.z = this._positions32[idx + 2];
  52340. }
  52341. if (this._positions32[idx + 2] > this._maximum.z) {
  52342. this._maximum.z = this._positions32[idx + 2];
  52343. }
  52344. }
  52345. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52346. if (!this._computeParticleVertex) {
  52347. this._normal.x = this._fixedNormal32[idx];
  52348. this._normal.y = this._fixedNormal32[idx + 1];
  52349. this._normal.z = this._fixedNormal32[idx + 2];
  52350. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52351. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52352. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52353. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52354. 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;
  52355. 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;
  52356. }
  52357. if (this._computeParticleColor && this._particle.color) {
  52358. this._colors32[colidx] = this._particle.color.r;
  52359. this._colors32[colidx + 1] = this._particle.color.g;
  52360. this._colors32[colidx + 2] = this._particle.color.b;
  52361. this._colors32[colidx + 3] = this._particle.color.a;
  52362. }
  52363. if (this._computeParticleTexture) {
  52364. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52365. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52366. }
  52367. }
  52368. }
  52369. else {
  52370. this._particle._stillInvisible = true; // mark the particle as invisible
  52371. for (pt = 0; pt < this._shape.length; pt++) {
  52372. idx = index + pt * 3;
  52373. colidx = colorIndex + pt * 4;
  52374. uvidx = uvIndex + pt * 2;
  52375. this._positions32[idx] = 0.0;
  52376. this._positions32[idx + 1] = 0.0;
  52377. this._positions32[idx + 2] = 0.0;
  52378. this._normals32[idx] = 0.0;
  52379. this._normals32[idx + 1] = 0.0;
  52380. this._normals32[idx + 2] = 0.0;
  52381. if (this._computeParticleColor && this._particle.color) {
  52382. this._colors32[colidx] = this._particle.color.r;
  52383. this._colors32[colidx + 1] = this._particle.color.g;
  52384. this._colors32[colidx + 2] = this._particle.color.b;
  52385. this._colors32[colidx + 3] = this._particle.color.a;
  52386. }
  52387. if (this._computeParticleTexture) {
  52388. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52389. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52390. }
  52391. }
  52392. }
  52393. // if the particle intersections must be computed : update the bbInfo
  52394. if (this._particlesIntersect) {
  52395. var bInfo = this._particle._boundingInfo;
  52396. var bBox = bInfo.boundingBox;
  52397. var bSphere = bInfo.boundingSphere;
  52398. if (!this._bSphereOnly) {
  52399. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52400. for (var b = 0; b < bBox.vectors.length; b++) {
  52401. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52402. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52403. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52404. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52405. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52406. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52407. 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;
  52408. 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;
  52409. 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;
  52410. }
  52411. bBox._update(this.mesh._worldMatrix);
  52412. }
  52413. // place and scale the particle bouding sphere in the SPS local system, then update it
  52414. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52415. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52416. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52417. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52418. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52419. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52420. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52421. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52422. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52423. 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));
  52424. bSphere._update(this.mesh._worldMatrix);
  52425. }
  52426. // increment indexes for the next particle
  52427. index = idx + 3;
  52428. colorIndex = colidx + 4;
  52429. uvIndex = uvidx + 2;
  52430. }
  52431. // if the VBO must be updated
  52432. if (update) {
  52433. if (this._computeParticleColor) {
  52434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52435. }
  52436. if (this._computeParticleTexture) {
  52437. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52438. }
  52439. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52440. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52441. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52442. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52443. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52444. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52445. for (var i = 0; i < this._normals32.length; i++) {
  52446. this._fixedNormal32[i] = this._normals32[i];
  52447. }
  52448. }
  52449. if (!this.mesh.areNormalsFrozen) {
  52450. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52451. }
  52452. }
  52453. if (this._depthSort && this._depthSortParticles) {
  52454. this.depthSortedParticles.sort(this._depthSortFunction);
  52455. var dspl = this.depthSortedParticles.length;
  52456. var sorted = 0;
  52457. var lind = 0;
  52458. var sind = 0;
  52459. var sid = 0;
  52460. for (sorted = 0; sorted < dspl; sorted++) {
  52461. lind = this.depthSortedParticles[sorted].indicesLength;
  52462. sind = this.depthSortedParticles[sorted].ind;
  52463. for (var i = 0; i < lind; i++) {
  52464. this._indices32[sid] = this._indices[sind + i];
  52465. sid++;
  52466. }
  52467. }
  52468. this.mesh.updateIndices(this._indices32);
  52469. }
  52470. }
  52471. if (this._computeBoundingBox) {
  52472. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52473. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52474. }
  52475. this.afterUpdateParticles(start, end, update);
  52476. return this;
  52477. };
  52478. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52479. this._halfroll = this._roll * 0.5;
  52480. this._halfpitch = this._pitch * 0.5;
  52481. this._halfyaw = this._yaw * 0.5;
  52482. this._sinRoll = Math.sin(this._halfroll);
  52483. this._cosRoll = Math.cos(this._halfroll);
  52484. this._sinPitch = Math.sin(this._halfpitch);
  52485. this._cosPitch = Math.cos(this._halfpitch);
  52486. this._sinYaw = Math.sin(this._halfyaw);
  52487. this._cosYaw = Math.cos(this._halfyaw);
  52488. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52489. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52490. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52491. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52492. };
  52493. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52494. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52495. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52496. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52497. this._rotMatrix.m[3] = 0;
  52498. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52499. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52500. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52501. this._rotMatrix.m[7] = 0;
  52502. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52503. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52504. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52505. this._rotMatrix.m[11] = 0;
  52506. this._rotMatrix.m[12] = 0;
  52507. this._rotMatrix.m[13] = 0;
  52508. this._rotMatrix.m[14] = 0;
  52509. this._rotMatrix.m[15] = 1.0;
  52510. };
  52511. /**
  52512. * Disposes the SPS.
  52513. */
  52514. SolidParticleSystem.prototype.dispose = function () {
  52515. this.mesh.dispose();
  52516. this.vars = null;
  52517. // drop references to internal big arrays for the GC
  52518. this._positions = null;
  52519. this._indices = null;
  52520. this._normals = null;
  52521. this._uvs = null;
  52522. this._colors = null;
  52523. this._indices32 = null;
  52524. this._positions32 = null;
  52525. this._normals32 = null;
  52526. this._fixedNormal32 = null;
  52527. this._uvs32 = null;
  52528. this._colors32 = null;
  52529. this.pickedParticles = null;
  52530. };
  52531. /**
  52532. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52533. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52534. * @returns the SPS.
  52535. */
  52536. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52537. if (!this._isVisibilityBoxLocked) {
  52538. this.mesh.refreshBoundingInfo();
  52539. }
  52540. return this;
  52541. };
  52542. /**
  52543. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52544. * @param size the size (float) of the visibility box
  52545. * note : this doesn't lock the SPS mesh bounding box.
  52546. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52547. */
  52548. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52549. var vis = size / 2;
  52550. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52551. };
  52552. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52553. /**
  52554. * Gets whether the SPS as always visible or not
  52555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52556. */
  52557. get: function () {
  52558. return this._alwaysVisible;
  52559. },
  52560. /**
  52561. * Sets the SPS as always visible or not
  52562. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52563. */
  52564. set: function (val) {
  52565. this._alwaysVisible = val;
  52566. this.mesh.alwaysSelectAsActiveMesh = val;
  52567. },
  52568. enumerable: true,
  52569. configurable: true
  52570. });
  52571. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52572. /**
  52573. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52574. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52575. */
  52576. get: function () {
  52577. return this._isVisibilityBoxLocked;
  52578. },
  52579. /**
  52580. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52581. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52582. */
  52583. set: function (val) {
  52584. this._isVisibilityBoxLocked = val;
  52585. var boundingInfo = this.mesh.getBoundingInfo();
  52586. boundingInfo.isLocked = val;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52592. /**
  52593. * Gets if `setParticles()` computes the particle rotations or not.
  52594. * Default value : true. The SPS is faster when it's set to false.
  52595. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52596. */
  52597. get: function () {
  52598. return this._computeParticleRotation;
  52599. },
  52600. /**
  52601. * Tells to `setParticles()` to compute the particle rotations or not.
  52602. * Default value : true. The SPS is faster when it's set to false.
  52603. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52604. */
  52605. set: function (val) {
  52606. this._computeParticleRotation = val;
  52607. },
  52608. enumerable: true,
  52609. configurable: true
  52610. });
  52611. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52612. /**
  52613. * Gets if `setParticles()` computes the particle colors or not.
  52614. * Default value : true. The SPS is faster when it's set to false.
  52615. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52616. */
  52617. get: function () {
  52618. return this._computeParticleColor;
  52619. },
  52620. /**
  52621. * Tells to `setParticles()` to compute the particle colors or not.
  52622. * Default value : true. The SPS is faster when it's set to false.
  52623. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52624. */
  52625. set: function (val) {
  52626. this._computeParticleColor = val;
  52627. },
  52628. enumerable: true,
  52629. configurable: true
  52630. });
  52631. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52632. /**
  52633. * Gets if `setParticles()` computes the particle textures or not.
  52634. * Default value : true. The SPS is faster when it's set to false.
  52635. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52636. */
  52637. get: function () {
  52638. return this._computeParticleTexture;
  52639. },
  52640. set: function (val) {
  52641. this._computeParticleTexture = val;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52647. /**
  52648. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52649. * Default value : false. The SPS is faster when it's set to false.
  52650. * Note : the particle custom vertex positions aren't stored values.
  52651. */
  52652. get: function () {
  52653. return this._computeParticleVertex;
  52654. },
  52655. /**
  52656. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52657. * Default value : false. The SPS is faster when it's set to false.
  52658. * Note : the particle custom vertex positions aren't stored values.
  52659. */
  52660. set: function (val) {
  52661. this._computeParticleVertex = val;
  52662. },
  52663. enumerable: true,
  52664. configurable: true
  52665. });
  52666. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52667. /**
  52668. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52669. */
  52670. get: function () {
  52671. return this._computeBoundingBox;
  52672. },
  52673. /**
  52674. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52675. */
  52676. set: function (val) {
  52677. this._computeBoundingBox = val;
  52678. },
  52679. enumerable: true,
  52680. configurable: true
  52681. });
  52682. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52683. /**
  52684. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52685. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52686. * Default : `true`
  52687. */
  52688. get: function () {
  52689. return this._depthSortParticles;
  52690. },
  52691. /**
  52692. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52693. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52694. * Default : `true`
  52695. */
  52696. set: function (val) {
  52697. this._depthSortParticles = val;
  52698. },
  52699. enumerable: true,
  52700. configurable: true
  52701. });
  52702. // =======================================================================
  52703. // Particle behavior logic
  52704. // these following methods may be overwritten by the user to fit his needs
  52705. /**
  52706. * This function does nothing. It may be overwritten to set all the particle first values.
  52707. * The SPS doesn't call this function, you may have to call it by your own.
  52708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52709. */
  52710. SolidParticleSystem.prototype.initParticles = function () {
  52711. };
  52712. /**
  52713. * This function does nothing. It may be overwritten to recycle a particle.
  52714. * The SPS doesn't call this function, you may have to call it by your own.
  52715. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52716. * @param particle The particle to recycle
  52717. * @returns the recycled particle
  52718. */
  52719. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52720. return particle;
  52721. };
  52722. /**
  52723. * Updates a particle : this function should be overwritten by the user.
  52724. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52725. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52726. * @example : just set a particle position or velocity and recycle conditions
  52727. * @param particle The particle to update
  52728. * @returns the updated particle
  52729. */
  52730. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52731. return particle;
  52732. };
  52733. /**
  52734. * Updates a vertex of a particle : it can be overwritten by the user.
  52735. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52736. * @param particle the current particle
  52737. * @param vertex the current index of the current particle
  52738. * @param pt the index of the current vertex in the particle shape
  52739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52740. * @example : just set a vertex particle position
  52741. * @returns the updated vertex
  52742. */
  52743. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52744. return vertex;
  52745. };
  52746. /**
  52747. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52748. * This does nothing and may be overwritten by the user.
  52749. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52750. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52751. * @param update the boolean update value actually passed to setParticles()
  52752. */
  52753. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52754. };
  52755. /**
  52756. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52757. * This will be passed three parameters.
  52758. * This does nothing and may be overwritten by the user.
  52759. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52760. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52761. * @param update the boolean update value actually passed to setParticles()
  52762. */
  52763. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52764. };
  52765. return SolidParticleSystem;
  52766. }());
  52767. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52768. })(BABYLON || (BABYLON = {}));
  52769. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52770. var BABYLON;
  52771. (function (BABYLON) {
  52772. var ShaderMaterial = /** @class */ (function (_super) {
  52773. __extends(ShaderMaterial, _super);
  52774. function ShaderMaterial(name, scene, shaderPath, options) {
  52775. var _this = _super.call(this, name, scene) || this;
  52776. _this._textures = {};
  52777. _this._textureArrays = {};
  52778. _this._floats = {};
  52779. _this._ints = {};
  52780. _this._floatsArrays = {};
  52781. _this._colors3 = {};
  52782. _this._colors3Arrays = {};
  52783. _this._colors4 = {};
  52784. _this._vectors2 = {};
  52785. _this._vectors3 = {};
  52786. _this._vectors4 = {};
  52787. _this._matrices = {};
  52788. _this._matrices3x3 = {};
  52789. _this._matrices2x2 = {};
  52790. _this._vectors2Arrays = {};
  52791. _this._vectors3Arrays = {};
  52792. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52793. _this._shaderPath = shaderPath;
  52794. options.needAlphaBlending = options.needAlphaBlending || false;
  52795. options.needAlphaTesting = options.needAlphaTesting || false;
  52796. options.attributes = options.attributes || ["position", "normal", "uv"];
  52797. options.uniforms = options.uniforms || ["worldViewProjection"];
  52798. options.uniformBuffers = options.uniformBuffers || [];
  52799. options.samplers = options.samplers || [];
  52800. options.defines = options.defines || [];
  52801. _this._options = options;
  52802. return _this;
  52803. }
  52804. ShaderMaterial.prototype.getClassName = function () {
  52805. return "ShaderMaterial";
  52806. };
  52807. ShaderMaterial.prototype.needAlphaBlending = function () {
  52808. return this._options.needAlphaBlending;
  52809. };
  52810. ShaderMaterial.prototype.needAlphaTesting = function () {
  52811. return this._options.needAlphaTesting;
  52812. };
  52813. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52814. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52815. this._options.uniforms.push(uniformName);
  52816. }
  52817. };
  52818. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52819. if (this._options.samplers.indexOf(name) === -1) {
  52820. this._options.samplers.push(name);
  52821. }
  52822. this._textures[name] = texture;
  52823. return this;
  52824. };
  52825. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52826. if (this._options.samplers.indexOf(name) === -1) {
  52827. this._options.samplers.push(name);
  52828. }
  52829. this._checkUniform(name);
  52830. this._textureArrays[name] = textures;
  52831. return this;
  52832. };
  52833. ShaderMaterial.prototype.setFloat = function (name, value) {
  52834. this._checkUniform(name);
  52835. this._floats[name] = value;
  52836. return this;
  52837. };
  52838. ShaderMaterial.prototype.setInt = function (name, value) {
  52839. this._checkUniform(name);
  52840. this._ints[name] = value;
  52841. return this;
  52842. };
  52843. ShaderMaterial.prototype.setFloats = function (name, value) {
  52844. this._checkUniform(name);
  52845. this._floatsArrays[name] = value;
  52846. return this;
  52847. };
  52848. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52849. this._checkUniform(name);
  52850. this._colors3[name] = value;
  52851. return this;
  52852. };
  52853. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52854. this._checkUniform(name);
  52855. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52856. color.toArray(arr, arr.length);
  52857. return arr;
  52858. }, []);
  52859. return this;
  52860. };
  52861. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52862. this._checkUniform(name);
  52863. this._colors4[name] = value;
  52864. return this;
  52865. };
  52866. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52867. this._checkUniform(name);
  52868. this._vectors2[name] = value;
  52869. return this;
  52870. };
  52871. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52872. this._checkUniform(name);
  52873. this._vectors3[name] = value;
  52874. return this;
  52875. };
  52876. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52877. this._checkUniform(name);
  52878. this._vectors4[name] = value;
  52879. return this;
  52880. };
  52881. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52882. this._checkUniform(name);
  52883. this._matrices[name] = value;
  52884. return this;
  52885. };
  52886. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52887. this._checkUniform(name);
  52888. this._matrices3x3[name] = value;
  52889. return this;
  52890. };
  52891. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52892. this._checkUniform(name);
  52893. this._matrices2x2[name] = value;
  52894. return this;
  52895. };
  52896. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52897. this._checkUniform(name);
  52898. this._vectors2Arrays[name] = value;
  52899. return this;
  52900. };
  52901. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52902. this._checkUniform(name);
  52903. this._vectors3Arrays[name] = value;
  52904. return this;
  52905. };
  52906. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52907. if (!mesh) {
  52908. return true;
  52909. }
  52910. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52911. return false;
  52912. }
  52913. return false;
  52914. };
  52915. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52916. var scene = this.getScene();
  52917. var engine = scene.getEngine();
  52918. if (!this.checkReadyOnEveryCall) {
  52919. if (this._renderId === scene.getRenderId()) {
  52920. if (this._checkCache(scene, mesh, useInstances)) {
  52921. return true;
  52922. }
  52923. }
  52924. }
  52925. // Instances
  52926. var defines = [];
  52927. var attribs = [];
  52928. var fallbacks = new BABYLON.EffectFallbacks();
  52929. if (useInstances) {
  52930. defines.push("#define INSTANCES");
  52931. }
  52932. for (var index = 0; index < this._options.defines.length; index++) {
  52933. defines.push(this._options.defines[index]);
  52934. }
  52935. for (var index = 0; index < this._options.attributes.length; index++) {
  52936. attribs.push(this._options.attributes[index]);
  52937. }
  52938. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52939. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52940. defines.push("#define VERTEXCOLOR");
  52941. }
  52942. // Bones
  52943. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52946. if (mesh.numBoneInfluencers > 4) {
  52947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52949. }
  52950. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52951. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52952. fallbacks.addCPUSkinningFallback(0, mesh);
  52953. if (this._options.uniforms.indexOf("mBones") === -1) {
  52954. this._options.uniforms.push("mBones");
  52955. }
  52956. }
  52957. else {
  52958. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52959. }
  52960. // Textures
  52961. for (var name in this._textures) {
  52962. if (!this._textures[name].isReady()) {
  52963. return false;
  52964. }
  52965. }
  52966. // Alpha test
  52967. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52968. defines.push("#define ALPHATEST");
  52969. }
  52970. var previousEffect = this._effect;
  52971. var join = defines.join("\n");
  52972. this._effect = engine.createEffect(this._shaderPath, {
  52973. attributes: attribs,
  52974. uniformsNames: this._options.uniforms,
  52975. uniformBuffersNames: this._options.uniformBuffers,
  52976. samplers: this._options.samplers,
  52977. defines: join,
  52978. fallbacks: fallbacks,
  52979. onCompiled: this.onCompiled,
  52980. onError: this.onError
  52981. }, engine);
  52982. if (!this._effect.isReady()) {
  52983. return false;
  52984. }
  52985. if (previousEffect !== this._effect) {
  52986. scene.resetCachedMaterial();
  52987. }
  52988. this._renderId = scene.getRenderId();
  52989. return true;
  52990. };
  52991. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52992. var scene = this.getScene();
  52993. if (!this._effect) {
  52994. return;
  52995. }
  52996. if (this._options.uniforms.indexOf("world") !== -1) {
  52997. this._effect.setMatrix("world", world);
  52998. }
  52999. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53000. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53001. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53002. }
  53003. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53004. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53005. }
  53006. };
  53007. ShaderMaterial.prototype.bind = function (world, mesh) {
  53008. // Std values
  53009. this.bindOnlyWorldMatrix(world);
  53010. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53011. if (this._options.uniforms.indexOf("view") !== -1) {
  53012. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53013. }
  53014. if (this._options.uniforms.indexOf("projection") !== -1) {
  53015. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53016. }
  53017. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53018. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53019. }
  53020. // Bones
  53021. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53022. var name;
  53023. // Texture
  53024. for (name in this._textures) {
  53025. this._effect.setTexture(name, this._textures[name]);
  53026. }
  53027. // Texture arrays
  53028. for (name in this._textureArrays) {
  53029. this._effect.setTextureArray(name, this._textureArrays[name]);
  53030. }
  53031. // Int
  53032. for (name in this._ints) {
  53033. this._effect.setInt(name, this._ints[name]);
  53034. }
  53035. // Float
  53036. for (name in this._floats) {
  53037. this._effect.setFloat(name, this._floats[name]);
  53038. }
  53039. // Floats
  53040. for (name in this._floatsArrays) {
  53041. this._effect.setArray(name, this._floatsArrays[name]);
  53042. }
  53043. // Color3
  53044. for (name in this._colors3) {
  53045. this._effect.setColor3(name, this._colors3[name]);
  53046. }
  53047. for (name in this._colors3Arrays) {
  53048. this._effect.setArray3(name, this._colors3Arrays[name]);
  53049. }
  53050. // Color4
  53051. for (name in this._colors4) {
  53052. var color = this._colors4[name];
  53053. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53054. }
  53055. // Vector2
  53056. for (name in this._vectors2) {
  53057. this._effect.setVector2(name, this._vectors2[name]);
  53058. }
  53059. // Vector3
  53060. for (name in this._vectors3) {
  53061. this._effect.setVector3(name, this._vectors3[name]);
  53062. }
  53063. // Vector4
  53064. for (name in this._vectors4) {
  53065. this._effect.setVector4(name, this._vectors4[name]);
  53066. }
  53067. // Matrix
  53068. for (name in this._matrices) {
  53069. this._effect.setMatrix(name, this._matrices[name]);
  53070. }
  53071. // Matrix 3x3
  53072. for (name in this._matrices3x3) {
  53073. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53074. }
  53075. // Matrix 2x2
  53076. for (name in this._matrices2x2) {
  53077. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53078. }
  53079. // Vector2Array
  53080. for (name in this._vectors2Arrays) {
  53081. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53082. }
  53083. // Vector3Array
  53084. for (name in this._vectors3Arrays) {
  53085. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53086. }
  53087. }
  53088. this._afterBind(mesh);
  53089. };
  53090. ShaderMaterial.prototype.getActiveTextures = function () {
  53091. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53092. for (var name in this._textures) {
  53093. activeTextures.push(this._textures[name]);
  53094. }
  53095. for (var name in this._textureArrays) {
  53096. var array = this._textureArrays[name];
  53097. for (var index = 0; index < array.length; index++) {
  53098. activeTextures.push(array[index]);
  53099. }
  53100. }
  53101. return activeTextures;
  53102. };
  53103. ShaderMaterial.prototype.hasTexture = function (texture) {
  53104. if (_super.prototype.hasTexture.call(this, texture)) {
  53105. return true;
  53106. }
  53107. for (var name in this._textures) {
  53108. if (this._textures[name] === texture) {
  53109. return true;
  53110. }
  53111. }
  53112. for (var name in this._textureArrays) {
  53113. var array = this._textureArrays[name];
  53114. for (var index = 0; index < array.length; index++) {
  53115. if (array[index] === texture) {
  53116. return true;
  53117. }
  53118. }
  53119. }
  53120. return false;
  53121. };
  53122. ShaderMaterial.prototype.clone = function (name) {
  53123. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53124. return newShaderMaterial;
  53125. };
  53126. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53127. if (forceDisposeTextures) {
  53128. var name;
  53129. for (name in this._textures) {
  53130. this._textures[name].dispose();
  53131. }
  53132. for (name in this._textureArrays) {
  53133. var array = this._textureArrays[name];
  53134. for (var index = 0; index < array.length; index++) {
  53135. array[index].dispose();
  53136. }
  53137. }
  53138. }
  53139. this._textures = {};
  53140. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53141. };
  53142. ShaderMaterial.prototype.serialize = function () {
  53143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53144. serializationObject.customType = "BABYLON.ShaderMaterial";
  53145. serializationObject.options = this._options;
  53146. serializationObject.shaderPath = this._shaderPath;
  53147. var name;
  53148. // Texture
  53149. serializationObject.textures = {};
  53150. for (name in this._textures) {
  53151. serializationObject.textures[name] = this._textures[name].serialize();
  53152. }
  53153. // Texture arrays
  53154. serializationObject.textureArrays = {};
  53155. for (name in this._textureArrays) {
  53156. serializationObject.textureArrays[name] = [];
  53157. var array = this._textureArrays[name];
  53158. for (var index = 0; index < array.length; index++) {
  53159. serializationObject.textureArrays[name].push(array[index].serialize());
  53160. }
  53161. }
  53162. // Float
  53163. serializationObject.floats = {};
  53164. for (name in this._floats) {
  53165. serializationObject.floats[name] = this._floats[name];
  53166. }
  53167. // Float s
  53168. serializationObject.FloatArrays = {};
  53169. for (name in this._floatsArrays) {
  53170. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53171. }
  53172. // Color3
  53173. serializationObject.colors3 = {};
  53174. for (name in this._colors3) {
  53175. serializationObject.colors3[name] = this._colors3[name].asArray();
  53176. }
  53177. // Color3 array
  53178. serializationObject.colors3Arrays = {};
  53179. for (name in this._colors3Arrays) {
  53180. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53181. }
  53182. // Color4
  53183. serializationObject.colors4 = {};
  53184. for (name in this._colors4) {
  53185. serializationObject.colors4[name] = this._colors4[name].asArray();
  53186. }
  53187. // Vector2
  53188. serializationObject.vectors2 = {};
  53189. for (name in this._vectors2) {
  53190. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53191. }
  53192. // Vector3
  53193. serializationObject.vectors3 = {};
  53194. for (name in this._vectors3) {
  53195. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53196. }
  53197. // Vector4
  53198. serializationObject.vectors4 = {};
  53199. for (name in this._vectors4) {
  53200. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53201. }
  53202. // Matrix
  53203. serializationObject.matrices = {};
  53204. for (name in this._matrices) {
  53205. serializationObject.matrices[name] = this._matrices[name].asArray();
  53206. }
  53207. // Matrix 3x3
  53208. serializationObject.matrices3x3 = {};
  53209. for (name in this._matrices3x3) {
  53210. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53211. }
  53212. // Matrix 2x2
  53213. serializationObject.matrices2x2 = {};
  53214. for (name in this._matrices2x2) {
  53215. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53216. }
  53217. // Vector2Array
  53218. serializationObject.vectors2Arrays = {};
  53219. for (name in this._vectors2Arrays) {
  53220. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53221. }
  53222. // Vector3Array
  53223. serializationObject.vectors3Arrays = {};
  53224. for (name in this._vectors3Arrays) {
  53225. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53226. }
  53227. return serializationObject;
  53228. };
  53229. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53230. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53231. var name;
  53232. // Texture
  53233. for (name in source.textures) {
  53234. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53235. }
  53236. // Texture arrays
  53237. for (name in source.textureArrays) {
  53238. var array = source.textureArrays[name];
  53239. var textureArray = new Array();
  53240. for (var index = 0; index < array.length; index++) {
  53241. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53242. }
  53243. material.setTextureArray(name, textureArray);
  53244. }
  53245. // Float
  53246. for (name in source.floats) {
  53247. material.setFloat(name, source.floats[name]);
  53248. }
  53249. // Float s
  53250. for (name in source.floatsArrays) {
  53251. material.setFloats(name, source.floatsArrays[name]);
  53252. }
  53253. // Color3
  53254. for (name in source.colors3) {
  53255. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53256. }
  53257. // Color3 arrays
  53258. for (name in source.colors3Arrays) {
  53259. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53260. if (i % 3 === 0) {
  53261. arr.push([num]);
  53262. }
  53263. else {
  53264. arr[arr.length - 1].push(num);
  53265. }
  53266. return arr;
  53267. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53268. material.setColor3Array(name, colors);
  53269. }
  53270. // Color4
  53271. for (name in source.colors4) {
  53272. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53273. }
  53274. // Vector2
  53275. for (name in source.vectors2) {
  53276. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53277. }
  53278. // Vector3
  53279. for (name in source.vectors3) {
  53280. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53281. }
  53282. // Vector4
  53283. for (name in source.vectors4) {
  53284. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53285. }
  53286. // Matrix
  53287. for (name in source.matrices) {
  53288. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53289. }
  53290. // Matrix 3x3
  53291. for (name in source.matrices3x3) {
  53292. material.setMatrix3x3(name, source.matrices3x3[name]);
  53293. }
  53294. // Matrix 2x2
  53295. for (name in source.matrices2x2) {
  53296. material.setMatrix2x2(name, source.matrices2x2[name]);
  53297. }
  53298. // Vector2Array
  53299. for (name in source.vectors2Arrays) {
  53300. material.setArray2(name, source.vectors2Arrays[name]);
  53301. }
  53302. // Vector3Array
  53303. for (name in source.vectors3Arrays) {
  53304. material.setArray3(name, source.vectors3Arrays[name]);
  53305. }
  53306. return material;
  53307. };
  53308. return ShaderMaterial;
  53309. }(BABYLON.Material));
  53310. BABYLON.ShaderMaterial = ShaderMaterial;
  53311. })(BABYLON || (BABYLON = {}));
  53312. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53313. var BABYLON;
  53314. (function (BABYLON) {
  53315. var GroundMesh = /** @class */ (function (_super) {
  53316. __extends(GroundMesh, _super);
  53317. function GroundMesh(name, scene) {
  53318. var _this = _super.call(this, name, scene) || this;
  53319. _this.generateOctree = false;
  53320. return _this;
  53321. }
  53322. GroundMesh.prototype.getClassName = function () {
  53323. return "GroundMesh";
  53324. };
  53325. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53326. get: function () {
  53327. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53333. get: function () {
  53334. return this._subdivisionsX;
  53335. },
  53336. enumerable: true,
  53337. configurable: true
  53338. });
  53339. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53340. get: function () {
  53341. return this._subdivisionsY;
  53342. },
  53343. enumerable: true,
  53344. configurable: true
  53345. });
  53346. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53347. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53348. this._subdivisionsX = chunksCount;
  53349. this._subdivisionsY = chunksCount;
  53350. this.subdivide(chunksCount);
  53351. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53352. };
  53353. /**
  53354. * Returns a height (y) value in the Worl system :
  53355. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53356. * Returns the ground y position if (x, z) are outside the ground surface.
  53357. */
  53358. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53359. var world = this.getWorldMatrix();
  53360. var invMat = BABYLON.Tmp.Matrix[5];
  53361. world.invertToRef(invMat);
  53362. var tmpVect = BABYLON.Tmp.Vector3[8];
  53363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53364. x = tmpVect.x;
  53365. z = tmpVect.z;
  53366. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53367. return this.position.y;
  53368. }
  53369. if (!this._heightQuads || this._heightQuads.length == 0) {
  53370. this._initHeightQuads();
  53371. this._computeHeightQuads();
  53372. }
  53373. var facet = this._getFacetAt(x, z);
  53374. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53375. // return y in the World system
  53376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53377. return tmpVect.y;
  53378. };
  53379. /**
  53380. * Returns a normalized vector (Vector3) orthogonal to the ground
  53381. * at the ground coordinates (x, z) expressed in the World system.
  53382. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53383. */
  53384. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53385. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53386. this.getNormalAtCoordinatesToRef(x, z, normal);
  53387. return normal;
  53388. };
  53389. /**
  53390. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53391. * at the ground coordinates (x, z) expressed in the World system.
  53392. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53393. * Returns the GroundMesh.
  53394. */
  53395. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53396. var world = this.getWorldMatrix();
  53397. var tmpMat = BABYLON.Tmp.Matrix[5];
  53398. world.invertToRef(tmpMat);
  53399. var tmpVect = BABYLON.Tmp.Vector3[8];
  53400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53401. x = tmpVect.x;
  53402. z = tmpVect.z;
  53403. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53404. return this;
  53405. }
  53406. if (!this._heightQuads || this._heightQuads.length == 0) {
  53407. this._initHeightQuads();
  53408. this._computeHeightQuads();
  53409. }
  53410. var facet = this._getFacetAt(x, z);
  53411. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53412. return this;
  53413. };
  53414. /**
  53415. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53416. * if the ground has been updated.
  53417. * This can be used in the render loop.
  53418. * Returns the GroundMesh.
  53419. */
  53420. GroundMesh.prototype.updateCoordinateHeights = function () {
  53421. if (!this._heightQuads || this._heightQuads.length == 0) {
  53422. this._initHeightQuads();
  53423. }
  53424. this._computeHeightQuads();
  53425. return this;
  53426. };
  53427. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53428. GroundMesh.prototype._getFacetAt = function (x, z) {
  53429. // retrieve col and row from x, z coordinates in the ground local system
  53430. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53431. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53432. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53433. var facet;
  53434. if (z < quad.slope.x * x + quad.slope.y) {
  53435. facet = quad.facet1;
  53436. }
  53437. else {
  53438. facet = quad.facet2;
  53439. }
  53440. return facet;
  53441. };
  53442. // Creates and populates the heightMap array with "facet" elements :
  53443. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53444. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53445. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53446. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53447. // Returns the GroundMesh.
  53448. GroundMesh.prototype._initHeightQuads = function () {
  53449. var subdivisionsX = this._subdivisionsX;
  53450. var subdivisionsY = this._subdivisionsY;
  53451. this._heightQuads = new Array();
  53452. for (var row = 0; row < subdivisionsY; row++) {
  53453. for (var col = 0; col < subdivisionsX; col++) {
  53454. 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) };
  53455. this._heightQuads[row * subdivisionsX + col] = quad;
  53456. }
  53457. }
  53458. return this;
  53459. };
  53460. // Compute each quad element values and update the the heightMap array :
  53461. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53462. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53463. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53464. // Returns the GroundMesh.
  53465. GroundMesh.prototype._computeHeightQuads = function () {
  53466. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53467. if (!positions) {
  53468. return this;
  53469. }
  53470. var v1 = BABYLON.Tmp.Vector3[3];
  53471. var v2 = BABYLON.Tmp.Vector3[2];
  53472. var v3 = BABYLON.Tmp.Vector3[1];
  53473. var v4 = BABYLON.Tmp.Vector3[0];
  53474. var v1v2 = BABYLON.Tmp.Vector3[4];
  53475. var v1v3 = BABYLON.Tmp.Vector3[5];
  53476. var v1v4 = BABYLON.Tmp.Vector3[6];
  53477. var norm1 = BABYLON.Tmp.Vector3[7];
  53478. var norm2 = BABYLON.Tmp.Vector3[8];
  53479. var i = 0;
  53480. var j = 0;
  53481. var k = 0;
  53482. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53483. var h = 0;
  53484. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53485. var d2 = 0;
  53486. var subdivisionsX = this._subdivisionsX;
  53487. var subdivisionsY = this._subdivisionsY;
  53488. for (var row = 0; row < subdivisionsY; row++) {
  53489. for (var col = 0; col < subdivisionsX; col++) {
  53490. i = col * 3;
  53491. j = row * (subdivisionsX + 1) * 3;
  53492. k = (row + 1) * (subdivisionsX + 1) * 3;
  53493. v1.x = positions[j + i];
  53494. v1.y = positions[j + i + 1];
  53495. v1.z = positions[j + i + 2];
  53496. v2.x = positions[j + i + 3];
  53497. v2.y = positions[j + i + 4];
  53498. v2.z = positions[j + i + 5];
  53499. v3.x = positions[k + i];
  53500. v3.y = positions[k + i + 1];
  53501. v3.z = positions[k + i + 2];
  53502. v4.x = positions[k + i + 3];
  53503. v4.y = positions[k + i + 4];
  53504. v4.z = positions[k + i + 5];
  53505. // 2D slope V1V4
  53506. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53507. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53508. // facet equations :
  53509. // we compute each facet normal vector
  53510. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53511. // we compute the value d by applying the equation to v1 which belongs to the plane
  53512. // then we store the facet equation in a Vector4
  53513. v2.subtractToRef(v1, v1v2);
  53514. v3.subtractToRef(v1, v1v3);
  53515. v4.subtractToRef(v1, v1v4);
  53516. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53517. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53518. norm1.normalize();
  53519. norm2.normalize();
  53520. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53521. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53522. var quad = this._heightQuads[row * subdivisionsX + col];
  53523. quad.slope.copyFromFloats(cd, h);
  53524. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53525. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53526. }
  53527. }
  53528. return this;
  53529. };
  53530. GroundMesh.prototype.serialize = function (serializationObject) {
  53531. _super.prototype.serialize.call(this, serializationObject);
  53532. serializationObject.subdivisionsX = this._subdivisionsX;
  53533. serializationObject.subdivisionsY = this._subdivisionsY;
  53534. serializationObject.minX = this._minX;
  53535. serializationObject.maxX = this._maxX;
  53536. serializationObject.minZ = this._minZ;
  53537. serializationObject.maxZ = this._maxZ;
  53538. serializationObject.width = this._width;
  53539. serializationObject.height = this._height;
  53540. };
  53541. GroundMesh.Parse = function (parsedMesh, scene) {
  53542. var result = new GroundMesh(parsedMesh.name, scene);
  53543. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53544. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53545. result._minX = parsedMesh.minX;
  53546. result._maxX = parsedMesh.maxX;
  53547. result._minZ = parsedMesh.minZ;
  53548. result._maxZ = parsedMesh.maxZ;
  53549. result._width = parsedMesh.width;
  53550. result._height = parsedMesh.height;
  53551. return result;
  53552. };
  53553. return GroundMesh;
  53554. }(BABYLON.Mesh));
  53555. BABYLON.GroundMesh = GroundMesh;
  53556. })(BABYLON || (BABYLON = {}));
  53557. //# sourceMappingURL=babylon.groundMesh.js.map
  53558. var BABYLON;
  53559. (function (BABYLON) {
  53560. /**
  53561. * Creates an instance based on a source mesh.
  53562. */
  53563. var InstancedMesh = /** @class */ (function (_super) {
  53564. __extends(InstancedMesh, _super);
  53565. function InstancedMesh(name, source) {
  53566. var _this = _super.call(this, name, source.getScene()) || this;
  53567. source.instances.push(_this);
  53568. _this._sourceMesh = source;
  53569. _this.position.copyFrom(source.position);
  53570. _this.rotation.copyFrom(source.rotation);
  53571. _this.scaling.copyFrom(source.scaling);
  53572. if (source.rotationQuaternion) {
  53573. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53574. }
  53575. _this.infiniteDistance = source.infiniteDistance;
  53576. _this.setPivotMatrix(source.getPivotMatrix());
  53577. _this.refreshBoundingInfo();
  53578. _this._syncSubMeshes();
  53579. return _this;
  53580. }
  53581. /**
  53582. * Returns the string "InstancedMesh".
  53583. */
  53584. InstancedMesh.prototype.getClassName = function () {
  53585. return "InstancedMesh";
  53586. };
  53587. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53588. // Methods
  53589. get: function () {
  53590. return this._sourceMesh.receiveShadows;
  53591. },
  53592. enumerable: true,
  53593. configurable: true
  53594. });
  53595. Object.defineProperty(InstancedMesh.prototype, "material", {
  53596. get: function () {
  53597. return this._sourceMesh.material;
  53598. },
  53599. enumerable: true,
  53600. configurable: true
  53601. });
  53602. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53603. get: function () {
  53604. return this._sourceMesh.visibility;
  53605. },
  53606. enumerable: true,
  53607. configurable: true
  53608. });
  53609. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53610. get: function () {
  53611. return this._sourceMesh.skeleton;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53617. get: function () {
  53618. return this._sourceMesh.renderingGroupId;
  53619. },
  53620. enumerable: true,
  53621. configurable: true
  53622. });
  53623. /**
  53624. * Returns the total number of vertices (integer).
  53625. */
  53626. InstancedMesh.prototype.getTotalVertices = function () {
  53627. return this._sourceMesh.getTotalVertices();
  53628. };
  53629. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53630. get: function () {
  53631. return this._sourceMesh;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. /**
  53637. * Is this node ready to be used/rendered
  53638. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  53639. * @return {boolean} is it ready
  53640. */
  53641. InstancedMesh.prototype.isReady = function (completeCheck) {
  53642. if (completeCheck === void 0) { completeCheck = false; }
  53643. return this._sourceMesh.isReady(completeCheck, true);
  53644. };
  53645. /**
  53646. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53647. */
  53648. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53649. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53650. };
  53651. /**
  53652. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53653. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53654. * The `data` are either a numeric array either a Float32Array.
  53655. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53656. * 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).
  53657. * Note that a new underlying VertexBuffer object is created each call.
  53658. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53659. *
  53660. * Possible `kind` values :
  53661. * - BABYLON.VertexBuffer.PositionKind
  53662. * - BABYLON.VertexBuffer.UVKind
  53663. * - BABYLON.VertexBuffer.UV2Kind
  53664. * - BABYLON.VertexBuffer.UV3Kind
  53665. * - BABYLON.VertexBuffer.UV4Kind
  53666. * - BABYLON.VertexBuffer.UV5Kind
  53667. * - BABYLON.VertexBuffer.UV6Kind
  53668. * - BABYLON.VertexBuffer.ColorKind
  53669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53673. *
  53674. * Returns the Mesh.
  53675. */
  53676. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53677. if (this.sourceMesh) {
  53678. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53679. }
  53680. return this.sourceMesh;
  53681. };
  53682. /**
  53683. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53684. * If the mesh has no geometry, it is simply returned as it is.
  53685. * The `data` are either a numeric array either a Float32Array.
  53686. * No new underlying VertexBuffer object is created.
  53687. * 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.
  53688. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53689. *
  53690. * Possible `kind` values :
  53691. * - BABYLON.VertexBuffer.PositionKind
  53692. * - BABYLON.VertexBuffer.UVKind
  53693. * - BABYLON.VertexBuffer.UV2Kind
  53694. * - BABYLON.VertexBuffer.UV3Kind
  53695. * - BABYLON.VertexBuffer.UV4Kind
  53696. * - BABYLON.VertexBuffer.UV5Kind
  53697. * - BABYLON.VertexBuffer.UV6Kind
  53698. * - BABYLON.VertexBuffer.ColorKind
  53699. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53700. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53701. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53702. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53703. *
  53704. * Returns the Mesh.
  53705. */
  53706. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53707. if (this.sourceMesh) {
  53708. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53709. }
  53710. return this.sourceMesh;
  53711. };
  53712. /**
  53713. * Sets the mesh indices.
  53714. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53715. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53716. * This method creates a new index buffer each call.
  53717. * Returns the Mesh.
  53718. */
  53719. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53720. if (totalVertices === void 0) { totalVertices = null; }
  53721. if (this.sourceMesh) {
  53722. this.sourceMesh.setIndices(indices, totalVertices);
  53723. }
  53724. return this.sourceMesh;
  53725. };
  53726. /**
  53727. * Boolean : True if the mesh owns the requested kind of data.
  53728. */
  53729. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53730. return this._sourceMesh.isVerticesDataPresent(kind);
  53731. };
  53732. /**
  53733. * Returns an array of indices (IndicesArray).
  53734. */
  53735. InstancedMesh.prototype.getIndices = function () {
  53736. return this._sourceMesh.getIndices();
  53737. };
  53738. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53739. get: function () {
  53740. return this._sourceMesh._positions;
  53741. },
  53742. enumerable: true,
  53743. configurable: true
  53744. });
  53745. /**
  53746. * Sets a new updated BoundingInfo to the mesh.
  53747. * Returns the mesh.
  53748. */
  53749. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53750. var meshBB = this._sourceMesh.getBoundingInfo();
  53751. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53752. this._updateBoundingInfo();
  53753. return this;
  53754. };
  53755. InstancedMesh.prototype._preActivate = function () {
  53756. if (this._currentLOD) {
  53757. this._currentLOD._preActivate();
  53758. }
  53759. return this;
  53760. };
  53761. InstancedMesh.prototype._activate = function (renderId) {
  53762. if (this._currentLOD) {
  53763. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53764. }
  53765. return this;
  53766. };
  53767. /**
  53768. * Returns the current associated LOD AbstractMesh.
  53769. */
  53770. InstancedMesh.prototype.getLOD = function (camera) {
  53771. if (!camera) {
  53772. return this;
  53773. }
  53774. var boundingInfo = this.getBoundingInfo();
  53775. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53776. if (this._currentLOD === this.sourceMesh) {
  53777. return this;
  53778. }
  53779. return this._currentLOD;
  53780. };
  53781. InstancedMesh.prototype._syncSubMeshes = function () {
  53782. this.releaseSubMeshes();
  53783. if (this._sourceMesh.subMeshes) {
  53784. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53785. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53786. }
  53787. }
  53788. return this;
  53789. };
  53790. InstancedMesh.prototype._generatePointsArray = function () {
  53791. return this._sourceMesh._generatePointsArray();
  53792. };
  53793. /**
  53794. * Creates a new InstancedMesh from the current mesh.
  53795. * - name (string) : the cloned mesh name
  53796. * - newParent (optional Node) : the optional Node to parent the clone to.
  53797. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53798. *
  53799. * Returns the clone.
  53800. */
  53801. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53802. var result = this._sourceMesh.createInstance(name);
  53803. // Deep copy
  53804. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53805. // Bounding info
  53806. this.refreshBoundingInfo();
  53807. // Parent
  53808. if (newParent) {
  53809. result.parent = newParent;
  53810. }
  53811. if (!doNotCloneChildren) {
  53812. // Children
  53813. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53814. var mesh = this.getScene().meshes[index];
  53815. if (mesh.parent === this) {
  53816. mesh.clone(mesh.name, result);
  53817. }
  53818. }
  53819. }
  53820. result.computeWorldMatrix(true);
  53821. return result;
  53822. };
  53823. /**
  53824. * Disposes the InstancedMesh.
  53825. * Returns nothing.
  53826. */
  53827. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53828. // Remove from mesh
  53829. var index = this._sourceMesh.instances.indexOf(this);
  53830. this._sourceMesh.instances.splice(index, 1);
  53831. _super.prototype.dispose.call(this, doNotRecurse);
  53832. };
  53833. return InstancedMesh;
  53834. }(BABYLON.AbstractMesh));
  53835. BABYLON.InstancedMesh = InstancedMesh;
  53836. })(BABYLON || (BABYLON = {}));
  53837. //# sourceMappingURL=babylon.instancedMesh.js.map
  53838. var BABYLON;
  53839. (function (BABYLON) {
  53840. var LinesMesh = /** @class */ (function (_super) {
  53841. __extends(LinesMesh, _super);
  53842. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53843. if (scene === void 0) { scene = null; }
  53844. if (parent === void 0) { parent = null; }
  53845. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53846. _this.useVertexColor = useVertexColor;
  53847. _this.useVertexAlpha = useVertexAlpha;
  53848. _this.color = new BABYLON.Color3(1, 1, 1);
  53849. _this.alpha = 1;
  53850. if (source) {
  53851. _this.color = source.color.clone();
  53852. _this.alpha = source.alpha;
  53853. _this.useVertexColor = source.useVertexColor;
  53854. _this.useVertexAlpha = source.useVertexAlpha;
  53855. }
  53856. _this._intersectionThreshold = 0.1;
  53857. var defines = [];
  53858. var options = {
  53859. attributes: [BABYLON.VertexBuffer.PositionKind],
  53860. uniforms: ["world", "viewProjection"],
  53861. needAlphaBlending: true,
  53862. defines: defines
  53863. };
  53864. if (useVertexAlpha === false) {
  53865. options.needAlphaBlending = false;
  53866. }
  53867. if (!useVertexColor) {
  53868. options.uniforms.push("color");
  53869. }
  53870. else {
  53871. options.defines.push("#define VERTEXCOLOR");
  53872. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53873. }
  53874. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53875. return _this;
  53876. }
  53877. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53878. /**
  53879. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53880. * This margin is expressed in world space coordinates, so its value may vary.
  53881. * Default value is 0.1
  53882. * @returns the intersection Threshold value.
  53883. */
  53884. get: function () {
  53885. return this._intersectionThreshold;
  53886. },
  53887. /**
  53888. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53889. * This margin is expressed in world space coordinates, so its value may vary.
  53890. * @param value the new threshold to apply
  53891. */
  53892. set: function (value) {
  53893. if (this._intersectionThreshold === value) {
  53894. return;
  53895. }
  53896. this._intersectionThreshold = value;
  53897. if (this.geometry) {
  53898. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53899. }
  53900. },
  53901. enumerable: true,
  53902. configurable: true
  53903. });
  53904. /**
  53905. * Returns the string "LineMesh"
  53906. */
  53907. LinesMesh.prototype.getClassName = function () {
  53908. return "LinesMesh";
  53909. };
  53910. Object.defineProperty(LinesMesh.prototype, "material", {
  53911. get: function () {
  53912. return this._colorShader;
  53913. },
  53914. set: function (value) {
  53915. // Do nothing
  53916. },
  53917. enumerable: true,
  53918. configurable: true
  53919. });
  53920. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53921. get: function () {
  53922. return false;
  53923. },
  53924. enumerable: true,
  53925. configurable: true
  53926. });
  53927. LinesMesh.prototype.createInstance = function (name) {
  53928. throw new Error("LinesMeshes do not support createInstance.");
  53929. };
  53930. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53931. if (!this._geometry) {
  53932. return this;
  53933. }
  53934. // VBOs
  53935. this._geometry._bind(this._colorShader.getEffect());
  53936. // Color
  53937. if (!this.useVertexColor) {
  53938. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53939. }
  53940. return this;
  53941. };
  53942. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53943. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53944. return this;
  53945. }
  53946. var engine = this.getScene().getEngine();
  53947. // Draw order
  53948. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53949. return this;
  53950. };
  53951. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53952. this._colorShader.dispose();
  53953. _super.prototype.dispose.call(this, doNotRecurse);
  53954. };
  53955. /**
  53956. * Returns a new LineMesh object cloned from the current one.
  53957. */
  53958. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53959. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53960. };
  53961. return LinesMesh;
  53962. }(BABYLON.Mesh));
  53963. BABYLON.LinesMesh = LinesMesh;
  53964. })(BABYLON || (BABYLON = {}));
  53965. //# sourceMappingURL=babylon.linesMesh.js.map
  53966. var BABYLON;
  53967. (function (BABYLON) {
  53968. var MeshBuilder = /** @class */ (function () {
  53969. function MeshBuilder() {
  53970. }
  53971. MeshBuilder.updateSideOrientation = function (orientation) {
  53972. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53973. return BABYLON.Mesh.DOUBLESIDE;
  53974. }
  53975. if (orientation === undefined || orientation === null) {
  53976. return BABYLON.Mesh.FRONTSIDE;
  53977. }
  53978. return orientation;
  53979. };
  53980. /**
  53981. * Creates a box mesh.
  53982. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53983. * The parameter `size` sets the size (float) of each box side (default 1).
  53984. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53985. * 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).
  53986. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53988. * 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).
  53989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53991. */
  53992. MeshBuilder.CreateBox = function (name, options, scene) {
  53993. if (scene === void 0) { scene = null; }
  53994. var box = new BABYLON.Mesh(name, scene);
  53995. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53996. box._originalBuilderSideOrientation = options.sideOrientation;
  53997. var vertexData = BABYLON.VertexData.CreateBox(options);
  53998. vertexData.applyToMesh(box, options.updatable);
  53999. return box;
  54000. };
  54001. /**
  54002. * Creates a sphere mesh.
  54003. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54004. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54005. * 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`).
  54006. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54007. * 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
  54008. * 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).
  54009. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54010. * 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).
  54011. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54013. */
  54014. MeshBuilder.CreateSphere = function (name, options, scene) {
  54015. var sphere = new BABYLON.Mesh(name, scene);
  54016. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54017. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54018. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54019. vertexData.applyToMesh(sphere, options.updatable);
  54020. return sphere;
  54021. };
  54022. /**
  54023. * Creates a plane polygonal mesh. By default, this is a disc.
  54024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54025. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54026. * 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.
  54027. * 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
  54028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54029. * 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).
  54030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54032. */
  54033. MeshBuilder.CreateDisc = function (name, options, scene) {
  54034. if (scene === void 0) { scene = null; }
  54035. var disc = new BABYLON.Mesh(name, scene);
  54036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54037. disc._originalBuilderSideOrientation = options.sideOrientation;
  54038. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54039. vertexData.applyToMesh(disc, options.updatable);
  54040. return disc;
  54041. };
  54042. /**
  54043. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54044. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54045. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54046. * 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`).
  54047. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54048. * 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.
  54049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54050. * 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).
  54051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54053. */
  54054. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54055. var sphere = new BABYLON.Mesh(name, scene);
  54056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54057. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54058. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54059. vertexData.applyToMesh(sphere, options.updatable);
  54060. return sphere;
  54061. };
  54062. ;
  54063. /**
  54064. * Creates a ribbon mesh.
  54065. * 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.
  54066. *
  54067. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54068. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54069. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54070. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54071. * 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.
  54072. * 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.
  54073. * 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
  54074. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54075. * 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).
  54076. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54077. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54078. * 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.
  54079. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54080. * 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
  54081. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54082. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54084. */
  54085. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54086. if (scene === void 0) { scene = null; }
  54087. var pathArray = options.pathArray;
  54088. var closeArray = options.closeArray;
  54089. var closePath = options.closePath;
  54090. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54091. var instance = options.instance;
  54092. var updatable = options.updatable;
  54093. if (instance) {
  54094. // positionFunction : ribbon case
  54095. // only pathArray and sideOrientation parameters are taken into account for positions update
  54096. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54097. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54098. var positionFunction = function (positions) {
  54099. var minlg = pathArray[0].length;
  54100. var i = 0;
  54101. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54102. for (var si = 1; si <= ns; si++) {
  54103. for (var p = 0; p < pathArray.length; p++) {
  54104. var path = pathArray[p];
  54105. var l = path.length;
  54106. minlg = (minlg < l) ? minlg : l;
  54107. var j = 0;
  54108. while (j < minlg) {
  54109. positions[i] = path[j].x;
  54110. positions[i + 1] = path[j].y;
  54111. positions[i + 2] = path[j].z;
  54112. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54113. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54114. }
  54115. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54116. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54117. }
  54118. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54119. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54120. }
  54121. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54122. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54123. }
  54124. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54125. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54126. }
  54127. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54128. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54129. }
  54130. j++;
  54131. i += 3;
  54132. }
  54133. if (instance._closePath) {
  54134. positions[i] = path[0].x;
  54135. positions[i + 1] = path[0].y;
  54136. positions[i + 2] = path[0].z;
  54137. i += 3;
  54138. }
  54139. }
  54140. }
  54141. };
  54142. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54143. positionFunction(positions);
  54144. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54145. instance._boundingInfo.update(instance._worldMatrix);
  54146. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54147. if (options.colors) {
  54148. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54149. for (var c = 0; c < options.colors.length; c++) {
  54150. colors[c * 4] = options.colors[c].r;
  54151. colors[c * 4 + 1] = options.colors[c].g;
  54152. colors[c * 4 + 2] = options.colors[c].b;
  54153. colors[c * 4 + 3] = options.colors[c].a;
  54154. }
  54155. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54156. }
  54157. if (options.uvs) {
  54158. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54159. for (var i = 0; i < options.uvs.length; i++) {
  54160. uvs[i * 2] = options.uvs[i].x;
  54161. uvs[i * 2 + 1] = options.uvs[i].y;
  54162. }
  54163. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54164. }
  54165. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54166. var indices = instance.getIndices();
  54167. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54168. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54169. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54170. if (instance._closePath) {
  54171. var indexFirst = 0;
  54172. var indexLast = 0;
  54173. for (var p = 0; p < pathArray.length; p++) {
  54174. indexFirst = instance._idx[p] * 3;
  54175. if (p + 1 < pathArray.length) {
  54176. indexLast = (instance._idx[p + 1] - 1) * 3;
  54177. }
  54178. else {
  54179. indexLast = normals.length - 3;
  54180. }
  54181. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54182. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54183. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54184. normals[indexLast] = normals[indexFirst];
  54185. normals[indexLast + 1] = normals[indexFirst + 1];
  54186. normals[indexLast + 2] = normals[indexFirst + 2];
  54187. }
  54188. }
  54189. if (!(instance.areNormalsFrozen)) {
  54190. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54191. }
  54192. }
  54193. return instance;
  54194. }
  54195. else {
  54196. var ribbon = new BABYLON.Mesh(name, scene);
  54197. ribbon._originalBuilderSideOrientation = sideOrientation;
  54198. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54199. if (closePath) {
  54200. ribbon._idx = vertexData._idx;
  54201. }
  54202. ribbon._closePath = closePath;
  54203. ribbon._closeArray = closeArray;
  54204. vertexData.applyToMesh(ribbon, updatable);
  54205. return ribbon;
  54206. }
  54207. };
  54208. /**
  54209. * Creates a cylinder or a cone mesh.
  54210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54211. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54212. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54213. * 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.
  54214. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54215. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54216. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54217. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54218. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54219. * 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).
  54220. * 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
  54221. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54222. * 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
  54223. * 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.
  54224. * If `enclose` is false, a ring surface is one element.
  54225. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54226. * 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
  54227. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54228. * 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).
  54229. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54231. */
  54232. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54233. var cylinder = new BABYLON.Mesh(name, scene);
  54234. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54235. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54236. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54237. vertexData.applyToMesh(cylinder, options.updatable);
  54238. return cylinder;
  54239. };
  54240. /**
  54241. * Creates a torus mesh.
  54242. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54243. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54244. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54245. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54247. * 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).
  54248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54250. */
  54251. MeshBuilder.CreateTorus = function (name, options, scene) {
  54252. var torus = new BABYLON.Mesh(name, scene);
  54253. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54254. torus._originalBuilderSideOrientation = options.sideOrientation;
  54255. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54256. vertexData.applyToMesh(torus, options.updatable);
  54257. return torus;
  54258. };
  54259. /**
  54260. * Creates a torus knot mesh.
  54261. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54262. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54263. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54264. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54265. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54266. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54267. * 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).
  54268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54270. */
  54271. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54272. var torusKnot = new BABYLON.Mesh(name, scene);
  54273. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54274. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54275. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54276. vertexData.applyToMesh(torusKnot, options.updatable);
  54277. return torusKnot;
  54278. };
  54279. /**
  54280. * Creates a line system mesh.
  54281. * A line system is a pool of many lines gathered in a single mesh.
  54282. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54283. * 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.
  54284. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54285. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54286. * 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
  54287. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54288. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54289. * 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
  54290. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54292. */
  54293. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54294. var instance = options.instance;
  54295. var lines = options.lines;
  54296. var colors = options.colors;
  54297. if (instance) {
  54298. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54299. var vertexColor;
  54300. var lineColors;
  54301. if (colors) {
  54302. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54303. }
  54304. var i = 0;
  54305. var c = 0;
  54306. for (var l = 0; l < lines.length; l++) {
  54307. var points = lines[l];
  54308. for (var p = 0; p < points.length; p++) {
  54309. positions[i] = points[p].x;
  54310. positions[i + 1] = points[p].y;
  54311. positions[i + 2] = points[p].z;
  54312. if (colors && vertexColor) {
  54313. lineColors = colors[l];
  54314. vertexColor[c] = lineColors[p].r;
  54315. vertexColor[c + 1] = lineColors[p].g;
  54316. vertexColor[c + 2] = lineColors[p].b;
  54317. vertexColor[c + 3] = lineColors[p].a;
  54318. c += 4;
  54319. }
  54320. i += 3;
  54321. }
  54322. }
  54323. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54324. if (colors && vertexColor) {
  54325. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54326. }
  54327. return instance;
  54328. }
  54329. // line system creation
  54330. var useVertexColor = (colors) ? true : false;
  54331. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54332. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54333. vertexData.applyToMesh(lineSystem, options.updatable);
  54334. return lineSystem;
  54335. };
  54336. /**
  54337. * Creates a line mesh.
  54338. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54339. * 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.
  54340. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54341. * The parameter `points` is an array successive Vector3.
  54342. * 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
  54343. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54344. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54345. * When updating an instance, remember that only point positions can change, not the number of points.
  54346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54347. */
  54348. MeshBuilder.CreateLines = function (name, options, scene) {
  54349. if (scene === void 0) { scene = null; }
  54350. var colors = (options.colors) ? [options.colors] : null;
  54351. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54352. return lines;
  54353. };
  54354. /**
  54355. * Creates a dashed line mesh.
  54356. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54357. * 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.
  54358. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54359. * The parameter `points` is an array successive Vector3.
  54360. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54361. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54362. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54363. * 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
  54364. * When updating an instance, remember that only point positions can change, not the number of points.
  54365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54366. */
  54367. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54368. if (scene === void 0) { scene = null; }
  54369. var points = options.points;
  54370. var instance = options.instance;
  54371. var gapSize = options.gapSize || 1;
  54372. var dashSize = options.dashSize || 3;
  54373. if (instance) {
  54374. var positionFunction = function (positions) {
  54375. var curvect = BABYLON.Vector3.Zero();
  54376. var nbSeg = positions.length / 6;
  54377. var lg = 0;
  54378. var nb = 0;
  54379. var shft = 0;
  54380. var dashshft = 0;
  54381. var curshft = 0;
  54382. var p = 0;
  54383. var i = 0;
  54384. var j = 0;
  54385. for (i = 0; i < points.length - 1; i++) {
  54386. points[i + 1].subtractToRef(points[i], curvect);
  54387. lg += curvect.length();
  54388. }
  54389. shft = lg / nbSeg;
  54390. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54391. for (i = 0; i < points.length - 1; i++) {
  54392. points[i + 1].subtractToRef(points[i], curvect);
  54393. nb = Math.floor(curvect.length() / shft);
  54394. curvect.normalize();
  54395. j = 0;
  54396. while (j < nb && p < positions.length) {
  54397. curshft = shft * j;
  54398. positions[p] = points[i].x + curshft * curvect.x;
  54399. positions[p + 1] = points[i].y + curshft * curvect.y;
  54400. positions[p + 2] = points[i].z + curshft * curvect.z;
  54401. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54402. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54403. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54404. p += 6;
  54405. j++;
  54406. }
  54407. }
  54408. while (p < positions.length) {
  54409. positions[p] = points[i].x;
  54410. positions[p + 1] = points[i].y;
  54411. positions[p + 2] = points[i].z;
  54412. p += 3;
  54413. }
  54414. };
  54415. instance.updateMeshPositions(positionFunction, false);
  54416. return instance;
  54417. }
  54418. // dashed lines creation
  54419. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54420. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54421. vertexData.applyToMesh(dashedLines, options.updatable);
  54422. dashedLines.dashSize = dashSize;
  54423. dashedLines.gapSize = gapSize;
  54424. return dashedLines;
  54425. };
  54426. /**
  54427. * Creates an extruded shape mesh.
  54428. * 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.
  54429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54430. *
  54431. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54432. * 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
  54433. * extruded along the Z axis.
  54434. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54435. * 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.
  54436. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54437. * 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
  54438. * 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
  54439. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54441. * 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).
  54442. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54443. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54445. */
  54446. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54447. if (scene === void 0) { scene = null; }
  54448. var path = options.path;
  54449. var shape = options.shape;
  54450. var scale = options.scale || 1;
  54451. var rotation = options.rotation || 0;
  54452. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54453. var updatable = options.updatable;
  54454. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54455. var instance = options.instance || null;
  54456. var invertUV = options.invertUV || false;
  54457. 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);
  54458. };
  54459. /**
  54460. * Creates an custom extruded shape mesh.
  54461. * 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.
  54462. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54463. *
  54464. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54465. * 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
  54466. * extruded along the Z axis.
  54467. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54468. * 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
  54469. * and the distance of this point from the begining of the path :
  54470. * ```javascript
  54471. * var rotationFunction = function(i, distance) {
  54472. * // do things
  54473. * return rotationValue; }
  54474. * ```
  54475. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54476. * 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
  54477. * and the distance of this point from the begining of the path :
  54478. * ```javascript
  54479. * var scaleFunction = function(i, distance) {
  54480. * // do things
  54481. * return scaleValue;}
  54482. * ```
  54483. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54484. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54485. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54486. * 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
  54487. * 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
  54488. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54490. * 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).
  54491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54492. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54494. */
  54495. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54496. var path = options.path;
  54497. var shape = options.shape;
  54498. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54499. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54500. var ribbonCloseArray = options.ribbonCloseArray || false;
  54501. var ribbonClosePath = options.ribbonClosePath || false;
  54502. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54503. var updatable = options.updatable;
  54504. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54505. var instance = options.instance;
  54506. var invertUV = options.invertUV || false;
  54507. 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);
  54508. };
  54509. /**
  54510. * Creates lathe mesh.
  54511. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54512. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54513. *
  54514. * 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
  54515. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54516. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54517. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54518. * 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.
  54519. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54520. * 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
  54521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54522. * 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).
  54523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54524. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54526. */
  54527. MeshBuilder.CreateLathe = function (name, options, scene) {
  54528. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54529. var closed = (options.closed === undefined) ? true : options.closed;
  54530. var shape = options.shape;
  54531. var radius = options.radius || 1;
  54532. var tessellation = options.tessellation || 64;
  54533. var updatable = options.updatable;
  54534. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54535. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54536. var pi2 = Math.PI * 2;
  54537. var paths = new Array();
  54538. var invertUV = options.invertUV || false;
  54539. var i = 0;
  54540. var p = 0;
  54541. var step = pi2 / tessellation * arc;
  54542. var rotated;
  54543. var path = new Array();
  54544. ;
  54545. for (i = 0; i <= tessellation; i++) {
  54546. var path = [];
  54547. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54548. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54549. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54550. }
  54551. for (p = 0; p < shape.length; p++) {
  54552. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54553. path.push(rotated);
  54554. }
  54555. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54556. 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));
  54557. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54558. }
  54559. paths.push(path);
  54560. }
  54561. // lathe ribbon
  54562. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54563. return lathe;
  54564. };
  54565. /**
  54566. * Creates a plane mesh.
  54567. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54568. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54569. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54570. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54572. * 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).
  54573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54575. */
  54576. MeshBuilder.CreatePlane = function (name, options, scene) {
  54577. var plane = new BABYLON.Mesh(name, scene);
  54578. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54579. plane._originalBuilderSideOrientation = options.sideOrientation;
  54580. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54581. vertexData.applyToMesh(plane, options.updatable);
  54582. if (options.sourcePlane) {
  54583. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54584. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54585. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54586. plane.rotate(vectorProduct, product);
  54587. }
  54588. return plane;
  54589. };
  54590. /**
  54591. * Creates a ground mesh.
  54592. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54593. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54594. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54596. */
  54597. MeshBuilder.CreateGround = function (name, options, scene) {
  54598. var ground = new BABYLON.GroundMesh(name, scene);
  54599. ground._setReady(false);
  54600. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54601. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54602. ground._width = options.width || 1;
  54603. ground._height = options.height || 1;
  54604. ground._maxX = ground._width / 2;
  54605. ground._maxZ = ground._height / 2;
  54606. ground._minX = -ground._maxX;
  54607. ground._minZ = -ground._maxZ;
  54608. var vertexData = BABYLON.VertexData.CreateGround(options);
  54609. vertexData.applyToMesh(ground, options.updatable);
  54610. ground._setReady(true);
  54611. return ground;
  54612. };
  54613. /**
  54614. * Creates a tiled ground mesh.
  54615. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54616. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54617. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54618. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54619. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54620. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54621. * numbers of subdivisions on the ground width and height of each tile.
  54622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54623. */
  54624. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54625. var tiledGround = new BABYLON.Mesh(name, scene);
  54626. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54627. vertexData.applyToMesh(tiledGround, options.updatable);
  54628. return tiledGround;
  54629. };
  54630. /**
  54631. * Creates a ground mesh from a height map.
  54632. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54634. * The parameter `url` sets the URL of the height map image resource.
  54635. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54636. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54637. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54638. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54639. * 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.
  54640. * 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).
  54641. * This function is passed the newly built mesh :
  54642. * ```javascript
  54643. * function(mesh) { // do things
  54644. * return; }
  54645. * ```
  54646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54647. */
  54648. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54649. var width = options.width || 10.0;
  54650. var height = options.height || 10.0;
  54651. var subdivisions = options.subdivisions || 1 | 0;
  54652. var minHeight = options.minHeight || 0.0;
  54653. var maxHeight = options.maxHeight || 1.0;
  54654. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54655. var updatable = options.updatable;
  54656. var onReady = options.onReady;
  54657. var ground = new BABYLON.GroundMesh(name, scene);
  54658. ground._subdivisionsX = subdivisions;
  54659. ground._subdivisionsY = subdivisions;
  54660. ground._width = width;
  54661. ground._height = height;
  54662. ground._maxX = ground._width / 2.0;
  54663. ground._maxZ = ground._height / 2.0;
  54664. ground._minX = -ground._maxX;
  54665. ground._minZ = -ground._maxZ;
  54666. ground._setReady(false);
  54667. var onload = function (img) {
  54668. // Getting height map data
  54669. var canvas = document.createElement("canvas");
  54670. var context = canvas.getContext("2d");
  54671. if (!context) {
  54672. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54673. }
  54674. if (scene.isDisposed) {
  54675. return;
  54676. }
  54677. var bufferWidth = img.width;
  54678. var bufferHeight = img.height;
  54679. canvas.width = bufferWidth;
  54680. canvas.height = bufferHeight;
  54681. context.drawImage(img, 0, 0);
  54682. // Create VertexData from map data
  54683. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54684. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54685. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54686. width: width, height: height,
  54687. subdivisions: subdivisions,
  54688. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54689. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54690. });
  54691. vertexData.applyToMesh(ground, updatable);
  54692. ground._setReady(true);
  54693. //execute ready callback, if set
  54694. if (onReady) {
  54695. onReady(ground);
  54696. }
  54697. };
  54698. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54699. return ground;
  54700. };
  54701. /**
  54702. * Creates a polygon mesh.
  54703. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54704. * 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.
  54705. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54707. * 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).
  54708. * Remember you can only change the shape positions, not their number when updating a polygon.
  54709. */
  54710. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54711. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54712. var shape = options.shape;
  54713. var holes = options.holes || [];
  54714. var depth = options.depth || 0;
  54715. var contours = [];
  54716. var hole = [];
  54717. for (var i = 0; i < shape.length; i++) {
  54718. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54719. }
  54720. var epsilon = 0.00000001;
  54721. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54722. contours.pop();
  54723. }
  54724. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54725. for (var hNb = 0; hNb < holes.length; hNb++) {
  54726. hole = [];
  54727. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54728. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54729. }
  54730. polygonTriangulation.addHole(hole);
  54731. }
  54732. var polygon = polygonTriangulation.build(options.updatable, depth);
  54733. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54734. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54735. vertexData.applyToMesh(polygon, options.updatable);
  54736. return polygon;
  54737. };
  54738. ;
  54739. /**
  54740. * Creates an extruded polygon mesh, with depth in the Y direction.
  54741. * 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).
  54742. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54743. */
  54744. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54745. return MeshBuilder.CreatePolygon(name, options, scene);
  54746. };
  54747. ;
  54748. /**
  54749. * Creates a tube mesh.
  54750. * 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.
  54751. *
  54752. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54753. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54754. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54755. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54756. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54757. * 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.
  54758. * It must return a radius value (positive float) :
  54759. * ```javascript
  54760. * var radiusFunction = function(i, distance) {
  54761. * // do things
  54762. * return radius; }
  54763. * ```
  54764. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54765. * 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
  54766. * 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
  54767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54768. * 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).
  54769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54770. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54772. */
  54773. MeshBuilder.CreateTube = function (name, options, scene) {
  54774. var path = options.path;
  54775. var instance = options.instance;
  54776. var radius = 1.0;
  54777. if (instance) {
  54778. radius = instance.radius;
  54779. }
  54780. if (options.radius !== undefined) {
  54781. radius = options.radius;
  54782. }
  54783. ;
  54784. var tessellation = options.tessellation || 64 | 0;
  54785. var radiusFunction = options.radiusFunction || null;
  54786. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54787. var invertUV = options.invertUV || false;
  54788. var updatable = options.updatable;
  54789. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54790. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54791. // tube geometry
  54792. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54793. var tangents = path3D.getTangents();
  54794. var normals = path3D.getNormals();
  54795. var distances = path3D.getDistances();
  54796. var pi2 = Math.PI * 2;
  54797. var step = pi2 / tessellation * arc;
  54798. var returnRadius = function () { return radius; };
  54799. var radiusFunctionFinal = radiusFunction || returnRadius;
  54800. var circlePath;
  54801. var rad;
  54802. var normal;
  54803. var rotated;
  54804. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54805. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54806. for (var i = 0; i < path.length; i++) {
  54807. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54808. circlePath = Array(); // current circle array
  54809. normal = normals[i]; // current normal
  54810. for (var t = 0; t < tessellation; t++) {
  54811. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54812. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54813. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54814. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54815. circlePath[t] = rotated;
  54816. }
  54817. circlePaths[index] = circlePath;
  54818. index++;
  54819. }
  54820. // cap
  54821. var capPath = function (nbPoints, pathIndex) {
  54822. var pointCap = Array();
  54823. for (var i = 0; i < nbPoints; i++) {
  54824. pointCap.push(path[pathIndex]);
  54825. }
  54826. return pointCap;
  54827. };
  54828. switch (cap) {
  54829. case BABYLON.Mesh.NO_CAP:
  54830. break;
  54831. case BABYLON.Mesh.CAP_START:
  54832. circlePaths[0] = capPath(tessellation, 0);
  54833. circlePaths[1] = circlePaths[2].slice(0);
  54834. break;
  54835. case BABYLON.Mesh.CAP_END:
  54836. circlePaths[index] = circlePaths[index - 1].slice(0);
  54837. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54838. break;
  54839. case BABYLON.Mesh.CAP_ALL:
  54840. circlePaths[0] = capPath(tessellation, 0);
  54841. circlePaths[1] = circlePaths[2].slice(0);
  54842. circlePaths[index] = circlePaths[index - 1].slice(0);
  54843. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54844. break;
  54845. default:
  54846. break;
  54847. }
  54848. return circlePaths;
  54849. };
  54850. var path3D;
  54851. var pathArray;
  54852. if (instance) {
  54853. var arc = options.arc || instance.arc;
  54854. path3D = (instance.path3D).update(path);
  54855. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54856. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54857. instance.path3D = path3D;
  54858. instance.pathArray = pathArray;
  54859. instance.arc = arc;
  54860. instance.radius = radius;
  54861. return instance;
  54862. }
  54863. // tube creation
  54864. path3D = new BABYLON.Path3D(path);
  54865. var newPathArray = new Array();
  54866. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54867. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54868. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54869. tube.pathArray = pathArray;
  54870. tube.path3D = path3D;
  54871. tube.tessellation = tessellation;
  54872. tube.cap = cap;
  54873. tube.arc = options.arc;
  54874. tube.radius = radius;
  54875. return tube;
  54876. };
  54877. /**
  54878. * Creates a polyhedron mesh.
  54879. *
  54880. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54881. * 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
  54882. * to choose the wanted type.
  54883. * The parameter `size` (positive float, default 1) sets the polygon size.
  54884. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54885. * 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`.
  54886. * 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
  54887. * 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)`).
  54888. * 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
  54889. * 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.
  54890. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54891. * 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).
  54892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54894. */
  54895. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54896. var polyhedron = new BABYLON.Mesh(name, scene);
  54897. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54898. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54899. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54900. vertexData.applyToMesh(polyhedron, options.updatable);
  54901. return polyhedron;
  54902. };
  54903. /**
  54904. * Creates a decal mesh.
  54905. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54906. * 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.
  54907. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54908. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54909. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54910. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54911. */
  54912. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54913. var indices = sourceMesh.getIndices();
  54914. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54915. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54916. var position = options.position || BABYLON.Vector3.Zero();
  54917. var normal = options.normal || BABYLON.Vector3.Up();
  54918. var size = options.size || BABYLON.Vector3.One();
  54919. var angle = options.angle || 0;
  54920. // Getting correct rotation
  54921. if (!normal) {
  54922. var target = new BABYLON.Vector3(0, 0, 1);
  54923. var camera = sourceMesh.getScene().activeCamera;
  54924. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54925. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54926. }
  54927. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54928. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54929. var pitch = Math.atan2(normal.y, len);
  54930. // Matrix
  54931. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54932. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54933. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54934. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54935. var vertexData = new BABYLON.VertexData();
  54936. vertexData.indices = [];
  54937. vertexData.positions = [];
  54938. vertexData.normals = [];
  54939. vertexData.uvs = [];
  54940. var currentVertexDataIndex = 0;
  54941. var extractDecalVector3 = function (indexId) {
  54942. var result = new BABYLON.PositionNormalVertex();
  54943. if (!indices || !positions || !normals) {
  54944. return result;
  54945. }
  54946. var vertexId = indices[indexId];
  54947. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54948. // Send vector to decal local world
  54949. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54950. // Get normal
  54951. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54952. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54953. return result;
  54954. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54955. var clip = function (vertices, axis) {
  54956. if (vertices.length === 0) {
  54957. return vertices;
  54958. }
  54959. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54960. var clipVertices = function (v0, v1) {
  54961. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54962. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54963. };
  54964. var result = new Array();
  54965. for (var index = 0; index < vertices.length; index += 3) {
  54966. var v1Out;
  54967. var v2Out;
  54968. var v3Out;
  54969. var total = 0;
  54970. var nV1 = null;
  54971. var nV2 = null;
  54972. var nV3 = null;
  54973. var nV4 = null;
  54974. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54975. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54976. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54977. v1Out = d1 > 0;
  54978. v2Out = d2 > 0;
  54979. v3Out = d3 > 0;
  54980. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54981. switch (total) {
  54982. case 0:
  54983. result.push(vertices[index]);
  54984. result.push(vertices[index + 1]);
  54985. result.push(vertices[index + 2]);
  54986. break;
  54987. case 1:
  54988. if (v1Out) {
  54989. nV1 = vertices[index + 1];
  54990. nV2 = vertices[index + 2];
  54991. nV3 = clipVertices(vertices[index], nV1);
  54992. nV4 = clipVertices(vertices[index], nV2);
  54993. }
  54994. if (v2Out) {
  54995. nV1 = vertices[index];
  54996. nV2 = vertices[index + 2];
  54997. nV3 = clipVertices(vertices[index + 1], nV1);
  54998. nV4 = clipVertices(vertices[index + 1], nV2);
  54999. result.push(nV3);
  55000. result.push(nV2.clone());
  55001. result.push(nV1.clone());
  55002. result.push(nV2.clone());
  55003. result.push(nV3.clone());
  55004. result.push(nV4);
  55005. break;
  55006. }
  55007. if (v3Out) {
  55008. nV1 = vertices[index];
  55009. nV2 = vertices[index + 1];
  55010. nV3 = clipVertices(vertices[index + 2], nV1);
  55011. nV4 = clipVertices(vertices[index + 2], nV2);
  55012. }
  55013. if (nV1 && nV2 && nV3 && nV4) {
  55014. result.push(nV1.clone());
  55015. result.push(nV2.clone());
  55016. result.push(nV3);
  55017. result.push(nV4);
  55018. result.push(nV3.clone());
  55019. result.push(nV2.clone());
  55020. }
  55021. break;
  55022. case 2:
  55023. if (!v1Out) {
  55024. nV1 = vertices[index].clone();
  55025. nV2 = clipVertices(nV1, vertices[index + 1]);
  55026. nV3 = clipVertices(nV1, vertices[index + 2]);
  55027. result.push(nV1);
  55028. result.push(nV2);
  55029. result.push(nV3);
  55030. }
  55031. if (!v2Out) {
  55032. nV1 = vertices[index + 1].clone();
  55033. nV2 = clipVertices(nV1, vertices[index + 2]);
  55034. nV3 = clipVertices(nV1, vertices[index]);
  55035. result.push(nV1);
  55036. result.push(nV2);
  55037. result.push(nV3);
  55038. }
  55039. if (!v3Out) {
  55040. nV1 = vertices[index + 2].clone();
  55041. nV2 = clipVertices(nV1, vertices[index]);
  55042. nV3 = clipVertices(nV1, vertices[index + 1]);
  55043. result.push(nV1);
  55044. result.push(nV2);
  55045. result.push(nV3);
  55046. }
  55047. break;
  55048. case 3:
  55049. break;
  55050. }
  55051. }
  55052. return result;
  55053. };
  55054. for (var index = 0; index < indices.length; index += 3) {
  55055. var faceVertices = new Array();
  55056. faceVertices.push(extractDecalVector3(index));
  55057. faceVertices.push(extractDecalVector3(index + 1));
  55058. faceVertices.push(extractDecalVector3(index + 2));
  55059. // Clip
  55060. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55061. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55062. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55063. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55064. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55065. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55066. if (faceVertices.length === 0) {
  55067. continue;
  55068. }
  55069. // Add UVs and get back to world
  55070. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55071. var vertex = faceVertices[vIndex];
  55072. //TODO check for Int32Array | Uint32Array | Uint16Array
  55073. vertexData.indices.push(currentVertexDataIndex);
  55074. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55075. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55076. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55077. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55078. currentVertexDataIndex++;
  55079. }
  55080. }
  55081. // Return mesh
  55082. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55083. vertexData.applyToMesh(decal);
  55084. decal.position = position.clone();
  55085. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55086. return decal;
  55087. };
  55088. // Privates
  55089. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55090. // extrusion geometry
  55091. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55092. var tangents = path3D.getTangents();
  55093. var normals = path3D.getNormals();
  55094. var binormals = path3D.getBinormals();
  55095. var distances = path3D.getDistances();
  55096. var angle = 0;
  55097. var returnScale = function () { return scale !== null ? scale : 1; };
  55098. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55099. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55100. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55101. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55102. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55103. for (var i = 0; i < curve.length; i++) {
  55104. var shapePath = new Array();
  55105. var angleStep = rotate(i, distances[i]);
  55106. var scaleRatio = scl(i, distances[i]);
  55107. for (var p = 0; p < shape.length; p++) {
  55108. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55109. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55110. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55111. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55112. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55113. shapePath[p] = rotated;
  55114. }
  55115. shapePaths[index] = shapePath;
  55116. angle += angleStep;
  55117. index++;
  55118. }
  55119. // cap
  55120. var capPath = function (shapePath) {
  55121. var pointCap = Array();
  55122. var barycenter = BABYLON.Vector3.Zero();
  55123. var i;
  55124. for (i = 0; i < shapePath.length; i++) {
  55125. barycenter.addInPlace(shapePath[i]);
  55126. }
  55127. barycenter.scaleInPlace(1.0 / shapePath.length);
  55128. for (i = 0; i < shapePath.length; i++) {
  55129. pointCap.push(barycenter);
  55130. }
  55131. return pointCap;
  55132. };
  55133. switch (cap) {
  55134. case BABYLON.Mesh.NO_CAP:
  55135. break;
  55136. case BABYLON.Mesh.CAP_START:
  55137. shapePaths[0] = capPath(shapePaths[2]);
  55138. shapePaths[1] = shapePaths[2];
  55139. break;
  55140. case BABYLON.Mesh.CAP_END:
  55141. shapePaths[index] = shapePaths[index - 1];
  55142. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55143. break;
  55144. case BABYLON.Mesh.CAP_ALL:
  55145. shapePaths[0] = capPath(shapePaths[2]);
  55146. shapePaths[1] = shapePaths[2];
  55147. shapePaths[index] = shapePaths[index - 1];
  55148. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55149. break;
  55150. default:
  55151. break;
  55152. }
  55153. return shapePaths;
  55154. };
  55155. var path3D;
  55156. var pathArray;
  55157. if (instance) {
  55158. path3D = (instance.path3D).update(curve);
  55159. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55160. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55161. return instance;
  55162. }
  55163. // extruded shape creation
  55164. path3D = new BABYLON.Path3D(curve);
  55165. var newShapePaths = new Array();
  55166. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55167. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55168. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55169. extrudedGeneric.pathArray = pathArray;
  55170. extrudedGeneric.path3D = path3D;
  55171. extrudedGeneric.cap = cap;
  55172. return extrudedGeneric;
  55173. };
  55174. return MeshBuilder;
  55175. }());
  55176. BABYLON.MeshBuilder = MeshBuilder;
  55177. })(BABYLON || (BABYLON = {}));
  55178. //# sourceMappingURL=babylon.meshBuilder.js.map
  55179. var BABYLON;
  55180. (function (BABYLON) {
  55181. var AudioEngine = /** @class */ (function () {
  55182. function AudioEngine() {
  55183. this._audioContext = null;
  55184. this._audioContextInitialized = false;
  55185. this.canUseWebAudio = false;
  55186. this.WarnedWebAudioUnsupported = false;
  55187. this.unlocked = false;
  55188. this.isMP3supported = false;
  55189. this.isOGGsupported = false;
  55190. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55191. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55192. this.canUseWebAudio = true;
  55193. }
  55194. var audioElem = document.createElement('audio');
  55195. try {
  55196. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55197. this.isMP3supported = true;
  55198. }
  55199. }
  55200. catch (e) {
  55201. // protect error during capability check.
  55202. }
  55203. try {
  55204. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55205. this.isOGGsupported = true;
  55206. }
  55207. }
  55208. catch (e) {
  55209. // protect error during capability check.
  55210. }
  55211. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55212. this._unlockiOSaudio();
  55213. }
  55214. else {
  55215. this.unlocked = true;
  55216. }
  55217. }
  55218. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55219. get: function () {
  55220. if (!this._audioContextInitialized) {
  55221. this._initializeAudioContext();
  55222. }
  55223. return this._audioContext;
  55224. },
  55225. enumerable: true,
  55226. configurable: true
  55227. });
  55228. AudioEngine.prototype._unlockiOSaudio = function () {
  55229. var _this = this;
  55230. var unlockaudio = function () {
  55231. if (!_this.audioContext) {
  55232. return;
  55233. }
  55234. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55235. var source = _this.audioContext.createBufferSource();
  55236. source.buffer = buffer;
  55237. source.connect(_this.audioContext.destination);
  55238. source.start(0);
  55239. setTimeout(function () {
  55240. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55241. _this.unlocked = true;
  55242. window.removeEventListener('touchend', unlockaudio, false);
  55243. if (_this.onAudioUnlocked) {
  55244. _this.onAudioUnlocked();
  55245. }
  55246. }
  55247. }, 0);
  55248. };
  55249. window.addEventListener('touchend', unlockaudio, false);
  55250. };
  55251. AudioEngine.prototype._initializeAudioContext = function () {
  55252. try {
  55253. if (this.canUseWebAudio) {
  55254. this._audioContext = new AudioContext();
  55255. // create a global volume gain node
  55256. this.masterGain = this._audioContext.createGain();
  55257. this.masterGain.gain.value = 1;
  55258. this.masterGain.connect(this._audioContext.destination);
  55259. this._audioContextInitialized = true;
  55260. }
  55261. }
  55262. catch (e) {
  55263. this.canUseWebAudio = false;
  55264. BABYLON.Tools.Error("Web Audio: " + e.message);
  55265. }
  55266. };
  55267. AudioEngine.prototype.dispose = function () {
  55268. if (this.canUseWebAudio && this._audioContextInitialized) {
  55269. if (this._connectedAnalyser && this._audioContext) {
  55270. this._connectedAnalyser.stopDebugCanvas();
  55271. this._connectedAnalyser.dispose();
  55272. this.masterGain.disconnect();
  55273. this.masterGain.connect(this._audioContext.destination);
  55274. this._connectedAnalyser = null;
  55275. }
  55276. this.masterGain.gain.value = 1;
  55277. }
  55278. this.WarnedWebAudioUnsupported = false;
  55279. };
  55280. AudioEngine.prototype.getGlobalVolume = function () {
  55281. if (this.canUseWebAudio && this._audioContextInitialized) {
  55282. return this.masterGain.gain.value;
  55283. }
  55284. else {
  55285. return -1;
  55286. }
  55287. };
  55288. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55289. if (this.canUseWebAudio && this._audioContextInitialized) {
  55290. this.masterGain.gain.value = newVolume;
  55291. }
  55292. };
  55293. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55294. if (this._connectedAnalyser) {
  55295. this._connectedAnalyser.stopDebugCanvas();
  55296. }
  55297. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55298. this._connectedAnalyser = analyser;
  55299. this.masterGain.disconnect();
  55300. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55301. }
  55302. };
  55303. return AudioEngine;
  55304. }());
  55305. BABYLON.AudioEngine = AudioEngine;
  55306. })(BABYLON || (BABYLON = {}));
  55307. //# sourceMappingURL=babylon.audioEngine.js.map
  55308. var BABYLON;
  55309. (function (BABYLON) {
  55310. var Sound = /** @class */ (function () {
  55311. /**
  55312. * Create a sound and attach it to a scene
  55313. * @param name Name of your sound
  55314. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55315. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55316. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55317. */
  55318. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55319. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55320. var _this = this;
  55321. this.autoplay = false;
  55322. this.loop = false;
  55323. this.useCustomAttenuation = false;
  55324. this.spatialSound = false;
  55325. this.refDistance = 1;
  55326. this.rolloffFactor = 1;
  55327. this.maxDistance = 100;
  55328. this.distanceModel = "linear";
  55329. this._panningModel = "equalpower";
  55330. this._playbackRate = 1;
  55331. this._streaming = false;
  55332. this._startTime = 0;
  55333. this._startOffset = 0;
  55334. this._position = BABYLON.Vector3.Zero();
  55335. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55336. this._volume = 1;
  55337. this._isReadyToPlay = false;
  55338. this.isPlaying = false;
  55339. this.isPaused = false;
  55340. this._isDirectional = false;
  55341. // Used if you'd like to create a directional sound.
  55342. // If not set, the sound will be omnidirectional
  55343. this._coneInnerAngle = 360;
  55344. this._coneOuterAngle = 360;
  55345. this._coneOuterGain = 0;
  55346. this._isOutputConnected = false;
  55347. this._urlType = "Unknown";
  55348. this.name = name;
  55349. this._scene = scene;
  55350. this._readyToPlayCallback = readyToPlayCallback;
  55351. // Default custom attenuation function is a linear attenuation
  55352. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55353. if (currentDistance < maxDistance) {
  55354. return currentVolume * (1 - currentDistance / maxDistance);
  55355. }
  55356. else {
  55357. return 0;
  55358. }
  55359. };
  55360. if (options) {
  55361. this.autoplay = options.autoplay || false;
  55362. this.loop = options.loop || false;
  55363. // if volume === 0, we need another way to check this option
  55364. if (options.volume !== undefined) {
  55365. this._volume = options.volume;
  55366. }
  55367. this.spatialSound = options.spatialSound || false;
  55368. this.maxDistance = options.maxDistance || 100;
  55369. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55370. this.rolloffFactor = options.rolloffFactor || 1;
  55371. this.refDistance = options.refDistance || 1;
  55372. this.distanceModel = options.distanceModel || "linear";
  55373. this._playbackRate = options.playbackRate || 1;
  55374. this._streaming = options.streaming || false;
  55375. }
  55376. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55377. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55378. this._soundGain.gain.value = this._volume;
  55379. this._inputAudioNode = this._soundGain;
  55380. this._ouputAudioNode = this._soundGain;
  55381. if (this.spatialSound) {
  55382. this._createSpatialParameters();
  55383. }
  55384. this._scene.mainSoundTrack.AddSound(this);
  55385. var validParameter = true;
  55386. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55387. if (urlOrArrayBuffer) {
  55388. if (typeof (urlOrArrayBuffer) === "string")
  55389. this._urlType = "String";
  55390. if (Array.isArray(urlOrArrayBuffer))
  55391. this._urlType = "Array";
  55392. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55393. this._urlType = "ArrayBuffer";
  55394. var urls = [];
  55395. var codecSupportedFound = false;
  55396. switch (this._urlType) {
  55397. case "ArrayBuffer":
  55398. if (urlOrArrayBuffer.byteLength > 0) {
  55399. codecSupportedFound = true;
  55400. this._soundLoaded(urlOrArrayBuffer);
  55401. }
  55402. break;
  55403. case "String":
  55404. urls.push(urlOrArrayBuffer);
  55405. case "Array":
  55406. if (urls.length === 0)
  55407. urls = urlOrArrayBuffer;
  55408. // If we found a supported format, we load it immediately and stop the loop
  55409. for (var i = 0; i < urls.length; i++) {
  55410. var url = urls[i];
  55411. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55412. codecSupportedFound = true;
  55413. }
  55414. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55415. codecSupportedFound = true;
  55416. }
  55417. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55418. codecSupportedFound = true;
  55419. }
  55420. if (url.indexOf("blob:") !== -1) {
  55421. codecSupportedFound = true;
  55422. }
  55423. if (codecSupportedFound) {
  55424. // Loading sound using XHR2
  55425. if (!this._streaming) {
  55426. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55427. }
  55428. else {
  55429. this._htmlAudioElement = new Audio(url);
  55430. this._htmlAudioElement.controls = false;
  55431. this._htmlAudioElement.loop = this.loop;
  55432. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55433. this._htmlAudioElement.preload = "auto";
  55434. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55435. _this._isReadyToPlay = true;
  55436. if (_this.autoplay) {
  55437. _this.play();
  55438. }
  55439. if (_this._readyToPlayCallback) {
  55440. _this._readyToPlayCallback();
  55441. }
  55442. });
  55443. document.body.appendChild(this._htmlAudioElement);
  55444. }
  55445. break;
  55446. }
  55447. }
  55448. break;
  55449. default:
  55450. validParameter = false;
  55451. break;
  55452. }
  55453. if (!validParameter) {
  55454. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55455. }
  55456. else {
  55457. if (!codecSupportedFound) {
  55458. this._isReadyToPlay = true;
  55459. // Simulating a ready to play event to avoid breaking code path
  55460. if (this._readyToPlayCallback) {
  55461. window.setTimeout(function () {
  55462. if (_this._readyToPlayCallback) {
  55463. _this._readyToPlayCallback();
  55464. }
  55465. }, 1000);
  55466. }
  55467. }
  55468. }
  55469. }
  55470. }
  55471. else {
  55472. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55473. this._scene.mainSoundTrack.AddSound(this);
  55474. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55475. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55476. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55477. }
  55478. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55479. if (this._readyToPlayCallback) {
  55480. window.setTimeout(function () {
  55481. if (_this._readyToPlayCallback) {
  55482. _this._readyToPlayCallback();
  55483. }
  55484. }, 1000);
  55485. }
  55486. }
  55487. }
  55488. Sound.prototype.dispose = function () {
  55489. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55490. if (this.isPlaying) {
  55491. this.stop();
  55492. }
  55493. this._isReadyToPlay = false;
  55494. if (this.soundTrackId === -1) {
  55495. this._scene.mainSoundTrack.RemoveSound(this);
  55496. }
  55497. else {
  55498. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55499. }
  55500. if (this._soundGain) {
  55501. this._soundGain.disconnect();
  55502. this._soundGain = null;
  55503. }
  55504. if (this._soundPanner) {
  55505. this._soundPanner.disconnect();
  55506. this._soundPanner = null;
  55507. }
  55508. if (this._soundSource) {
  55509. this._soundSource.disconnect();
  55510. this._soundSource = null;
  55511. }
  55512. this._audioBuffer = null;
  55513. if (this._htmlAudioElement) {
  55514. this._htmlAudioElement.pause();
  55515. this._htmlAudioElement.src = "";
  55516. document.body.removeChild(this._htmlAudioElement);
  55517. }
  55518. if (this._connectedMesh && this._registerFunc) {
  55519. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55520. this._connectedMesh = null;
  55521. }
  55522. }
  55523. };
  55524. Sound.prototype.isReady = function () {
  55525. return this._isReadyToPlay;
  55526. };
  55527. Sound.prototype._soundLoaded = function (audioData) {
  55528. var _this = this;
  55529. if (!BABYLON.Engine.audioEngine.audioContext) {
  55530. return;
  55531. }
  55532. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55533. _this._audioBuffer = buffer;
  55534. _this._isReadyToPlay = true;
  55535. if (_this.autoplay) {
  55536. _this.play();
  55537. }
  55538. if (_this._readyToPlayCallback) {
  55539. _this._readyToPlayCallback();
  55540. }
  55541. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55542. };
  55543. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55544. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55545. this._audioBuffer = audioBuffer;
  55546. this._isReadyToPlay = true;
  55547. }
  55548. };
  55549. Sound.prototype.updateOptions = function (options) {
  55550. if (options) {
  55551. this.loop = options.loop || this.loop;
  55552. this.maxDistance = options.maxDistance || this.maxDistance;
  55553. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55554. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55555. this.refDistance = options.refDistance || this.refDistance;
  55556. this.distanceModel = options.distanceModel || this.distanceModel;
  55557. this._playbackRate = options.playbackRate || this._playbackRate;
  55558. this._updateSpatialParameters();
  55559. if (this.isPlaying) {
  55560. if (this._streaming) {
  55561. this._htmlAudioElement.playbackRate = this._playbackRate;
  55562. }
  55563. else {
  55564. if (this._soundSource) {
  55565. this._soundSource.playbackRate.value = this._playbackRate;
  55566. }
  55567. }
  55568. }
  55569. }
  55570. };
  55571. Sound.prototype._createSpatialParameters = function () {
  55572. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55573. if (this._scene.headphone) {
  55574. this._panningModel = "HRTF";
  55575. }
  55576. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55577. this._updateSpatialParameters();
  55578. this._soundPanner.connect(this._ouputAudioNode);
  55579. this._inputAudioNode = this._soundPanner;
  55580. }
  55581. };
  55582. Sound.prototype._updateSpatialParameters = function () {
  55583. if (this.spatialSound && this._soundPanner) {
  55584. if (this.useCustomAttenuation) {
  55585. // Tricks to disable in a way embedded Web Audio attenuation
  55586. this._soundPanner.distanceModel = "linear";
  55587. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55588. this._soundPanner.refDistance = 1;
  55589. this._soundPanner.rolloffFactor = 1;
  55590. this._soundPanner.panningModel = this._panningModel;
  55591. }
  55592. else {
  55593. this._soundPanner.distanceModel = this.distanceModel;
  55594. this._soundPanner.maxDistance = this.maxDistance;
  55595. this._soundPanner.refDistance = this.refDistance;
  55596. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55597. this._soundPanner.panningModel = this._panningModel;
  55598. }
  55599. }
  55600. };
  55601. Sound.prototype.switchPanningModelToHRTF = function () {
  55602. this._panningModel = "HRTF";
  55603. this._switchPanningModel();
  55604. };
  55605. Sound.prototype.switchPanningModelToEqualPower = function () {
  55606. this._panningModel = "equalpower";
  55607. this._switchPanningModel();
  55608. };
  55609. Sound.prototype._switchPanningModel = function () {
  55610. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55611. this._soundPanner.panningModel = this._panningModel;
  55612. }
  55613. };
  55614. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55615. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55616. if (this._isOutputConnected) {
  55617. this._ouputAudioNode.disconnect();
  55618. }
  55619. this._ouputAudioNode.connect(soundTrackAudioNode);
  55620. this._isOutputConnected = true;
  55621. }
  55622. };
  55623. /**
  55624. * Transform this sound into a directional source
  55625. * @param coneInnerAngle Size of the inner cone in degree
  55626. * @param coneOuterAngle Size of the outer cone in degree
  55627. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55628. */
  55629. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55630. if (coneOuterAngle < coneInnerAngle) {
  55631. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55632. return;
  55633. }
  55634. this._coneInnerAngle = coneInnerAngle;
  55635. this._coneOuterAngle = coneOuterAngle;
  55636. this._coneOuterGain = coneOuterGain;
  55637. this._isDirectional = true;
  55638. if (this.isPlaying && this.loop) {
  55639. this.stop();
  55640. this.play();
  55641. }
  55642. };
  55643. Sound.prototype.setPosition = function (newPosition) {
  55644. this._position = newPosition;
  55645. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55646. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55647. }
  55648. };
  55649. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55650. this._localDirection = newLocalDirection;
  55651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55652. this._updateDirection();
  55653. }
  55654. };
  55655. Sound.prototype._updateDirection = function () {
  55656. if (!this._connectedMesh || !this._soundPanner) {
  55657. return;
  55658. }
  55659. var mat = this._connectedMesh.getWorldMatrix();
  55660. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55661. direction.normalize();
  55662. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55663. };
  55664. Sound.prototype.updateDistanceFromListener = function () {
  55665. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55666. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55667. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55668. }
  55669. };
  55670. Sound.prototype.setAttenuationFunction = function (callback) {
  55671. this._customAttenuationFunction = callback;
  55672. };
  55673. /**
  55674. * Play the sound
  55675. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55676. * @param offset (optional) Start the sound setting it at a specific time
  55677. */
  55678. Sound.prototype.play = function (time, offset) {
  55679. var _this = this;
  55680. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55681. try {
  55682. if (this._startOffset < 0) {
  55683. time = -this._startOffset;
  55684. this._startOffset = 0;
  55685. }
  55686. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55687. if (!this._soundSource || !this._streamingSource) {
  55688. if (this.spatialSound && this._soundPanner) {
  55689. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55690. if (this._isDirectional) {
  55691. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55692. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55693. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55694. if (this._connectedMesh) {
  55695. this._updateDirection();
  55696. }
  55697. else {
  55698. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55699. }
  55700. }
  55701. }
  55702. }
  55703. if (this._streaming) {
  55704. if (!this._streamingSource) {
  55705. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55706. this._htmlAudioElement.onended = function () { _this._onended(); };
  55707. this._htmlAudioElement.playbackRate = this._playbackRate;
  55708. }
  55709. this._streamingSource.disconnect();
  55710. this._streamingSource.connect(this._inputAudioNode);
  55711. this._htmlAudioElement.play();
  55712. }
  55713. else {
  55714. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55715. this._soundSource.buffer = this._audioBuffer;
  55716. this._soundSource.connect(this._inputAudioNode);
  55717. this._soundSource.loop = this.loop;
  55718. this._soundSource.playbackRate.value = this._playbackRate;
  55719. this._soundSource.onended = function () { _this._onended(); };
  55720. if (this._soundSource.buffer) {
  55721. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55722. }
  55723. }
  55724. this._startTime = startTime;
  55725. this.isPlaying = true;
  55726. this.isPaused = false;
  55727. }
  55728. catch (ex) {
  55729. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55730. }
  55731. }
  55732. };
  55733. Sound.prototype._onended = function () {
  55734. this.isPlaying = false;
  55735. if (this.onended) {
  55736. this.onended();
  55737. }
  55738. };
  55739. /**
  55740. * Stop the sound
  55741. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55742. */
  55743. Sound.prototype.stop = function (time) {
  55744. if (this.isPlaying) {
  55745. if (this._streaming) {
  55746. this._htmlAudioElement.pause();
  55747. // Test needed for Firefox or it will generate an Invalid State Error
  55748. if (this._htmlAudioElement.currentTime > 0) {
  55749. this._htmlAudioElement.currentTime = 0;
  55750. }
  55751. }
  55752. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55753. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55754. this._soundSource.stop(stopTime);
  55755. this._soundSource.onended = function () { };
  55756. if (!this.isPaused) {
  55757. this._startOffset = 0;
  55758. }
  55759. }
  55760. this.isPlaying = false;
  55761. }
  55762. };
  55763. Sound.prototype.pause = function () {
  55764. if (this.isPlaying) {
  55765. this.isPaused = true;
  55766. if (this._streaming) {
  55767. this._htmlAudioElement.pause();
  55768. }
  55769. else if (BABYLON.Engine.audioEngine.audioContext) {
  55770. this.stop(0);
  55771. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55772. }
  55773. }
  55774. };
  55775. Sound.prototype.setVolume = function (newVolume, time) {
  55776. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55777. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55778. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55779. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55780. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55781. }
  55782. else {
  55783. this._soundGain.gain.value = newVolume;
  55784. }
  55785. }
  55786. this._volume = newVolume;
  55787. };
  55788. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55789. this._playbackRate = newPlaybackRate;
  55790. if (this.isPlaying) {
  55791. if (this._streaming) {
  55792. this._htmlAudioElement.playbackRate = this._playbackRate;
  55793. }
  55794. else if (this._soundSource) {
  55795. this._soundSource.playbackRate.value = this._playbackRate;
  55796. }
  55797. }
  55798. };
  55799. Sound.prototype.getVolume = function () {
  55800. return this._volume;
  55801. };
  55802. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55803. var _this = this;
  55804. if (this._connectedMesh && this._registerFunc) {
  55805. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55806. this._registerFunc = null;
  55807. }
  55808. this._connectedMesh = meshToConnectTo;
  55809. if (!this.spatialSound) {
  55810. this.spatialSound = true;
  55811. this._createSpatialParameters();
  55812. if (this.isPlaying && this.loop) {
  55813. this.stop();
  55814. this.play();
  55815. }
  55816. }
  55817. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55818. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55819. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55820. };
  55821. Sound.prototype.detachFromMesh = function () {
  55822. if (this._connectedMesh && this._registerFunc) {
  55823. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55824. this._registerFunc = null;
  55825. this._connectedMesh = null;
  55826. }
  55827. };
  55828. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55829. if (!node.getBoundingInfo) {
  55830. return;
  55831. }
  55832. var mesh = node;
  55833. var boundingInfo = mesh.getBoundingInfo();
  55834. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55835. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55836. this._updateDirection();
  55837. }
  55838. };
  55839. Sound.prototype.clone = function () {
  55840. var _this = this;
  55841. if (!this._streaming) {
  55842. var setBufferAndRun = function () {
  55843. if (_this._isReadyToPlay) {
  55844. clonedSound._audioBuffer = _this.getAudioBuffer();
  55845. clonedSound._isReadyToPlay = true;
  55846. if (clonedSound.autoplay) {
  55847. clonedSound.play();
  55848. }
  55849. }
  55850. else {
  55851. window.setTimeout(setBufferAndRun, 300);
  55852. }
  55853. };
  55854. var currentOptions = {
  55855. autoplay: this.autoplay, loop: this.loop,
  55856. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55857. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55858. refDistance: this.refDistance, distanceModel: this.distanceModel
  55859. };
  55860. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55861. if (this.useCustomAttenuation) {
  55862. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55863. }
  55864. clonedSound.setPosition(this._position);
  55865. clonedSound.setPlaybackRate(this._playbackRate);
  55866. setBufferAndRun();
  55867. return clonedSound;
  55868. }
  55869. else {
  55870. return null;
  55871. }
  55872. };
  55873. Sound.prototype.getAudioBuffer = function () {
  55874. return this._audioBuffer;
  55875. };
  55876. Sound.prototype.serialize = function () {
  55877. var serializationObject = {
  55878. name: this.name,
  55879. url: this.name,
  55880. autoplay: this.autoplay,
  55881. loop: this.loop,
  55882. volume: this._volume,
  55883. spatialSound: this.spatialSound,
  55884. maxDistance: this.maxDistance,
  55885. rolloffFactor: this.rolloffFactor,
  55886. refDistance: this.refDistance,
  55887. distanceModel: this.distanceModel,
  55888. playbackRate: this._playbackRate,
  55889. panningModel: this._panningModel,
  55890. soundTrackId: this.soundTrackId
  55891. };
  55892. if (this.spatialSound) {
  55893. if (this._connectedMesh)
  55894. serializationObject.connectedMeshId = this._connectedMesh.id;
  55895. serializationObject.position = this._position.asArray();
  55896. serializationObject.refDistance = this.refDistance;
  55897. serializationObject.distanceModel = this.distanceModel;
  55898. serializationObject.isDirectional = this._isDirectional;
  55899. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55900. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55901. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55902. serializationObject.coneOuterGain = this._coneOuterGain;
  55903. }
  55904. return serializationObject;
  55905. };
  55906. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55907. var soundName = parsedSound.name;
  55908. var soundUrl;
  55909. if (parsedSound.url) {
  55910. soundUrl = rootUrl + parsedSound.url;
  55911. }
  55912. else {
  55913. soundUrl = rootUrl + soundName;
  55914. }
  55915. var options = {
  55916. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55917. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55918. rolloffFactor: parsedSound.rolloffFactor,
  55919. refDistance: parsedSound.refDistance,
  55920. distanceModel: parsedSound.distanceModel,
  55921. playbackRate: parsedSound.playbackRate
  55922. };
  55923. var newSound;
  55924. if (!sourceSound) {
  55925. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55926. scene._addPendingData(newSound);
  55927. }
  55928. else {
  55929. var setBufferAndRun = function () {
  55930. if (sourceSound._isReadyToPlay) {
  55931. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55932. newSound._isReadyToPlay = true;
  55933. if (newSound.autoplay) {
  55934. newSound.play();
  55935. }
  55936. }
  55937. else {
  55938. window.setTimeout(setBufferAndRun, 300);
  55939. }
  55940. };
  55941. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55942. setBufferAndRun();
  55943. }
  55944. if (parsedSound.position) {
  55945. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55946. newSound.setPosition(soundPosition);
  55947. }
  55948. if (parsedSound.isDirectional) {
  55949. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55950. if (parsedSound.localDirectionToMesh) {
  55951. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55952. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55953. }
  55954. }
  55955. if (parsedSound.connectedMeshId) {
  55956. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55957. if (connectedMesh) {
  55958. newSound.attachToMesh(connectedMesh);
  55959. }
  55960. }
  55961. return newSound;
  55962. };
  55963. return Sound;
  55964. }());
  55965. BABYLON.Sound = Sound;
  55966. })(BABYLON || (BABYLON = {}));
  55967. //# sourceMappingURL=babylon.sound.js.map
  55968. var BABYLON;
  55969. (function (BABYLON) {
  55970. var SoundTrack = /** @class */ (function () {
  55971. function SoundTrack(scene, options) {
  55972. this.id = -1;
  55973. this._isMainTrack = false;
  55974. this._isInitialized = false;
  55975. this._scene = scene;
  55976. this.soundCollection = new Array();
  55977. this._options = options;
  55978. if (!this._isMainTrack) {
  55979. this._scene.soundTracks.push(this);
  55980. this.id = this._scene.soundTracks.length - 1;
  55981. }
  55982. }
  55983. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55984. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55985. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55986. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55987. if (this._options) {
  55988. if (this._options.volume) {
  55989. this._outputAudioNode.gain.value = this._options.volume;
  55990. }
  55991. if (this._options.mainTrack) {
  55992. this._isMainTrack = this._options.mainTrack;
  55993. }
  55994. }
  55995. this._isInitialized = true;
  55996. }
  55997. };
  55998. SoundTrack.prototype.dispose = function () {
  55999. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56000. if (this._connectedAnalyser) {
  56001. this._connectedAnalyser.stopDebugCanvas();
  56002. }
  56003. while (this.soundCollection.length) {
  56004. this.soundCollection[0].dispose();
  56005. }
  56006. if (this._outputAudioNode) {
  56007. this._outputAudioNode.disconnect();
  56008. }
  56009. this._outputAudioNode = null;
  56010. }
  56011. };
  56012. SoundTrack.prototype.AddSound = function (sound) {
  56013. if (!this._isInitialized) {
  56014. this._initializeSoundTrackAudioGraph();
  56015. }
  56016. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56017. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56018. }
  56019. if (sound.soundTrackId) {
  56020. if (sound.soundTrackId === -1) {
  56021. this._scene.mainSoundTrack.RemoveSound(sound);
  56022. }
  56023. else {
  56024. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56025. }
  56026. }
  56027. this.soundCollection.push(sound);
  56028. sound.soundTrackId = this.id;
  56029. };
  56030. SoundTrack.prototype.RemoveSound = function (sound) {
  56031. var index = this.soundCollection.indexOf(sound);
  56032. if (index !== -1) {
  56033. this.soundCollection.splice(index, 1);
  56034. }
  56035. };
  56036. SoundTrack.prototype.setVolume = function (newVolume) {
  56037. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56038. this._outputAudioNode.gain.value = newVolume;
  56039. }
  56040. };
  56041. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56042. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56043. for (var i = 0; i < this.soundCollection.length; i++) {
  56044. this.soundCollection[i].switchPanningModelToHRTF();
  56045. }
  56046. }
  56047. };
  56048. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56050. for (var i = 0; i < this.soundCollection.length; i++) {
  56051. this.soundCollection[i].switchPanningModelToEqualPower();
  56052. }
  56053. }
  56054. };
  56055. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56056. if (this._connectedAnalyser) {
  56057. this._connectedAnalyser.stopDebugCanvas();
  56058. }
  56059. this._connectedAnalyser = analyser;
  56060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56061. this._outputAudioNode.disconnect();
  56062. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56063. }
  56064. };
  56065. return SoundTrack;
  56066. }());
  56067. BABYLON.SoundTrack = SoundTrack;
  56068. })(BABYLON || (BABYLON = {}));
  56069. //# sourceMappingURL=babylon.soundtrack.js.map
  56070. var BABYLON;
  56071. (function (BABYLON) {
  56072. var Analyser = /** @class */ (function () {
  56073. function Analyser(scene) {
  56074. this.SMOOTHING = 0.75;
  56075. this.FFT_SIZE = 512;
  56076. this.BARGRAPHAMPLITUDE = 256;
  56077. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56078. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56079. this._scene = scene;
  56080. this._audioEngine = BABYLON.Engine.audioEngine;
  56081. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56082. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56083. this._webAudioAnalyser.minDecibels = -140;
  56084. this._webAudioAnalyser.maxDecibels = 0;
  56085. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56086. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56087. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56088. }
  56089. }
  56090. Analyser.prototype.getFrequencyBinCount = function () {
  56091. if (this._audioEngine.canUseWebAudio) {
  56092. return this._webAudioAnalyser.frequencyBinCount;
  56093. }
  56094. else {
  56095. return 0;
  56096. }
  56097. };
  56098. Analyser.prototype.getByteFrequencyData = function () {
  56099. if (this._audioEngine.canUseWebAudio) {
  56100. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56101. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56102. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56103. }
  56104. return this._byteFreqs;
  56105. };
  56106. Analyser.prototype.getByteTimeDomainData = function () {
  56107. if (this._audioEngine.canUseWebAudio) {
  56108. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56109. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56110. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56111. }
  56112. return this._byteTime;
  56113. };
  56114. Analyser.prototype.getFloatFrequencyData = function () {
  56115. if (this._audioEngine.canUseWebAudio) {
  56116. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56117. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56118. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56119. }
  56120. return this._floatFreqs;
  56121. };
  56122. Analyser.prototype.drawDebugCanvas = function () {
  56123. var _this = this;
  56124. if (this._audioEngine.canUseWebAudio) {
  56125. if (!this._debugCanvas) {
  56126. this._debugCanvas = document.createElement("canvas");
  56127. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56128. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56129. this._debugCanvas.style.position = "absolute";
  56130. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56131. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56132. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56133. document.body.appendChild(this._debugCanvas);
  56134. this._registerFunc = function () {
  56135. _this.drawDebugCanvas();
  56136. };
  56137. this._scene.registerBeforeRender(this._registerFunc);
  56138. }
  56139. if (this._registerFunc && this._debugCanvasContext) {
  56140. var workingArray = this.getByteFrequencyData();
  56141. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56142. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56143. // Draw the frequency domain chart.
  56144. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56145. var value = workingArray[i];
  56146. var percent = value / this.BARGRAPHAMPLITUDE;
  56147. var height = this.DEBUGCANVASSIZE.height * percent;
  56148. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56149. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56150. var hue = i / this.getFrequencyBinCount() * 360;
  56151. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56152. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56153. }
  56154. }
  56155. }
  56156. };
  56157. Analyser.prototype.stopDebugCanvas = function () {
  56158. if (this._debugCanvas) {
  56159. if (this._registerFunc) {
  56160. this._scene.unregisterBeforeRender(this._registerFunc);
  56161. this._registerFunc = null;
  56162. }
  56163. document.body.removeChild(this._debugCanvas);
  56164. this._debugCanvas = null;
  56165. this._debugCanvasContext = null;
  56166. }
  56167. };
  56168. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56169. if (this._audioEngine.canUseWebAudio) {
  56170. inputAudioNode.connect(this._webAudioAnalyser);
  56171. this._webAudioAnalyser.connect(outputAudioNode);
  56172. }
  56173. };
  56174. Analyser.prototype.dispose = function () {
  56175. if (this._audioEngine.canUseWebAudio) {
  56176. this._webAudioAnalyser.disconnect();
  56177. }
  56178. };
  56179. return Analyser;
  56180. }());
  56181. BABYLON.Analyser = Analyser;
  56182. })(BABYLON || (BABYLON = {}));
  56183. //# sourceMappingURL=babylon.analyser.js.map
  56184. var BABYLON;
  56185. (function (BABYLON) {
  56186. var CubeTexture = /** @class */ (function (_super) {
  56187. __extends(CubeTexture, _super);
  56188. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56189. if (extensions === void 0) { extensions = null; }
  56190. if (noMipmap === void 0) { noMipmap = false; }
  56191. if (files === void 0) { files = null; }
  56192. if (onLoad === void 0) { onLoad = null; }
  56193. if (onError === void 0) { onError = null; }
  56194. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56195. if (prefiltered === void 0) { prefiltered = false; }
  56196. if (forcedExtension === void 0) { forcedExtension = null; }
  56197. var _this = _super.call(this, scene) || this;
  56198. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56199. /**
  56200. * Gets or sets the center of the bounding box associated with the cube texture
  56201. * It must define where the camera used to render the texture was set
  56202. */
  56203. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56204. _this.name = rootUrl;
  56205. _this.url = rootUrl;
  56206. _this._noMipmap = noMipmap;
  56207. _this.hasAlpha = false;
  56208. _this._format = format;
  56209. _this._prefiltered = prefiltered;
  56210. _this.isCube = true;
  56211. _this._textureMatrix = BABYLON.Matrix.Identity();
  56212. if (prefiltered) {
  56213. _this.gammaSpace = false;
  56214. }
  56215. if (!rootUrl && !files) {
  56216. return _this;
  56217. }
  56218. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56219. var lastDot = rootUrl.lastIndexOf(".");
  56220. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56221. var isDDS = (extension === ".dds");
  56222. if (!files) {
  56223. if (!isDDS && !extensions) {
  56224. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56225. }
  56226. files = [];
  56227. if (extensions) {
  56228. for (var index = 0; index < extensions.length; index++) {
  56229. files.push(rootUrl + extensions[index]);
  56230. }
  56231. }
  56232. }
  56233. _this._files = files;
  56234. if (!_this._texture) {
  56235. if (!scene.useDelayedTextureLoading) {
  56236. if (prefiltered) {
  56237. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56238. }
  56239. else {
  56240. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56241. }
  56242. }
  56243. else {
  56244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56245. }
  56246. }
  56247. else if (onLoad) {
  56248. if (_this._texture.isReady) {
  56249. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56250. }
  56251. else {
  56252. _this._texture.onLoadedObservable.add(onLoad);
  56253. }
  56254. }
  56255. return _this;
  56256. }
  56257. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56258. get: function () {
  56259. return this._boundingBoxSize;
  56260. },
  56261. /**
  56262. * Gets or sets the size of the bounding box associated with the cube texture
  56263. * When defined, the cubemap will switch to local mode
  56264. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56265. * @example https://www.babylonjs-playground.com/#RNASML
  56266. */
  56267. set: function (value) {
  56268. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56269. return;
  56270. }
  56271. this._boundingBoxSize = value;
  56272. var scene = this.getScene();
  56273. if (scene) {
  56274. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56275. }
  56276. },
  56277. enumerable: true,
  56278. configurable: true
  56279. });
  56280. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56281. return new CubeTexture("", scene, null, noMipmap, files);
  56282. };
  56283. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56284. if (forcedExtension === void 0) { forcedExtension = null; }
  56285. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56286. };
  56287. // Methods
  56288. CubeTexture.prototype.delayLoad = function () {
  56289. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56290. return;
  56291. }
  56292. var scene = this.getScene();
  56293. if (!scene) {
  56294. return;
  56295. }
  56296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56297. this._texture = this._getFromCache(this.url, this._noMipmap);
  56298. if (!this._texture) {
  56299. if (this._prefiltered) {
  56300. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56301. }
  56302. else {
  56303. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56304. }
  56305. }
  56306. };
  56307. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56308. return this._textureMatrix;
  56309. };
  56310. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56311. this._textureMatrix = value;
  56312. };
  56313. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56314. var texture = BABYLON.SerializationHelper.Parse(function () {
  56315. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56316. }, parsedTexture, scene);
  56317. // Animations
  56318. if (parsedTexture.animations) {
  56319. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56320. var parsedAnimation = parsedTexture.animations[animationIndex];
  56321. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56322. }
  56323. }
  56324. return texture;
  56325. };
  56326. CubeTexture.prototype.clone = function () {
  56327. var _this = this;
  56328. return BABYLON.SerializationHelper.Clone(function () {
  56329. var scene = _this.getScene();
  56330. if (!scene) {
  56331. return _this;
  56332. }
  56333. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56334. }, this);
  56335. };
  56336. return CubeTexture;
  56337. }(BABYLON.BaseTexture));
  56338. BABYLON.CubeTexture = CubeTexture;
  56339. })(BABYLON || (BABYLON = {}));
  56340. //# sourceMappingURL=babylon.cubeTexture.js.map
  56341. var BABYLON;
  56342. (function (BABYLON) {
  56343. var RenderTargetTexture = /** @class */ (function (_super) {
  56344. __extends(RenderTargetTexture, _super);
  56345. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56346. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56347. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56348. if (isCube === void 0) { isCube = false; }
  56349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56350. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56351. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56352. if (isMulti === void 0) { isMulti = false; }
  56353. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56354. _this.isCube = isCube;
  56355. /**
  56356. * Use this list to define the list of mesh you want to render.
  56357. */
  56358. _this.renderList = new Array();
  56359. _this.renderParticles = true;
  56360. _this.renderSprites = false;
  56361. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56362. _this.ignoreCameraViewport = false;
  56363. // Events
  56364. /**
  56365. * An event triggered when the texture is unbind.
  56366. * @type {BABYLON.Observable}
  56367. */
  56368. _this.onBeforeBindObservable = new BABYLON.Observable();
  56369. /**
  56370. * An event triggered when the texture is unbind.
  56371. * @type {BABYLON.Observable}
  56372. */
  56373. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56374. /**
  56375. * An event triggered before rendering the texture
  56376. * @type {BABYLON.Observable}
  56377. */
  56378. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56379. /**
  56380. * An event triggered after rendering the texture
  56381. * @type {BABYLON.Observable}
  56382. */
  56383. _this.onAfterRenderObservable = new BABYLON.Observable();
  56384. /**
  56385. * An event triggered after the texture clear
  56386. * @type {BABYLON.Observable}
  56387. */
  56388. _this.onClearObservable = new BABYLON.Observable();
  56389. _this._currentRefreshId = -1;
  56390. _this._refreshRate = 1;
  56391. _this._samples = 1;
  56392. /**
  56393. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56394. * It must define where the camera used to render the texture is set
  56395. */
  56396. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56397. scene = _this.getScene();
  56398. if (!scene) {
  56399. return _this;
  56400. }
  56401. _this._engine = scene.getEngine();
  56402. _this.name = name;
  56403. _this.isRenderTarget = true;
  56404. _this._initialSizeParameter = size;
  56405. _this._processSizeParameter(size);
  56406. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56407. });
  56408. _this._generateMipMaps = generateMipMaps ? true : false;
  56409. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56410. // Rendering groups
  56411. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56412. if (isMulti) {
  56413. return _this;
  56414. }
  56415. _this._renderTargetOptions = {
  56416. generateMipMaps: generateMipMaps,
  56417. type: type,
  56418. samplingMode: samplingMode,
  56419. generateDepthBuffer: generateDepthBuffer,
  56420. generateStencilBuffer: generateStencilBuffer
  56421. };
  56422. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56423. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56424. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56425. }
  56426. if (isCube) {
  56427. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56428. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56429. _this._textureMatrix = BABYLON.Matrix.Identity();
  56430. }
  56431. else {
  56432. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56433. }
  56434. return _this;
  56435. }
  56436. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56437. get: function () {
  56438. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56439. },
  56440. enumerable: true,
  56441. configurable: true
  56442. });
  56443. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56444. get: function () {
  56445. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56446. },
  56447. enumerable: true,
  56448. configurable: true
  56449. });
  56450. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56451. get: function () {
  56452. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56453. },
  56454. enumerable: true,
  56455. configurable: true
  56456. });
  56457. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56458. set: function (callback) {
  56459. if (this._onAfterUnbindObserver) {
  56460. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56461. }
  56462. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56463. },
  56464. enumerable: true,
  56465. configurable: true
  56466. });
  56467. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56468. set: function (callback) {
  56469. if (this._onBeforeRenderObserver) {
  56470. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56471. }
  56472. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56473. },
  56474. enumerable: true,
  56475. configurable: true
  56476. });
  56477. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56478. set: function (callback) {
  56479. if (this._onAfterRenderObserver) {
  56480. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56481. }
  56482. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56483. },
  56484. enumerable: true,
  56485. configurable: true
  56486. });
  56487. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56488. set: function (callback) {
  56489. if (this._onClearObserver) {
  56490. this.onClearObservable.remove(this._onClearObserver);
  56491. }
  56492. this._onClearObserver = this.onClearObservable.add(callback);
  56493. },
  56494. enumerable: true,
  56495. configurable: true
  56496. });
  56497. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56498. get: function () {
  56499. return this._renderTargetOptions;
  56500. },
  56501. enumerable: true,
  56502. configurable: true
  56503. });
  56504. RenderTargetTexture.prototype._onRatioRescale = function () {
  56505. if (this._sizeRatio) {
  56506. this.resize(this._initialSizeParameter);
  56507. }
  56508. };
  56509. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56510. get: function () {
  56511. return this._boundingBoxSize;
  56512. },
  56513. /**
  56514. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56515. * When defined, the cubemap will switch to local mode
  56516. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56517. * @example https://www.babylonjs-playground.com/#RNASML
  56518. */
  56519. set: function (value) {
  56520. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56521. return;
  56522. }
  56523. this._boundingBoxSize = value;
  56524. var scene = this.getScene();
  56525. if (scene) {
  56526. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56527. }
  56528. },
  56529. enumerable: true,
  56530. configurable: true
  56531. });
  56532. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56533. if (size.ratio) {
  56534. this._sizeRatio = size.ratio;
  56535. this._size = {
  56536. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56537. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56538. };
  56539. }
  56540. else {
  56541. this._size = size;
  56542. }
  56543. };
  56544. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56545. get: function () {
  56546. return this._samples;
  56547. },
  56548. set: function (value) {
  56549. if (this._samples === value) {
  56550. return;
  56551. }
  56552. var scene = this.getScene();
  56553. if (!scene) {
  56554. return;
  56555. }
  56556. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56557. },
  56558. enumerable: true,
  56559. configurable: true
  56560. });
  56561. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56562. this._currentRefreshId = -1;
  56563. };
  56564. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56565. get: function () {
  56566. return this._refreshRate;
  56567. },
  56568. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56569. set: function (value) {
  56570. this._refreshRate = value;
  56571. this.resetRefreshCounter();
  56572. },
  56573. enumerable: true,
  56574. configurable: true
  56575. });
  56576. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56577. if (!this._postProcessManager) {
  56578. var scene = this.getScene();
  56579. if (!scene) {
  56580. return;
  56581. }
  56582. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56583. this._postProcesses = new Array();
  56584. }
  56585. this._postProcesses.push(postProcess);
  56586. this._postProcesses[0].autoClear = false;
  56587. };
  56588. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56589. if (!this._postProcesses) {
  56590. return;
  56591. }
  56592. if (dispose) {
  56593. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56594. var postProcess = _a[_i];
  56595. postProcess.dispose();
  56596. }
  56597. }
  56598. this._postProcesses = [];
  56599. };
  56600. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56601. if (!this._postProcesses) {
  56602. return;
  56603. }
  56604. var index = this._postProcesses.indexOf(postProcess);
  56605. if (index === -1) {
  56606. return;
  56607. }
  56608. this._postProcesses.splice(index, 1);
  56609. if (this._postProcesses.length > 0) {
  56610. this._postProcesses[0].autoClear = false;
  56611. }
  56612. };
  56613. RenderTargetTexture.prototype._shouldRender = function () {
  56614. if (this._currentRefreshId === -1) {
  56615. this._currentRefreshId = 1;
  56616. return true;
  56617. }
  56618. if (this.refreshRate === this._currentRefreshId) {
  56619. this._currentRefreshId = 1;
  56620. return true;
  56621. }
  56622. this._currentRefreshId++;
  56623. return false;
  56624. };
  56625. RenderTargetTexture.prototype.getRenderSize = function () {
  56626. if (this._size.width) {
  56627. return this._size.width;
  56628. }
  56629. return this._size;
  56630. };
  56631. RenderTargetTexture.prototype.getRenderWidth = function () {
  56632. if (this._size.width) {
  56633. return this._size.width;
  56634. }
  56635. return this._size;
  56636. };
  56637. RenderTargetTexture.prototype.getRenderHeight = function () {
  56638. if (this._size.width) {
  56639. return this._size.height;
  56640. }
  56641. return this._size;
  56642. };
  56643. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56644. get: function () {
  56645. return true;
  56646. },
  56647. enumerable: true,
  56648. configurable: true
  56649. });
  56650. RenderTargetTexture.prototype.scale = function (ratio) {
  56651. var newSize = this.getRenderSize() * ratio;
  56652. this.resize(newSize);
  56653. };
  56654. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56655. if (this.isCube) {
  56656. return this._textureMatrix;
  56657. }
  56658. return _super.prototype.getReflectionTextureMatrix.call(this);
  56659. };
  56660. RenderTargetTexture.prototype.resize = function (size) {
  56661. this.releaseInternalTexture();
  56662. var scene = this.getScene();
  56663. if (!scene) {
  56664. return;
  56665. }
  56666. this._processSizeParameter(size);
  56667. if (this.isCube) {
  56668. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56669. }
  56670. else {
  56671. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56672. }
  56673. };
  56674. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56675. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56676. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56677. var scene = this.getScene();
  56678. if (!scene) {
  56679. return;
  56680. }
  56681. var engine = scene.getEngine();
  56682. if (this.useCameraPostProcesses !== undefined) {
  56683. useCameraPostProcess = this.useCameraPostProcesses;
  56684. }
  56685. if (this._waitingRenderList) {
  56686. this.renderList = [];
  56687. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56688. var id = this._waitingRenderList[index];
  56689. var mesh_1 = scene.getMeshByID(id);
  56690. if (mesh_1) {
  56691. this.renderList.push(mesh_1);
  56692. }
  56693. }
  56694. delete this._waitingRenderList;
  56695. }
  56696. // Is predicate defined?
  56697. if (this.renderListPredicate) {
  56698. if (this.renderList) {
  56699. this.renderList.splice(0); // Clear previous renderList
  56700. }
  56701. else {
  56702. this.renderList = [];
  56703. }
  56704. var scene = this.getScene();
  56705. if (!scene) {
  56706. return;
  56707. }
  56708. var sceneMeshes = scene.meshes;
  56709. for (var index = 0; index < sceneMeshes.length; index++) {
  56710. var mesh = sceneMeshes[index];
  56711. if (this.renderListPredicate(mesh)) {
  56712. this.renderList.push(mesh);
  56713. }
  56714. }
  56715. }
  56716. this.onBeforeBindObservable.notifyObservers(this);
  56717. // Set custom projection.
  56718. // Needs to be before binding to prevent changing the aspect ratio.
  56719. var camera;
  56720. if (this.activeCamera) {
  56721. camera = this.activeCamera;
  56722. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56723. if (this.activeCamera !== scene.activeCamera) {
  56724. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56725. }
  56726. }
  56727. else {
  56728. camera = scene.activeCamera;
  56729. if (camera) {
  56730. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56731. }
  56732. }
  56733. // Prepare renderingManager
  56734. this._renderingManager.reset();
  56735. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56736. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56737. var sceneRenderId = scene.getRenderId();
  56738. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56739. var mesh = currentRenderList[meshIndex];
  56740. if (mesh) {
  56741. if (!mesh.isReady()) {
  56742. // Reset _currentRefreshId
  56743. this.resetRefreshCounter();
  56744. continue;
  56745. }
  56746. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56747. var isMasked = void 0;
  56748. if (!this.renderList && camera) {
  56749. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56750. }
  56751. else {
  56752. isMasked = false;
  56753. }
  56754. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56755. mesh._activate(sceneRenderId);
  56756. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56757. var subMesh = mesh.subMeshes[subIndex];
  56758. scene._activeIndices.addCount(subMesh.indexCount, false);
  56759. this._renderingManager.dispatch(subMesh, mesh);
  56760. }
  56761. }
  56762. }
  56763. }
  56764. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56765. var particleSystem = scene.particleSystems[particleIndex];
  56766. var emitter = particleSystem.emitter;
  56767. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56768. continue;
  56769. }
  56770. if (currentRenderList.indexOf(emitter) >= 0) {
  56771. this._renderingManager.dispatchParticles(particleSystem);
  56772. }
  56773. }
  56774. if (this.isCube) {
  56775. for (var face = 0; face < 6; face++) {
  56776. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56777. scene.incrementRenderId();
  56778. scene.resetCachedMaterial();
  56779. }
  56780. }
  56781. else {
  56782. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56783. }
  56784. this.onAfterUnbindObservable.notifyObservers(this);
  56785. if (scene.activeCamera) {
  56786. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56787. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56788. }
  56789. engine.setViewport(scene.activeCamera.viewport);
  56790. }
  56791. scene.resetCachedMaterial();
  56792. };
  56793. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56794. var minimum = 128;
  56795. var x = renderDimension * scale;
  56796. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56797. // Ensure we don't exceed the render dimension (while staying POT)
  56798. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56799. };
  56800. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56801. var _this = this;
  56802. if (!this._texture) {
  56803. return;
  56804. }
  56805. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56806. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56807. });
  56808. };
  56809. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56810. var scene = this.getScene();
  56811. if (!scene) {
  56812. return;
  56813. }
  56814. var engine = scene.getEngine();
  56815. if (!this._texture) {
  56816. return;
  56817. }
  56818. // Bind
  56819. if (this._postProcessManager) {
  56820. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56821. }
  56822. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56823. if (this._texture) {
  56824. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56825. }
  56826. }
  56827. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56828. // Clear
  56829. if (this.onClearObservable.hasObservers()) {
  56830. this.onClearObservable.notifyObservers(engine);
  56831. }
  56832. else {
  56833. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56834. }
  56835. if (!this._doNotChangeAspectRatio) {
  56836. scene.updateTransformMatrix(true);
  56837. }
  56838. // Render
  56839. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56840. if (this._postProcessManager) {
  56841. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56842. }
  56843. else if (useCameraPostProcess) {
  56844. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56845. }
  56846. if (!this._doNotChangeAspectRatio) {
  56847. scene.updateTransformMatrix(true);
  56848. }
  56849. // Dump ?
  56850. if (dumpForDebug) {
  56851. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56852. }
  56853. // Unbind
  56854. if (!this.isCube || faceIndex === 5) {
  56855. if (this.isCube) {
  56856. if (faceIndex === 5) {
  56857. engine.generateMipMapsForCubemap(this._texture);
  56858. }
  56859. }
  56860. this.unbindFrameBuffer(engine, faceIndex);
  56861. }
  56862. else {
  56863. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56864. }
  56865. };
  56866. /**
  56867. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56868. * This allowed control for front to back rendering or reversly depending of the special needs.
  56869. *
  56870. * @param renderingGroupId The rendering group id corresponding to its index
  56871. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56872. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56873. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56874. */
  56875. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56876. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56877. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56878. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56879. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56880. };
  56881. /**
  56882. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56883. *
  56884. * @param renderingGroupId The rendering group id corresponding to its index
  56885. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56886. */
  56887. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56888. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56889. };
  56890. RenderTargetTexture.prototype.clone = function () {
  56891. var textureSize = this.getSize();
  56892. 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);
  56893. // Base texture
  56894. newTexture.hasAlpha = this.hasAlpha;
  56895. newTexture.level = this.level;
  56896. // RenderTarget Texture
  56897. newTexture.coordinatesMode = this.coordinatesMode;
  56898. if (this.renderList) {
  56899. newTexture.renderList = this.renderList.slice(0);
  56900. }
  56901. return newTexture;
  56902. };
  56903. RenderTargetTexture.prototype.serialize = function () {
  56904. if (!this.name) {
  56905. return null;
  56906. }
  56907. var serializationObject = _super.prototype.serialize.call(this);
  56908. serializationObject.renderTargetSize = this.getRenderSize();
  56909. serializationObject.renderList = [];
  56910. if (this.renderList) {
  56911. for (var index = 0; index < this.renderList.length; index++) {
  56912. serializationObject.renderList.push(this.renderList[index].id);
  56913. }
  56914. }
  56915. return serializationObject;
  56916. };
  56917. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56918. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56919. var objBuffer = this.getInternalTexture();
  56920. var scene = this.getScene();
  56921. if (objBuffer && scene) {
  56922. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56923. }
  56924. };
  56925. RenderTargetTexture.prototype.dispose = function () {
  56926. if (this._postProcessManager) {
  56927. this._postProcessManager.dispose();
  56928. this._postProcessManager = null;
  56929. }
  56930. this.clearPostProcesses(true);
  56931. if (this._resizeObserver) {
  56932. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56933. this._resizeObserver = null;
  56934. }
  56935. this.renderList = null;
  56936. // Remove from custom render targets
  56937. var scene = this.getScene();
  56938. if (!scene) {
  56939. return;
  56940. }
  56941. var index = scene.customRenderTargets.indexOf(this);
  56942. if (index >= 0) {
  56943. scene.customRenderTargets.splice(index, 1);
  56944. }
  56945. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56946. var camera = _a[_i];
  56947. index = camera.customRenderTargets.indexOf(this);
  56948. if (index >= 0) {
  56949. camera.customRenderTargets.splice(index, 1);
  56950. }
  56951. }
  56952. _super.prototype.dispose.call(this);
  56953. };
  56954. RenderTargetTexture.prototype._rebuild = function () {
  56955. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56956. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56957. }
  56958. if (this._postProcessManager) {
  56959. this._postProcessManager._rebuild();
  56960. }
  56961. };
  56962. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56963. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56964. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56965. return RenderTargetTexture;
  56966. }(BABYLON.Texture));
  56967. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56968. })(BABYLON || (BABYLON = {}));
  56969. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56970. var BABYLON;
  56971. (function (BABYLON) {
  56972. ;
  56973. var MultiRenderTarget = /** @class */ (function (_super) {
  56974. __extends(MultiRenderTarget, _super);
  56975. function MultiRenderTarget(name, size, count, scene, options) {
  56976. var _this = this;
  56977. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56978. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56979. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56980. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56981. _this._engine = scene.getEngine();
  56982. if (!_this.isSupported) {
  56983. _this.dispose();
  56984. return;
  56985. }
  56986. var types = [];
  56987. var samplingModes = [];
  56988. for (var i = 0; i < count; i++) {
  56989. if (options && options.types && options.types[i] !== undefined) {
  56990. types.push(options.types[i]);
  56991. }
  56992. else {
  56993. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56994. }
  56995. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56996. samplingModes.push(options.samplingModes[i]);
  56997. }
  56998. else {
  56999. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57000. }
  57001. }
  57002. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57003. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57004. _this._size = size;
  57005. _this._multiRenderTargetOptions = {
  57006. samplingModes: samplingModes,
  57007. generateMipMaps: generateMipMaps,
  57008. generateDepthBuffer: generateDepthBuffer,
  57009. generateStencilBuffer: generateStencilBuffer,
  57010. generateDepthTexture: generateDepthTexture,
  57011. types: types,
  57012. textureCount: count
  57013. };
  57014. _this._createInternalTextures();
  57015. _this._createTextures();
  57016. return _this;
  57017. }
  57018. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57019. get: function () {
  57020. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57021. },
  57022. enumerable: true,
  57023. configurable: true
  57024. });
  57025. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57026. get: function () {
  57027. return this._textures;
  57028. },
  57029. enumerable: true,
  57030. configurable: true
  57031. });
  57032. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57033. get: function () {
  57034. return this._textures[this._textures.length - 1];
  57035. },
  57036. enumerable: true,
  57037. configurable: true
  57038. });
  57039. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57040. set: function (wrap) {
  57041. if (this._textures) {
  57042. for (var i = 0; i < this._textures.length; i++) {
  57043. this._textures[i].wrapU = wrap;
  57044. }
  57045. }
  57046. },
  57047. enumerable: true,
  57048. configurable: true
  57049. });
  57050. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57051. set: function (wrap) {
  57052. if (this._textures) {
  57053. for (var i = 0; i < this._textures.length; i++) {
  57054. this._textures[i].wrapV = wrap;
  57055. }
  57056. }
  57057. },
  57058. enumerable: true,
  57059. configurable: true
  57060. });
  57061. MultiRenderTarget.prototype._rebuild = function () {
  57062. this.releaseInternalTextures();
  57063. this._createInternalTextures();
  57064. for (var i = 0; i < this._internalTextures.length; i++) {
  57065. var texture = this._textures[i];
  57066. texture._texture = this._internalTextures[i];
  57067. }
  57068. // Keeps references to frame buffer and stencil/depth buffer
  57069. this._texture = this._internalTextures[0];
  57070. };
  57071. MultiRenderTarget.prototype._createInternalTextures = function () {
  57072. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57073. };
  57074. MultiRenderTarget.prototype._createTextures = function () {
  57075. this._textures = [];
  57076. for (var i = 0; i < this._internalTextures.length; i++) {
  57077. var texture = new BABYLON.Texture(null, this.getScene());
  57078. texture._texture = this._internalTextures[i];
  57079. this._textures.push(texture);
  57080. }
  57081. // Keeps references to frame buffer and stencil/depth buffer
  57082. this._texture = this._internalTextures[0];
  57083. };
  57084. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57085. get: function () {
  57086. return this._samples;
  57087. },
  57088. set: function (value) {
  57089. if (this._samples === value) {
  57090. return;
  57091. }
  57092. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57093. },
  57094. enumerable: true,
  57095. configurable: true
  57096. });
  57097. MultiRenderTarget.prototype.resize = function (size) {
  57098. this.releaseInternalTextures();
  57099. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57100. this._createInternalTextures();
  57101. };
  57102. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57103. var _this = this;
  57104. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57105. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57106. });
  57107. };
  57108. MultiRenderTarget.prototype.dispose = function () {
  57109. this.releaseInternalTextures();
  57110. _super.prototype.dispose.call(this);
  57111. };
  57112. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57113. if (!this._internalTextures) {
  57114. return;
  57115. }
  57116. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57117. if (this._internalTextures[i] !== undefined) {
  57118. this._internalTextures[i].dispose();
  57119. this._internalTextures.splice(i, 1);
  57120. }
  57121. }
  57122. };
  57123. return MultiRenderTarget;
  57124. }(BABYLON.RenderTargetTexture));
  57125. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57126. })(BABYLON || (BABYLON = {}));
  57127. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57128. var BABYLON;
  57129. (function (BABYLON) {
  57130. var MirrorTexture = /** @class */ (function (_super) {
  57131. __extends(MirrorTexture, _super);
  57132. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57133. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57135. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57136. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57137. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57138. _this._transformMatrix = BABYLON.Matrix.Zero();
  57139. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57140. _this._adaptiveBlurKernel = 0;
  57141. _this._blurKernelX = 0;
  57142. _this._blurKernelY = 0;
  57143. _this._blurRatio = 1.0;
  57144. _this.ignoreCameraViewport = true;
  57145. _this.onBeforeRenderObservable.add(function () {
  57146. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57147. _this._savedViewMatrix = scene.getViewMatrix();
  57148. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57149. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57150. scene.clipPlane = _this.mirrorPlane;
  57151. scene.getEngine().cullBackFaces = false;
  57152. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57153. });
  57154. _this.onAfterRenderObservable.add(function () {
  57155. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57156. scene.getEngine().cullBackFaces = true;
  57157. scene._mirroredCameraPosition = null;
  57158. delete scene.clipPlane;
  57159. });
  57160. return _this;
  57161. }
  57162. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57163. get: function () {
  57164. return this._blurRatio;
  57165. },
  57166. set: function (value) {
  57167. if (this._blurRatio === value) {
  57168. return;
  57169. }
  57170. this._blurRatio = value;
  57171. this._preparePostProcesses();
  57172. },
  57173. enumerable: true,
  57174. configurable: true
  57175. });
  57176. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57177. set: function (value) {
  57178. this._adaptiveBlurKernel = value;
  57179. this._autoComputeBlurKernel();
  57180. },
  57181. enumerable: true,
  57182. configurable: true
  57183. });
  57184. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57185. set: function (value) {
  57186. this.blurKernelX = value;
  57187. this.blurKernelY = value;
  57188. },
  57189. enumerable: true,
  57190. configurable: true
  57191. });
  57192. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57193. get: function () {
  57194. return this._blurKernelX;
  57195. },
  57196. set: function (value) {
  57197. if (this._blurKernelX === value) {
  57198. return;
  57199. }
  57200. this._blurKernelX = value;
  57201. this._preparePostProcesses();
  57202. },
  57203. enumerable: true,
  57204. configurable: true
  57205. });
  57206. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57207. get: function () {
  57208. return this._blurKernelY;
  57209. },
  57210. set: function (value) {
  57211. if (this._blurKernelY === value) {
  57212. return;
  57213. }
  57214. this._blurKernelY = value;
  57215. this._preparePostProcesses();
  57216. },
  57217. enumerable: true,
  57218. configurable: true
  57219. });
  57220. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57221. var engine = this.getScene().getEngine();
  57222. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57223. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57224. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57225. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57226. };
  57227. MirrorTexture.prototype._onRatioRescale = function () {
  57228. if (this._sizeRatio) {
  57229. this.resize(this._initialSizeParameter);
  57230. if (!this._adaptiveBlurKernel) {
  57231. this._preparePostProcesses();
  57232. }
  57233. }
  57234. if (this._adaptiveBlurKernel) {
  57235. this._autoComputeBlurKernel();
  57236. }
  57237. };
  57238. MirrorTexture.prototype._preparePostProcesses = function () {
  57239. this.clearPostProcesses(true);
  57240. if (this._blurKernelX && this._blurKernelY) {
  57241. var engine = this.getScene().getEngine();
  57242. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57243. 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);
  57244. this._blurX.autoClear = false;
  57245. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57246. this._blurX.inputTexture = this._texture;
  57247. }
  57248. else {
  57249. this._blurX.alwaysForcePOT = true;
  57250. }
  57251. 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);
  57252. this._blurY.autoClear = false;
  57253. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57254. this.addPostProcess(this._blurX);
  57255. this.addPostProcess(this._blurY);
  57256. }
  57257. else {
  57258. if (this._blurY) {
  57259. this.removePostProcess(this._blurY);
  57260. this._blurY.dispose();
  57261. this._blurY = null;
  57262. }
  57263. if (this._blurX) {
  57264. this.removePostProcess(this._blurX);
  57265. this._blurX.dispose();
  57266. this._blurX = null;
  57267. }
  57268. }
  57269. };
  57270. MirrorTexture.prototype.clone = function () {
  57271. var scene = this.getScene();
  57272. if (!scene) {
  57273. return this;
  57274. }
  57275. var textureSize = this.getSize();
  57276. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57277. // Base texture
  57278. newTexture.hasAlpha = this.hasAlpha;
  57279. newTexture.level = this.level;
  57280. // Mirror Texture
  57281. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57282. if (this.renderList) {
  57283. newTexture.renderList = this.renderList.slice(0);
  57284. }
  57285. return newTexture;
  57286. };
  57287. MirrorTexture.prototype.serialize = function () {
  57288. if (!this.name) {
  57289. return null;
  57290. }
  57291. var serializationObject = _super.prototype.serialize.call(this);
  57292. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57293. return serializationObject;
  57294. };
  57295. return MirrorTexture;
  57296. }(BABYLON.RenderTargetTexture));
  57297. BABYLON.MirrorTexture = MirrorTexture;
  57298. })(BABYLON || (BABYLON = {}));
  57299. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57300. var BABYLON;
  57301. (function (BABYLON) {
  57302. /**
  57303. * Creates a refraction texture used by refraction channel of the standard material.
  57304. * @param name the texture name
  57305. * @param size size of the underlying texture
  57306. * @param scene root scene
  57307. */
  57308. var RefractionTexture = /** @class */ (function (_super) {
  57309. __extends(RefractionTexture, _super);
  57310. function RefractionTexture(name, size, scene, generateMipMaps) {
  57311. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57312. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57313. _this.depth = 2.0;
  57314. _this.onBeforeRenderObservable.add(function () {
  57315. scene.clipPlane = _this.refractionPlane;
  57316. });
  57317. _this.onAfterRenderObservable.add(function () {
  57318. delete scene.clipPlane;
  57319. });
  57320. return _this;
  57321. }
  57322. RefractionTexture.prototype.clone = function () {
  57323. var scene = this.getScene();
  57324. if (!scene) {
  57325. return this;
  57326. }
  57327. var textureSize = this.getSize();
  57328. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57329. // Base texture
  57330. newTexture.hasAlpha = this.hasAlpha;
  57331. newTexture.level = this.level;
  57332. // Refraction Texture
  57333. newTexture.refractionPlane = this.refractionPlane.clone();
  57334. if (this.renderList) {
  57335. newTexture.renderList = this.renderList.slice(0);
  57336. }
  57337. newTexture.depth = this.depth;
  57338. return newTexture;
  57339. };
  57340. RefractionTexture.prototype.serialize = function () {
  57341. if (!this.name) {
  57342. return null;
  57343. }
  57344. var serializationObject = _super.prototype.serialize.call(this);
  57345. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57346. serializationObject.depth = this.depth;
  57347. return serializationObject;
  57348. };
  57349. return RefractionTexture;
  57350. }(BABYLON.RenderTargetTexture));
  57351. BABYLON.RefractionTexture = RefractionTexture;
  57352. })(BABYLON || (BABYLON = {}));
  57353. //# sourceMappingURL=babylon.refractionTexture.js.map
  57354. var BABYLON;
  57355. (function (BABYLON) {
  57356. var DynamicTexture = /** @class */ (function (_super) {
  57357. __extends(DynamicTexture, _super);
  57358. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57359. if (scene === void 0) { scene = null; }
  57360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57361. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57362. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57363. _this.name = name;
  57364. _this._engine = _this.getScene().getEngine();
  57365. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57366. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57367. _this._generateMipMaps = generateMipMaps;
  57368. if (options.getContext) {
  57369. _this._canvas = options;
  57370. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57371. }
  57372. else {
  57373. _this._canvas = document.createElement("canvas");
  57374. if (options.width) {
  57375. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57376. }
  57377. else {
  57378. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57379. }
  57380. }
  57381. var textureSize = _this.getSize();
  57382. _this._canvas.width = textureSize.width;
  57383. _this._canvas.height = textureSize.height;
  57384. _this._context = _this._canvas.getContext("2d");
  57385. return _this;
  57386. }
  57387. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57388. get: function () {
  57389. return true;
  57390. },
  57391. enumerable: true,
  57392. configurable: true
  57393. });
  57394. DynamicTexture.prototype._recreate = function (textureSize) {
  57395. this._canvas.width = textureSize.width;
  57396. this._canvas.height = textureSize.height;
  57397. this.releaseInternalTexture();
  57398. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57399. };
  57400. DynamicTexture.prototype.scale = function (ratio) {
  57401. var textureSize = this.getSize();
  57402. textureSize.width *= ratio;
  57403. textureSize.height *= ratio;
  57404. this._recreate(textureSize);
  57405. };
  57406. DynamicTexture.prototype.scaleTo = function (width, height) {
  57407. var textureSize = this.getSize();
  57408. textureSize.width = width;
  57409. textureSize.height = height;
  57410. this._recreate(textureSize);
  57411. };
  57412. DynamicTexture.prototype.getContext = function () {
  57413. return this._context;
  57414. };
  57415. DynamicTexture.prototype.clear = function () {
  57416. var size = this.getSize();
  57417. this._context.fillRect(0, 0, size.width, size.height);
  57418. };
  57419. DynamicTexture.prototype.update = function (invertY) {
  57420. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57421. };
  57422. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57423. if (update === void 0) { update = true; }
  57424. var size = this.getSize();
  57425. if (clearColor) {
  57426. this._context.fillStyle = clearColor;
  57427. this._context.fillRect(0, 0, size.width, size.height);
  57428. }
  57429. this._context.font = font;
  57430. if (x === null || x === undefined) {
  57431. var textSize = this._context.measureText(text);
  57432. x = (size.width - textSize.width) / 2;
  57433. }
  57434. if (y === null || y === undefined) {
  57435. var fontSize = parseInt((font.replace(/\D/g, '')));
  57436. ;
  57437. y = (size.height / 2) + (fontSize / 3.65);
  57438. }
  57439. this._context.fillStyle = color;
  57440. this._context.fillText(text, x, y);
  57441. if (update) {
  57442. this.update(invertY);
  57443. }
  57444. };
  57445. DynamicTexture.prototype.clone = function () {
  57446. var scene = this.getScene();
  57447. if (!scene) {
  57448. return this;
  57449. }
  57450. var textureSize = this.getSize();
  57451. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57452. // Base texture
  57453. newTexture.hasAlpha = this.hasAlpha;
  57454. newTexture.level = this.level;
  57455. // Dynamic Texture
  57456. newTexture.wrapU = this.wrapU;
  57457. newTexture.wrapV = this.wrapV;
  57458. return newTexture;
  57459. };
  57460. DynamicTexture.prototype._rebuild = function () {
  57461. this.update();
  57462. };
  57463. return DynamicTexture;
  57464. }(BABYLON.Texture));
  57465. BABYLON.DynamicTexture = DynamicTexture;
  57466. })(BABYLON || (BABYLON = {}));
  57467. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57468. var BABYLON;
  57469. (function (BABYLON) {
  57470. var VideoTexture = /** @class */ (function (_super) {
  57471. __extends(VideoTexture, _super);
  57472. /**
  57473. * Creates a video texture.
  57474. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57475. * @param {string | null} name optional name, will detect from video source, if not defined
  57476. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57477. * @param {BABYLON.Scene} scene is obviously the current scene.
  57478. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57479. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57480. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57481. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57482. */
  57483. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57484. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57485. if (invertY === void 0) { invertY = false; }
  57486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57487. if (settings === void 0) { settings = {
  57488. autoPlay: true,
  57489. loop: true,
  57490. autoUpdateTexture: true,
  57491. }; }
  57492. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57493. _this._createInternalTexture = function () {
  57494. if (_this._texture != null) {
  57495. return;
  57496. }
  57497. if (!_this._engine.needPOTTextures ||
  57498. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57499. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57500. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57501. }
  57502. else {
  57503. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57504. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57505. _this._generateMipMaps = false;
  57506. }
  57507. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57508. _this._texture.isReady = true;
  57509. _this._updateInternalTexture();
  57510. };
  57511. _this.reset = function () {
  57512. if (_this._texture == null) {
  57513. return;
  57514. }
  57515. _this._texture.dispose();
  57516. _this._texture = null;
  57517. };
  57518. _this._updateInternalTexture = function (e) {
  57519. if (_this._texture == null || !_this._texture.isReady) {
  57520. return;
  57521. }
  57522. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57523. return;
  57524. }
  57525. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57526. };
  57527. _this._engine = _this.getScene().getEngine();
  57528. _this._generateMipMaps = generateMipMaps;
  57529. _this._samplingMode = samplingMode;
  57530. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57531. _this.name = name || _this._getName(src);
  57532. _this.video = _this._getVideo(src);
  57533. if (settings.autoPlay !== undefined) {
  57534. _this.video.autoplay = settings.autoPlay;
  57535. }
  57536. if (settings.loop !== undefined) {
  57537. _this.video.loop = settings.loop;
  57538. }
  57539. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57540. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57541. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57542. _this.video.addEventListener("emptied", _this.reset);
  57543. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57544. _this._createInternalTexture();
  57545. }
  57546. return _this;
  57547. }
  57548. VideoTexture.prototype._getName = function (src) {
  57549. if (src instanceof HTMLVideoElement) {
  57550. return src.currentSrc;
  57551. }
  57552. if (typeof src === "object") {
  57553. return src.toString();
  57554. }
  57555. return src;
  57556. };
  57557. ;
  57558. VideoTexture.prototype._getVideo = function (src) {
  57559. if (src instanceof HTMLVideoElement) {
  57560. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57561. return src;
  57562. }
  57563. var video = document.createElement("video");
  57564. if (typeof src === "string") {
  57565. BABYLON.Tools.SetCorsBehavior(src, video);
  57566. video.src = src;
  57567. }
  57568. else {
  57569. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57570. src.forEach(function (url) {
  57571. var source = document.createElement("source");
  57572. source.src = url;
  57573. video.appendChild(source);
  57574. });
  57575. }
  57576. return video;
  57577. };
  57578. ;
  57579. /**
  57580. * Internal method to initiate `update`.
  57581. */
  57582. VideoTexture.prototype._rebuild = function () {
  57583. this.update();
  57584. };
  57585. /**
  57586. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57587. */
  57588. VideoTexture.prototype.update = function () {
  57589. if (!this.autoUpdateTexture) {
  57590. // Expecting user to call `updateTexture` manually
  57591. return;
  57592. }
  57593. this.updateTexture(true);
  57594. };
  57595. /**
  57596. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57597. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57598. */
  57599. VideoTexture.prototype.updateTexture = function (isVisible) {
  57600. if (!isVisible) {
  57601. return;
  57602. }
  57603. if (this.video.paused) {
  57604. return;
  57605. }
  57606. this._updateInternalTexture();
  57607. };
  57608. /**
  57609. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57610. * @param url New url.
  57611. */
  57612. VideoTexture.prototype.updateURL = function (url) {
  57613. this.video.src = url;
  57614. };
  57615. VideoTexture.prototype.dispose = function () {
  57616. _super.prototype.dispose.call(this);
  57617. this.video.removeEventListener("canplay", this._createInternalTexture);
  57618. this.video.removeEventListener("paused", this._updateInternalTexture);
  57619. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57620. this.video.removeEventListener("emptied", this.reset);
  57621. };
  57622. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57623. var video = document.createElement("video");
  57624. var constraintsDeviceId;
  57625. if (constraints && constraints.deviceId) {
  57626. constraintsDeviceId = {
  57627. exact: constraints.deviceId,
  57628. };
  57629. }
  57630. navigator.getUserMedia =
  57631. navigator.getUserMedia ||
  57632. navigator.webkitGetUserMedia ||
  57633. navigator.mozGetUserMedia ||
  57634. navigator.msGetUserMedia;
  57635. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57636. if (navigator.getUserMedia) {
  57637. navigator.getUserMedia({
  57638. video: {
  57639. deviceId: constraintsDeviceId,
  57640. width: {
  57641. min: (constraints && constraints.minWidth) || 256,
  57642. max: (constraints && constraints.maxWidth) || 640,
  57643. },
  57644. height: {
  57645. min: (constraints && constraints.minHeight) || 256,
  57646. max: (constraints && constraints.maxHeight) || 480,
  57647. },
  57648. },
  57649. }, function (stream) {
  57650. if (video.mozSrcObject !== undefined) {
  57651. // hack for Firefox < 19
  57652. video.mozSrcObject = stream;
  57653. }
  57654. else {
  57655. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57656. }
  57657. video.play();
  57658. if (onReady) {
  57659. onReady(new VideoTexture("video", video, scene, true, true));
  57660. }
  57661. }, function (e) {
  57662. BABYLON.Tools.Error(e.name);
  57663. });
  57664. }
  57665. };
  57666. return VideoTexture;
  57667. }(BABYLON.Texture));
  57668. BABYLON.VideoTexture = VideoTexture;
  57669. })(BABYLON || (BABYLON = {}));
  57670. //# sourceMappingURL=babylon.videoTexture.js.map
  57671. var BABYLON;
  57672. (function (BABYLON) {
  57673. var RawTexture = /** @class */ (function (_super) {
  57674. __extends(RawTexture, _super);
  57675. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57677. if (invertY === void 0) { invertY = false; }
  57678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57679. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57680. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57681. _this.format = format;
  57682. _this._engine = scene.getEngine();
  57683. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57684. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57685. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57686. return _this;
  57687. }
  57688. RawTexture.prototype.update = function (data) {
  57689. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57690. };
  57691. // Statics
  57692. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57693. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57694. if (invertY === void 0) { invertY = false; }
  57695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57696. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57697. };
  57698. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57699. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57700. if (invertY === void 0) { invertY = false; }
  57701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57702. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57703. };
  57704. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57705. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57706. if (invertY === void 0) { invertY = false; }
  57707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57708. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57709. };
  57710. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57711. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57712. if (invertY === void 0) { invertY = false; }
  57713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57714. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57715. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57716. };
  57717. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57718. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57719. if (invertY === void 0) { invertY = false; }
  57720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57722. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57723. };
  57724. return RawTexture;
  57725. }(BABYLON.Texture));
  57726. BABYLON.RawTexture = RawTexture;
  57727. })(BABYLON || (BABYLON = {}));
  57728. //# sourceMappingURL=babylon.rawTexture.js.map
  57729. var BABYLON;
  57730. (function (BABYLON) {
  57731. /**
  57732. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57733. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57734. */
  57735. var PostProcess = /** @class */ (function () {
  57736. /**
  57737. * Creates a new instance of @see PostProcess
  57738. * @param name The name of the PostProcess.
  57739. * @param fragmentUrl The url of the fragment shader to be used.
  57740. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57741. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57742. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57743. * @param camera The camera to apply the render pass to.
  57744. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57745. * @param engine The engine which the post process will be applied. (default: current engine)
  57746. * @param reusable If the post process can be reused on the same frame. (default: false)
  57747. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57748. * @param textureType Type of textures used when performing the post process. (default: 0)
  57749. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57750. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  57751. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57752. */
  57753. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57755. if (defines === void 0) { defines = null; }
  57756. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57757. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57758. if (blockCompilation === void 0) { blockCompilation = false; }
  57759. this.name = name;
  57760. /**
  57761. * Width of the texture to apply the post process on
  57762. */
  57763. this.width = -1;
  57764. /**
  57765. * Height of the texture to apply the post process on
  57766. */
  57767. this.height = -1;
  57768. /**
  57769. * If the buffer needs to be cleared before applying the post process. (default: true)
  57770. * Should be set to false if shader will overwrite all previous pixels.
  57771. */
  57772. this.autoClear = true;
  57773. /**
  57774. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57775. */
  57776. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57777. /**
  57778. * Animations to be used for the post processing
  57779. */
  57780. this.animations = new Array();
  57781. /**
  57782. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57783. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57784. */
  57785. this.enablePixelPerfectMode = false;
  57786. /**
  57787. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57788. */
  57789. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57790. /**
  57791. * Force textures to be a power of two (default: false)
  57792. */
  57793. this.alwaysForcePOT = false;
  57794. /**
  57795. * Number of sample textures (default: 1)
  57796. */
  57797. this.samples = 1;
  57798. /**
  57799. * Modify the scale of the post process to be the same as the viewport (default: false)
  57800. */
  57801. this.adaptScaleToCurrentViewport = false;
  57802. this._reusable = false;
  57803. /**
  57804. * Smart array of input and output textures for the post process.
  57805. */
  57806. this._textures = new BABYLON.SmartArray(2);
  57807. /**
  57808. * The index in _textures that corresponds to the output texture.
  57809. */
  57810. this._currentRenderTextureInd = 0;
  57811. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57812. this._texelSize = BABYLON.Vector2.Zero();
  57813. // Events
  57814. /**
  57815. * An event triggered when the postprocess is activated.
  57816. * @type {BABYLON.Observable}
  57817. */
  57818. this.onActivateObservable = new BABYLON.Observable();
  57819. /**
  57820. * An event triggered when the postprocess changes its size.
  57821. * @type {BABYLON.Observable}
  57822. */
  57823. this.onSizeChangedObservable = new BABYLON.Observable();
  57824. /**
  57825. * An event triggered when the postprocess applies its effect.
  57826. * @type {BABYLON.Observable}
  57827. */
  57828. this.onApplyObservable = new BABYLON.Observable();
  57829. /**
  57830. * An event triggered before rendering the postprocess
  57831. * @type {BABYLON.Observable}
  57832. */
  57833. this.onBeforeRenderObservable = new BABYLON.Observable();
  57834. /**
  57835. * An event triggered after rendering the postprocess
  57836. * @type {BABYLON.Observable}
  57837. */
  57838. this.onAfterRenderObservable = new BABYLON.Observable();
  57839. if (camera != null) {
  57840. this._camera = camera;
  57841. this._scene = camera.getScene();
  57842. camera.attachPostProcess(this);
  57843. this._engine = this._scene.getEngine();
  57844. this._scene.postProcesses.push(this);
  57845. }
  57846. else if (engine) {
  57847. this._engine = engine;
  57848. this._engine.postProcesses.push(this);
  57849. }
  57850. this._options = options;
  57851. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57852. this._reusable = reusable || false;
  57853. this._textureType = textureType;
  57854. this._samplers = samplers || [];
  57855. this._samplers.push("textureSampler");
  57856. this._fragmentUrl = fragmentUrl;
  57857. this._vertexUrl = vertexUrl;
  57858. this._parameters = parameters || [];
  57859. this._parameters.push("scale");
  57860. this._indexParameters = indexParameters;
  57861. if (!blockCompilation) {
  57862. this.updateEffect(defines);
  57863. }
  57864. }
  57865. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57866. /**
  57867. * A function that is added to the onActivateObservable
  57868. */
  57869. set: function (callback) {
  57870. if (this._onActivateObserver) {
  57871. this.onActivateObservable.remove(this._onActivateObserver);
  57872. }
  57873. if (callback) {
  57874. this._onActivateObserver = this.onActivateObservable.add(callback);
  57875. }
  57876. },
  57877. enumerable: true,
  57878. configurable: true
  57879. });
  57880. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57881. /**
  57882. * A function that is added to the onSizeChangedObservable
  57883. */
  57884. set: function (callback) {
  57885. if (this._onSizeChangedObserver) {
  57886. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57887. }
  57888. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57889. },
  57890. enumerable: true,
  57891. configurable: true
  57892. });
  57893. Object.defineProperty(PostProcess.prototype, "onApply", {
  57894. /**
  57895. * A function that is added to the onApplyObservable
  57896. */
  57897. set: function (callback) {
  57898. if (this._onApplyObserver) {
  57899. this.onApplyObservable.remove(this._onApplyObserver);
  57900. }
  57901. this._onApplyObserver = this.onApplyObservable.add(callback);
  57902. },
  57903. enumerable: true,
  57904. configurable: true
  57905. });
  57906. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57907. /**
  57908. * A function that is added to the onBeforeRenderObservable
  57909. */
  57910. set: function (callback) {
  57911. if (this._onBeforeRenderObserver) {
  57912. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57913. }
  57914. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57915. },
  57916. enumerable: true,
  57917. configurable: true
  57918. });
  57919. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57920. /**
  57921. * A function that is added to the onAfterRenderObservable
  57922. */
  57923. set: function (callback) {
  57924. if (this._onAfterRenderObserver) {
  57925. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57926. }
  57927. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57928. },
  57929. enumerable: true,
  57930. configurable: true
  57931. });
  57932. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57933. /**
  57934. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  57935. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57936. */
  57937. get: function () {
  57938. return this._textures.data[this._currentRenderTextureInd];
  57939. },
  57940. set: function (value) {
  57941. this._forcedOutputTexture = value;
  57942. },
  57943. enumerable: true,
  57944. configurable: true
  57945. });
  57946. /**
  57947. * Gets the camera which post process is applied to.
  57948. * @returns The camera the post process is applied to.
  57949. */
  57950. PostProcess.prototype.getCamera = function () {
  57951. return this._camera;
  57952. };
  57953. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57954. /**
  57955. * Gets the texel size of the postprocess.
  57956. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57957. */
  57958. get: function () {
  57959. if (this._shareOutputWithPostProcess) {
  57960. return this._shareOutputWithPostProcess.texelSize;
  57961. }
  57962. if (this._forcedOutputTexture) {
  57963. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57964. }
  57965. return this._texelSize;
  57966. },
  57967. enumerable: true,
  57968. configurable: true
  57969. });
  57970. /**
  57971. * Gets the engine which this post process belongs to.
  57972. * @returns The engine the post process was enabled with.
  57973. */
  57974. PostProcess.prototype.getEngine = function () {
  57975. return this._engine;
  57976. };
  57977. /**
  57978. * The effect that is created when initializing the post process.
  57979. * @returns The created effect corrisponding the the postprocess.
  57980. */
  57981. PostProcess.prototype.getEffect = function () {
  57982. return this._effect;
  57983. };
  57984. /**
  57985. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57986. * @param postProcess The post process to share the output with.
  57987. * @returns This post process.
  57988. */
  57989. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57990. this._disposeTextures();
  57991. this._shareOutputWithPostProcess = postProcess;
  57992. return this;
  57993. };
  57994. /**
  57995. * Updates the effect with the current post process compile time values and recompiles the shader.
  57996. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57997. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57998. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57999. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  58000. * @param onCompiled Called when the shader has been compiled.
  58001. * @param onError Called if there is an error when compiling a shader.
  58002. */
  58003. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58004. if (defines === void 0) { defines = null; }
  58005. if (uniforms === void 0) { uniforms = null; }
  58006. if (samplers === void 0) { samplers = null; }
  58007. 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);
  58008. };
  58009. /**
  58010. * The post process is reusable if it can be used multiple times within one frame.
  58011. * @returns If the post process is reusable
  58012. */
  58013. PostProcess.prototype.isReusable = function () {
  58014. return this._reusable;
  58015. };
  58016. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58017. PostProcess.prototype.markTextureDirty = function () {
  58018. this.width = -1;
  58019. };
  58020. /**
  58021. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58022. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  58023. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58024. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58025. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58026. */
  58027. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58028. var _this = this;
  58029. if (sourceTexture === void 0) { sourceTexture = null; }
  58030. camera = camera || this._camera;
  58031. var scene = camera.getScene();
  58032. var engine = scene.getEngine();
  58033. var maxSize = engine.getCaps().maxTextureSize;
  58034. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58035. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58036. var desiredWidth = (this._options.width || requiredWidth);
  58037. var desiredHeight = this._options.height || requiredHeight;
  58038. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58039. if (this.adaptScaleToCurrentViewport) {
  58040. var currentViewport = engine.currentViewport;
  58041. if (currentViewport) {
  58042. desiredWidth *= currentViewport.width;
  58043. desiredHeight *= currentViewport.height;
  58044. }
  58045. }
  58046. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58047. if (!this._options.width) {
  58048. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58049. }
  58050. if (!this._options.height) {
  58051. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58052. }
  58053. }
  58054. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58055. if (this._textures.length > 0) {
  58056. for (var i = 0; i < this._textures.length; i++) {
  58057. this._engine._releaseTexture(this._textures.data[i]);
  58058. }
  58059. this._textures.reset();
  58060. }
  58061. this.width = desiredWidth;
  58062. this.height = desiredHeight;
  58063. var textureSize = { width: this.width, height: this.height };
  58064. var textureOptions = {
  58065. generateMipMaps: false,
  58066. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58067. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58068. samplingMode: this.renderTargetSamplingMode,
  58069. type: this._textureType
  58070. };
  58071. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58072. if (this._reusable) {
  58073. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58074. }
  58075. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58076. this.onSizeChangedObservable.notifyObservers(this);
  58077. }
  58078. this._textures.forEach(function (texture) {
  58079. if (texture.samples !== _this.samples) {
  58080. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58081. }
  58082. });
  58083. }
  58084. var target;
  58085. if (this._shareOutputWithPostProcess) {
  58086. target = this._shareOutputWithPostProcess.inputTexture;
  58087. }
  58088. else if (this._forcedOutputTexture) {
  58089. target = this._forcedOutputTexture;
  58090. this.width = this._forcedOutputTexture.width;
  58091. this.height = this._forcedOutputTexture.height;
  58092. }
  58093. else {
  58094. target = this.inputTexture;
  58095. }
  58096. // Bind the input of this post process to be used as the output of the previous post process.
  58097. if (this.enablePixelPerfectMode) {
  58098. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58099. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58100. }
  58101. else {
  58102. this._scaleRatio.copyFromFloats(1, 1);
  58103. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58104. }
  58105. this.onActivateObservable.notifyObservers(camera);
  58106. // Clear
  58107. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58108. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58109. }
  58110. if (this._reusable) {
  58111. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58112. }
  58113. };
  58114. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58115. /**
  58116. * If the post process is supported.
  58117. */
  58118. get: function () {
  58119. return this._effect.isSupported;
  58120. },
  58121. enumerable: true,
  58122. configurable: true
  58123. });
  58124. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58125. /**
  58126. * The aspect ratio of the output texture.
  58127. */
  58128. get: function () {
  58129. if (this._shareOutputWithPostProcess) {
  58130. return this._shareOutputWithPostProcess.aspectRatio;
  58131. }
  58132. if (this._forcedOutputTexture) {
  58133. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58134. }
  58135. return this.width / this.height;
  58136. },
  58137. enumerable: true,
  58138. configurable: true
  58139. });
  58140. /**
  58141. * Get a value indicating if the post-process is ready to be used
  58142. * @returns true if the post-process is ready (shader is compiled)
  58143. */
  58144. PostProcess.prototype.isReady = function () {
  58145. return this._effect && this._effect.isReady();
  58146. };
  58147. /**
  58148. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58149. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58150. */
  58151. PostProcess.prototype.apply = function () {
  58152. // Check
  58153. if (!this._effect || !this._effect.isReady())
  58154. return null;
  58155. // States
  58156. this._engine.enableEffect(this._effect);
  58157. this._engine.setState(false);
  58158. this._engine.setDepthBuffer(false);
  58159. this._engine.setDepthWrite(false);
  58160. // Alpha
  58161. this._engine.setAlphaMode(this.alphaMode);
  58162. if (this.alphaConstants) {
  58163. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58164. }
  58165. // Bind the output texture of the preivous post process as the input to this post process.
  58166. var source;
  58167. if (this._shareOutputWithPostProcess) {
  58168. source = this._shareOutputWithPostProcess.inputTexture;
  58169. }
  58170. else if (this._forcedOutputTexture) {
  58171. source = this._forcedOutputTexture;
  58172. }
  58173. else {
  58174. source = this.inputTexture;
  58175. }
  58176. this._effect._bindTexture("textureSampler", source);
  58177. // Parameters
  58178. this._effect.setVector2("scale", this._scaleRatio);
  58179. this.onApplyObservable.notifyObservers(this._effect);
  58180. return this._effect;
  58181. };
  58182. PostProcess.prototype._disposeTextures = function () {
  58183. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58184. return;
  58185. }
  58186. if (this._textures.length > 0) {
  58187. for (var i = 0; i < this._textures.length; i++) {
  58188. this._engine._releaseTexture(this._textures.data[i]);
  58189. }
  58190. }
  58191. this._textures.dispose();
  58192. };
  58193. /**
  58194. * Disposes the post process.
  58195. * @param camera The camera to dispose the post process on.
  58196. */
  58197. PostProcess.prototype.dispose = function (camera) {
  58198. camera = camera || this._camera;
  58199. this._disposeTextures();
  58200. if (this._scene) {
  58201. var index_1 = this._scene.postProcesses.indexOf(this);
  58202. if (index_1 !== -1) {
  58203. this._scene.postProcesses.splice(index_1, 1);
  58204. }
  58205. }
  58206. else {
  58207. var index_2 = this._engine.postProcesses.indexOf(this);
  58208. if (index_2 !== -1) {
  58209. this._engine.postProcesses.splice(index_2, 1);
  58210. }
  58211. }
  58212. if (!camera) {
  58213. return;
  58214. }
  58215. camera.detachPostProcess(this);
  58216. var index = camera._postProcesses.indexOf(this);
  58217. if (index === 0 && camera._postProcesses.length > 0) {
  58218. this._camera._postProcesses[0].markTextureDirty();
  58219. }
  58220. this.onActivateObservable.clear();
  58221. this.onAfterRenderObservable.clear();
  58222. this.onApplyObservable.clear();
  58223. this.onBeforeRenderObservable.clear();
  58224. this.onSizeChangedObservable.clear();
  58225. };
  58226. return PostProcess;
  58227. }());
  58228. BABYLON.PostProcess = PostProcess;
  58229. })(BABYLON || (BABYLON = {}));
  58230. //# sourceMappingURL=babylon.postProcess.js.map
  58231. var BABYLON;
  58232. (function (BABYLON) {
  58233. var PassPostProcess = /** @class */ (function (_super) {
  58234. __extends(PassPostProcess, _super);
  58235. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58236. if (camera === void 0) { camera = null; }
  58237. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58238. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58239. }
  58240. return PassPostProcess;
  58241. }(BABYLON.PostProcess));
  58242. BABYLON.PassPostProcess = PassPostProcess;
  58243. })(BABYLON || (BABYLON = {}));
  58244. //# sourceMappingURL=babylon.passPostProcess.js.map
  58245. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58246. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58247. s = arguments[i];
  58248. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58249. t[p] = s[p];
  58250. }
  58251. return t;
  58252. };
  58253. var BABYLON;
  58254. (function (BABYLON) {
  58255. /**
  58256. * Default implementation of @see IShadowGenerator.
  58257. * This is the main object responsible of generating shadows in the framework.
  58258. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58259. */
  58260. var ShadowGenerator = /** @class */ (function () {
  58261. /**
  58262. * Creates a ShadowGenerator object.
  58263. * A ShadowGenerator is the required tool to use the shadows.
  58264. * Each light casting shadows needs to use its own ShadowGenerator.
  58265. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58266. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58267. * @param light The light object generating the shadows.
  58268. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  58269. */
  58270. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58271. this._bias = 0.00005;
  58272. this._blurBoxOffset = 1;
  58273. this._blurScale = 2;
  58274. this._blurKernel = 1;
  58275. this._useKernelBlur = false;
  58276. this._filter = ShadowGenerator.FILTER_NONE;
  58277. this._darkness = 0;
  58278. this._transparencyShadow = false;
  58279. /**
  58280. * Controls the extent to which the shadows fade out at the edge of the frustum
  58281. * Used only by directionals and spots
  58282. */
  58283. this.frustumEdgeFalloff = 0;
  58284. /**
  58285. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58286. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58287. * It might on the other hand introduce peter panning.
  58288. */
  58289. this.forceBackFacesOnly = false;
  58290. this._lightDirection = BABYLON.Vector3.Zero();
  58291. this._viewMatrix = BABYLON.Matrix.Zero();
  58292. this._projectionMatrix = BABYLON.Matrix.Zero();
  58293. this._transformMatrix = BABYLON.Matrix.Zero();
  58294. this._currentFaceIndex = 0;
  58295. this._currentFaceIndexCache = 0;
  58296. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58297. this._mapSize = mapSize;
  58298. this._light = light;
  58299. this._scene = light.getScene();
  58300. light._shadowGenerator = this;
  58301. // Texture type fallback from float to int if not supported.
  58302. var caps = this._scene.getEngine().getCaps();
  58303. if (!useFullFloatFirst) {
  58304. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58305. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58306. }
  58307. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58308. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58309. }
  58310. else {
  58311. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58312. }
  58313. }
  58314. else {
  58315. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58316. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58317. }
  58318. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58319. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58320. }
  58321. else {
  58322. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58323. }
  58324. }
  58325. this._initializeGenerator();
  58326. }
  58327. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58328. /**
  58329. * Shadow generator mode None: no filtering applied.
  58330. */
  58331. get: function () {
  58332. return ShadowGenerator._FILTER_NONE;
  58333. },
  58334. enumerable: true,
  58335. configurable: true
  58336. });
  58337. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58338. /**
  58339. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58340. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58341. */
  58342. get: function () {
  58343. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58344. },
  58345. enumerable: true,
  58346. configurable: true
  58347. });
  58348. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58349. /**
  58350. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58351. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58352. */
  58353. get: function () {
  58354. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58355. },
  58356. enumerable: true,
  58357. configurable: true
  58358. });
  58359. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58360. /**
  58361. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58362. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58363. */
  58364. get: function () {
  58365. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58366. },
  58367. enumerable: true,
  58368. configurable: true
  58369. });
  58370. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58371. /**
  58372. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58373. * edge artifacts on steep falloff.
  58374. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58375. */
  58376. get: function () {
  58377. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58378. },
  58379. enumerable: true,
  58380. configurable: true
  58381. });
  58382. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58383. /**
  58384. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58385. * edge artifacts on steep falloff.
  58386. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58387. */
  58388. get: function () {
  58389. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58390. },
  58391. enumerable: true,
  58392. configurable: true
  58393. });
  58394. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58395. /**
  58396. * Gets the bias: offset applied on the depth preventing acnea.
  58397. */
  58398. get: function () {
  58399. return this._bias;
  58400. },
  58401. /**
  58402. * Sets the bias: offset applied on the depth preventing acnea.
  58403. */
  58404. set: function (bias) {
  58405. this._bias = bias;
  58406. },
  58407. enumerable: true,
  58408. configurable: true
  58409. });
  58410. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58411. /**
  58412. * Gets the blur box offset: offset applied during the blur pass.
  58413. * Only usefull if useKernelBlur = false
  58414. */
  58415. get: function () {
  58416. return this._blurBoxOffset;
  58417. },
  58418. /**
  58419. * Sets the blur box offset: offset applied during the blur pass.
  58420. * Only usefull if useKernelBlur = false
  58421. */
  58422. set: function (value) {
  58423. if (this._blurBoxOffset === value) {
  58424. return;
  58425. }
  58426. this._blurBoxOffset = value;
  58427. this._disposeBlurPostProcesses();
  58428. },
  58429. enumerable: true,
  58430. configurable: true
  58431. });
  58432. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58433. /**
  58434. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58435. * 2 means half of the size.
  58436. */
  58437. get: function () {
  58438. return this._blurScale;
  58439. },
  58440. /**
  58441. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58442. * 2 means half of the size.
  58443. */
  58444. set: function (value) {
  58445. if (this._blurScale === value) {
  58446. return;
  58447. }
  58448. this._blurScale = value;
  58449. this._disposeBlurPostProcesses();
  58450. },
  58451. enumerable: true,
  58452. configurable: true
  58453. });
  58454. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58455. /**
  58456. * Gets the blur kernel: kernel size of the blur pass.
  58457. * Only usefull if useKernelBlur = true
  58458. */
  58459. get: function () {
  58460. return this._blurKernel;
  58461. },
  58462. /**
  58463. * Sets the blur kernel: kernel size of the blur pass.
  58464. * Only usefull if useKernelBlur = true
  58465. */
  58466. set: function (value) {
  58467. if (this._blurKernel === value) {
  58468. return;
  58469. }
  58470. this._blurKernel = value;
  58471. this._disposeBlurPostProcesses();
  58472. },
  58473. enumerable: true,
  58474. configurable: true
  58475. });
  58476. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58477. /**
  58478. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58479. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58480. */
  58481. get: function () {
  58482. return this._useKernelBlur;
  58483. },
  58484. /**
  58485. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58486. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58487. */
  58488. set: function (value) {
  58489. if (this._useKernelBlur === value) {
  58490. return;
  58491. }
  58492. this._useKernelBlur = value;
  58493. this._disposeBlurPostProcesses();
  58494. },
  58495. enumerable: true,
  58496. configurable: true
  58497. });
  58498. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58499. /**
  58500. * Gets the depth scale used in ESM mode.
  58501. */
  58502. get: function () {
  58503. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58504. },
  58505. /**
  58506. * Sets the depth scale used in ESM mode.
  58507. * This can override the scale stored on the light.
  58508. */
  58509. set: function (value) {
  58510. this._depthScale = value;
  58511. },
  58512. enumerable: true,
  58513. configurable: true
  58514. });
  58515. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58516. /**
  58517. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58518. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58519. */
  58520. get: function () {
  58521. return this._filter;
  58522. },
  58523. /**
  58524. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58525. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58526. */
  58527. set: function (value) {
  58528. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58529. if (this._light.needCube()) {
  58530. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58531. this.useExponentialShadowMap = true;
  58532. return;
  58533. }
  58534. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58535. this.useCloseExponentialShadowMap = true;
  58536. return;
  58537. }
  58538. }
  58539. if (this._filter === value) {
  58540. return;
  58541. }
  58542. this._filter = value;
  58543. this._disposeBlurPostProcesses();
  58544. this._applyFilterValues();
  58545. this._light._markMeshesAsLightDirty();
  58546. },
  58547. enumerable: true,
  58548. configurable: true
  58549. });
  58550. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58551. /**
  58552. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58553. */
  58554. get: function () {
  58555. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58556. },
  58557. /**
  58558. * Sets the current filter to Poisson Sampling aka PCF.
  58559. */
  58560. set: function (value) {
  58561. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58562. return;
  58563. }
  58564. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58565. },
  58566. enumerable: true,
  58567. configurable: true
  58568. });
  58569. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58570. /**
  58571. * Gets if the current filter is set to VSM.
  58572. * DEPRECATED. Should use useExponentialShadowMap instead.
  58573. */
  58574. get: function () {
  58575. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58576. return this.useExponentialShadowMap;
  58577. },
  58578. /**
  58579. * Sets the current filter is to VSM.
  58580. * DEPRECATED. Should use useExponentialShadowMap instead.
  58581. */
  58582. set: function (value) {
  58583. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58584. this.useExponentialShadowMap = value;
  58585. },
  58586. enumerable: true,
  58587. configurable: true
  58588. });
  58589. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58590. /**
  58591. * Gets if the current filter is set to blurred VSM.
  58592. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58593. */
  58594. get: function () {
  58595. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58596. return this.useBlurExponentialShadowMap;
  58597. },
  58598. /**
  58599. * Sets the current filter is to blurred VSM.
  58600. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58601. */
  58602. set: function (value) {
  58603. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58604. this.useBlurExponentialShadowMap = value;
  58605. },
  58606. enumerable: true,
  58607. configurable: true
  58608. });
  58609. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58610. /**
  58611. * Gets if the current filter is set to ESM.
  58612. */
  58613. get: function () {
  58614. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58615. },
  58616. /**
  58617. * Sets the current filter is to ESM.
  58618. */
  58619. set: function (value) {
  58620. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58621. return;
  58622. }
  58623. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58624. },
  58625. enumerable: true,
  58626. configurable: true
  58627. });
  58628. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58629. /**
  58630. * Gets if the current filter is set to filtered ESM.
  58631. */
  58632. get: function () {
  58633. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58634. },
  58635. /**
  58636. * Gets if the current filter is set to filtered ESM.
  58637. */
  58638. set: function (value) {
  58639. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58640. return;
  58641. }
  58642. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58643. },
  58644. enumerable: true,
  58645. configurable: true
  58646. });
  58647. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58648. /**
  58649. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58650. * exponential to prevent steep falloff artifacts).
  58651. */
  58652. get: function () {
  58653. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58654. },
  58655. /**
  58656. * Sets the current filter to "close ESM" (using the inverse of the
  58657. * exponential to prevent steep falloff artifacts).
  58658. */
  58659. set: function (value) {
  58660. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58661. return;
  58662. }
  58663. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58664. },
  58665. enumerable: true,
  58666. configurable: true
  58667. });
  58668. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58669. /**
  58670. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58671. * exponential to prevent steep falloff artifacts).
  58672. */
  58673. get: function () {
  58674. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58675. },
  58676. /**
  58677. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58678. * exponential to prevent steep falloff artifacts).
  58679. */
  58680. set: function (value) {
  58681. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58682. return;
  58683. }
  58684. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58685. },
  58686. enumerable: true,
  58687. configurable: true
  58688. });
  58689. /**
  58690. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58691. * 0 means strongest and 1 would means no shadow.
  58692. * @returns the darkness.
  58693. */
  58694. ShadowGenerator.prototype.getDarkness = function () {
  58695. return this._darkness;
  58696. };
  58697. /**
  58698. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58699. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58700. * @returns the shadow generator allowing fluent coding.
  58701. */
  58702. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58703. if (darkness >= 1.0)
  58704. this._darkness = 1.0;
  58705. else if (darkness <= 0.0)
  58706. this._darkness = 0.0;
  58707. else
  58708. this._darkness = darkness;
  58709. return this;
  58710. };
  58711. /**
  58712. * Sets the ability to have transparent shadow (boolean).
  58713. * @param transparent True if transparent else False
  58714. * @returns the shadow generator allowing fluent coding
  58715. */
  58716. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58717. this._transparencyShadow = transparent;
  58718. return this;
  58719. };
  58720. /**
  58721. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58722. * @returns The render target texture if present otherwise, null
  58723. */
  58724. ShadowGenerator.prototype.getShadowMap = function () {
  58725. return this._shadowMap;
  58726. };
  58727. /**
  58728. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58729. * @returns The render target texture if the shadow map is present otherwise, null
  58730. */
  58731. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58732. if (this._shadowMap2) {
  58733. return this._shadowMap2;
  58734. }
  58735. return this._shadowMap;
  58736. };
  58737. /**
  58738. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58739. * @param mesh Mesh to add
  58740. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58741. * @returns the Shadow Generator itself
  58742. */
  58743. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58744. if (includeDescendants === void 0) { includeDescendants = true; }
  58745. if (!this._shadowMap) {
  58746. return this;
  58747. }
  58748. if (!this._shadowMap.renderList) {
  58749. this._shadowMap.renderList = [];
  58750. }
  58751. this._shadowMap.renderList.push(mesh);
  58752. if (includeDescendants) {
  58753. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58754. }
  58755. return this;
  58756. var _a;
  58757. };
  58758. /**
  58759. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58760. * @param mesh Mesh to remove
  58761. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58762. * @returns the Shadow Generator itself
  58763. */
  58764. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58765. if (includeDescendants === void 0) { includeDescendants = true; }
  58766. if (!this._shadowMap || !this._shadowMap.renderList) {
  58767. return this;
  58768. }
  58769. var index = this._shadowMap.renderList.indexOf(mesh);
  58770. if (index !== -1) {
  58771. this._shadowMap.renderList.splice(index, 1);
  58772. }
  58773. if (includeDescendants) {
  58774. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58775. var child = _a[_i];
  58776. this.removeShadowCaster(child);
  58777. }
  58778. }
  58779. return this;
  58780. };
  58781. /**
  58782. * Returns the associated light object.
  58783. * @returns the light generating the shadow
  58784. */
  58785. ShadowGenerator.prototype.getLight = function () {
  58786. return this._light;
  58787. };
  58788. ShadowGenerator.prototype._initializeGenerator = function () {
  58789. this._light._markMeshesAsLightDirty();
  58790. this._initializeShadowMap();
  58791. };
  58792. ShadowGenerator.prototype._initializeShadowMap = function () {
  58793. var _this = this;
  58794. // Render target
  58795. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58796. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58797. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58798. this._shadowMap.anisotropicFilteringLevel = 1;
  58799. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58800. this._shadowMap.renderParticles = false;
  58801. this._shadowMap.ignoreCameraViewport = true;
  58802. // Record Face Index before render.
  58803. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58804. _this._currentFaceIndex = faceIndex;
  58805. });
  58806. // Custom render function.
  58807. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58808. // Blur if required afer render.
  58809. this._shadowMap.onAfterUnbindObservable.add(function () {
  58810. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58811. return;
  58812. }
  58813. var shadowMap = _this.getShadowMapForRendering();
  58814. if (shadowMap) {
  58815. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58816. }
  58817. });
  58818. // Clear according to the chosen filter.
  58819. this._shadowMap.onClearObservable.add(function (engine) {
  58820. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58821. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58822. }
  58823. else {
  58824. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58825. }
  58826. });
  58827. };
  58828. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58829. var _this = this;
  58830. var engine = this._scene.getEngine();
  58831. var targetSize = this._mapSize / this.blurScale;
  58832. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58833. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58834. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58835. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58836. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58837. }
  58838. if (this.useKernelBlur) {
  58839. 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);
  58840. this._kernelBlurXPostprocess.width = targetSize;
  58841. this._kernelBlurXPostprocess.height = targetSize;
  58842. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58843. effect.setTexture("textureSampler", _this._shadowMap);
  58844. });
  58845. 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);
  58846. this._kernelBlurXPostprocess.autoClear = false;
  58847. this._kernelBlurYPostprocess.autoClear = false;
  58848. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58849. this._kernelBlurXPostprocess.packedFloat = true;
  58850. this._kernelBlurYPostprocess.packedFloat = true;
  58851. }
  58852. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58853. }
  58854. else {
  58855. 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);
  58856. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58857. effect.setFloat2("screenSize", targetSize, targetSize);
  58858. effect.setTexture("textureSampler", _this._shadowMap);
  58859. });
  58860. this._boxBlurPostprocess.autoClear = false;
  58861. this._blurPostProcesses = [this._boxBlurPostprocess];
  58862. }
  58863. };
  58864. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58865. var index;
  58866. var engine = this._scene.getEngine();
  58867. if (depthOnlySubMeshes.length) {
  58868. engine.setColorWrite(false);
  58869. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58870. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58871. }
  58872. engine.setColorWrite(true);
  58873. }
  58874. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58875. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58876. }
  58877. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58878. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58879. }
  58880. if (this._transparencyShadow) {
  58881. for (index = 0; index < transparentSubMeshes.length; index++) {
  58882. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58883. }
  58884. }
  58885. };
  58886. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58887. var _this = this;
  58888. var mesh = subMesh.getRenderingMesh();
  58889. var scene = this._scene;
  58890. var engine = scene.getEngine();
  58891. var material = subMesh.getMaterial();
  58892. if (!material) {
  58893. return;
  58894. }
  58895. // Culling
  58896. engine.setState(material.backFaceCulling);
  58897. // Managing instances
  58898. var batch = mesh._getInstancesRenderList(subMesh._id);
  58899. if (batch.mustReturn) {
  58900. return;
  58901. }
  58902. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58903. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58904. engine.enableEffect(this._effect);
  58905. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58906. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58907. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58908. this._effect.setVector3("lightPosition", this.getLight().position);
  58909. if (scene.activeCamera) {
  58910. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58911. }
  58912. // Alpha test
  58913. if (material && material.needAlphaTesting()) {
  58914. var alphaTexture = material.getAlphaTestTexture();
  58915. if (alphaTexture) {
  58916. this._effect.setTexture("diffuseSampler", alphaTexture);
  58917. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58918. }
  58919. }
  58920. // Bones
  58921. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58922. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58923. }
  58924. if (this.forceBackFacesOnly) {
  58925. engine.setState(true, 0, false, true);
  58926. }
  58927. // Draw
  58928. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58929. if (this.forceBackFacesOnly) {
  58930. engine.setState(true, 0, false, false);
  58931. }
  58932. }
  58933. else {
  58934. // Need to reset refresh rate of the shadowMap
  58935. if (this._shadowMap) {
  58936. this._shadowMap.resetRefreshCounter();
  58937. }
  58938. }
  58939. };
  58940. ShadowGenerator.prototype._applyFilterValues = function () {
  58941. if (!this._shadowMap) {
  58942. return;
  58943. }
  58944. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58945. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58946. }
  58947. else {
  58948. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58949. }
  58950. };
  58951. /**
  58952. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58953. * @param onCompiled Callback triggered at the and of the effects compilation
  58954. * @param options Sets of optional options forcing the compilation with different modes
  58955. */
  58956. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58957. var _this = this;
  58958. var localOptions = __assign({ useInstances: false }, options);
  58959. var shadowMap = this.getShadowMap();
  58960. if (!shadowMap) {
  58961. if (onCompiled) {
  58962. onCompiled(this);
  58963. }
  58964. return;
  58965. }
  58966. var renderList = shadowMap.renderList;
  58967. if (!renderList) {
  58968. if (onCompiled) {
  58969. onCompiled(this);
  58970. }
  58971. return;
  58972. }
  58973. var subMeshes = new Array();
  58974. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58975. var mesh = renderList_1[_i];
  58976. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58977. }
  58978. if (subMeshes.length === 0) {
  58979. if (onCompiled) {
  58980. onCompiled(this);
  58981. }
  58982. return;
  58983. }
  58984. var currentIndex = 0;
  58985. var checkReady = function () {
  58986. if (!_this._scene || !_this._scene.getEngine()) {
  58987. return;
  58988. }
  58989. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58990. currentIndex++;
  58991. if (currentIndex >= subMeshes.length) {
  58992. if (onCompiled) {
  58993. onCompiled(_this);
  58994. }
  58995. return;
  58996. }
  58997. }
  58998. setTimeout(checkReady, 16);
  58999. };
  59000. checkReady();
  59001. };
  59002. /**
  59003. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59004. * @param options Sets of optional options forcing the compilation with different modes
  59005. * @returns A promise that resolves when the compilation completes
  59006. */
  59007. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59008. var _this = this;
  59009. return new Promise(function (resolve) {
  59010. _this.forceCompilation(function () {
  59011. resolve();
  59012. }, options);
  59013. });
  59014. };
  59015. /**
  59016. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59017. * @param subMesh The submesh we want to render in the shadow map
  59018. * @param useInstances Defines wether will draw in the map using instances
  59019. * @returns true if ready otherwise, false
  59020. */
  59021. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59022. var defines = [];
  59023. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59024. defines.push("#define FLOAT");
  59025. }
  59026. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59027. defines.push("#define ESM");
  59028. }
  59029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59030. var mesh = subMesh.getMesh();
  59031. var material = subMesh.getMaterial();
  59032. // Alpha test
  59033. if (material && material.needAlphaTesting()) {
  59034. var alphaTexture = material.getAlphaTestTexture();
  59035. if (alphaTexture) {
  59036. defines.push("#define ALPHATEST");
  59037. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59038. attribs.push(BABYLON.VertexBuffer.UVKind);
  59039. defines.push("#define UV1");
  59040. }
  59041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59042. if (alphaTexture.coordinatesIndex === 1) {
  59043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59044. defines.push("#define UV2");
  59045. }
  59046. }
  59047. }
  59048. }
  59049. // Bones
  59050. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59051. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59052. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59053. if (mesh.numBoneInfluencers > 4) {
  59054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59056. }
  59057. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59058. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59059. }
  59060. else {
  59061. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59062. }
  59063. // Instances
  59064. if (useInstances) {
  59065. defines.push("#define INSTANCES");
  59066. attribs.push("world0");
  59067. attribs.push("world1");
  59068. attribs.push("world2");
  59069. attribs.push("world3");
  59070. }
  59071. // Get correct effect
  59072. var join = defines.join("\n");
  59073. if (this._cachedDefines !== join) {
  59074. this._cachedDefines = join;
  59075. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59076. }
  59077. if (!this._effect.isReady()) {
  59078. return false;
  59079. }
  59080. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59081. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59082. this._initializeBlurRTTAndPostProcesses();
  59083. }
  59084. }
  59085. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59086. return false;
  59087. }
  59088. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59089. return false;
  59090. }
  59091. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59092. return false;
  59093. }
  59094. return true;
  59095. };
  59096. /**
  59097. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59098. * @param defines Defines of the material we want to update
  59099. * @param lightIndex Index of the light in the enabled light list of the material
  59100. */
  59101. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59102. var scene = this._scene;
  59103. var light = this._light;
  59104. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59105. return;
  59106. }
  59107. defines["SHADOW" + lightIndex] = true;
  59108. if (this.usePoissonSampling) {
  59109. defines["SHADOWPCF" + lightIndex] = true;
  59110. }
  59111. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59112. defines["SHADOWESM" + lightIndex] = true;
  59113. }
  59114. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59115. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59116. }
  59117. if (light.needCube()) {
  59118. defines["SHADOWCUBE" + lightIndex] = true;
  59119. }
  59120. };
  59121. /**
  59122. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59123. * defined in the generator but impacting the effect).
  59124. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59125. * @param effect The effect we are binfing the information for
  59126. */
  59127. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59128. var light = this._light;
  59129. var scene = this._scene;
  59130. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59131. return;
  59132. }
  59133. var camera = scene.activeCamera;
  59134. if (!camera) {
  59135. return;
  59136. }
  59137. var shadowMap = this.getShadowMap();
  59138. if (!shadowMap) {
  59139. return;
  59140. }
  59141. if (!light.needCube()) {
  59142. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59143. }
  59144. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59145. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59146. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59147. };
  59148. /**
  59149. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59150. * (eq to shadow prjection matrix * light transform matrix)
  59151. * @returns The transform matrix used to create the shadow map
  59152. */
  59153. ShadowGenerator.prototype.getTransformMatrix = function () {
  59154. var scene = this._scene;
  59155. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59156. return this._transformMatrix;
  59157. }
  59158. this._currentRenderID = scene.getRenderId();
  59159. this._currentFaceIndexCache = this._currentFaceIndex;
  59160. var lightPosition = this._light.position;
  59161. if (this._light.computeTransformedInformation()) {
  59162. lightPosition = this._light.transformedPosition;
  59163. }
  59164. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59165. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59166. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59167. }
  59168. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59169. this._cachedPosition = lightPosition.clone();
  59170. this._cachedDirection = this._lightDirection.clone();
  59171. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59172. var shadowMap = this.getShadowMap();
  59173. if (shadowMap) {
  59174. var renderList = shadowMap.renderList;
  59175. if (renderList) {
  59176. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59177. }
  59178. }
  59179. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59180. }
  59181. return this._transformMatrix;
  59182. };
  59183. /**
  59184. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59185. * Cube and 2D textures for instance.
  59186. */
  59187. ShadowGenerator.prototype.recreateShadowMap = function () {
  59188. var shadowMap = this._shadowMap;
  59189. if (!shadowMap) {
  59190. return;
  59191. }
  59192. // Track render list.
  59193. var renderList = shadowMap.renderList;
  59194. // Clean up existing data.
  59195. this._disposeRTTandPostProcesses();
  59196. // Reinitializes.
  59197. this._initializeGenerator();
  59198. // Reaffect the filter to ensure a correct fallback if necessary.
  59199. this.filter = this.filter;
  59200. // Reaffect the filter.
  59201. this._applyFilterValues();
  59202. // Reaffect Render List.
  59203. this._shadowMap.renderList = renderList;
  59204. };
  59205. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59206. if (this._shadowMap2) {
  59207. this._shadowMap2.dispose();
  59208. this._shadowMap2 = null;
  59209. }
  59210. if (this._boxBlurPostprocess) {
  59211. this._boxBlurPostprocess.dispose();
  59212. this._boxBlurPostprocess = null;
  59213. }
  59214. if (this._kernelBlurXPostprocess) {
  59215. this._kernelBlurXPostprocess.dispose();
  59216. this._kernelBlurXPostprocess = null;
  59217. }
  59218. if (this._kernelBlurYPostprocess) {
  59219. this._kernelBlurYPostprocess.dispose();
  59220. this._kernelBlurYPostprocess = null;
  59221. }
  59222. this._blurPostProcesses = [];
  59223. };
  59224. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59225. if (this._shadowMap) {
  59226. this._shadowMap.dispose();
  59227. this._shadowMap = null;
  59228. }
  59229. this._disposeBlurPostProcesses();
  59230. };
  59231. /**
  59232. * Disposes the ShadowGenerator.
  59233. * Returns nothing.
  59234. */
  59235. ShadowGenerator.prototype.dispose = function () {
  59236. this._disposeRTTandPostProcesses();
  59237. if (this._light) {
  59238. this._light._shadowGenerator = null;
  59239. this._light._markMeshesAsLightDirty();
  59240. }
  59241. };
  59242. /**
  59243. * Serializes the shadow generator setup to a json object.
  59244. * @returns The serialized JSON object
  59245. */
  59246. ShadowGenerator.prototype.serialize = function () {
  59247. var serializationObject = {};
  59248. var shadowMap = this.getShadowMap();
  59249. if (!shadowMap) {
  59250. return serializationObject;
  59251. }
  59252. serializationObject.lightId = this._light.id;
  59253. serializationObject.mapSize = shadowMap.getRenderSize();
  59254. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59255. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59256. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59257. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59258. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59259. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59260. serializationObject.depthScale = this.depthScale;
  59261. serializationObject.darkness = this.getDarkness();
  59262. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59263. serializationObject.blurKernel = this.blurKernel;
  59264. serializationObject.blurScale = this.blurScale;
  59265. serializationObject.useKernelBlur = this.useKernelBlur;
  59266. serializationObject.transparencyShadow = this._transparencyShadow;
  59267. serializationObject.renderList = [];
  59268. if (shadowMap.renderList) {
  59269. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59270. var mesh = shadowMap.renderList[meshIndex];
  59271. serializationObject.renderList.push(mesh.id);
  59272. }
  59273. }
  59274. return serializationObject;
  59275. };
  59276. /**
  59277. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59278. * @param parsedShadowGenerator The JSON object to parse
  59279. * @param scene The scene to create the shadow map for
  59280. * @returns The parsed shadow generator
  59281. */
  59282. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59283. //casting to point light, as light is missing the position attr and typescript complains.
  59284. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59285. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59286. var shadowMap = shadowGenerator.getShadowMap();
  59287. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59288. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59289. meshes.forEach(function (mesh) {
  59290. if (!shadowMap) {
  59291. return;
  59292. }
  59293. if (!shadowMap.renderList) {
  59294. shadowMap.renderList = [];
  59295. }
  59296. shadowMap.renderList.push(mesh);
  59297. });
  59298. }
  59299. if (parsedShadowGenerator.usePoissonSampling) {
  59300. shadowGenerator.usePoissonSampling = true;
  59301. }
  59302. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59303. shadowGenerator.useExponentialShadowMap = true;
  59304. }
  59305. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59306. shadowGenerator.useBlurExponentialShadowMap = true;
  59307. }
  59308. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59309. shadowGenerator.useCloseExponentialShadowMap = true;
  59310. }
  59311. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59312. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59313. }
  59314. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59315. shadowGenerator.useExponentialShadowMap = true;
  59316. }
  59317. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59318. shadowGenerator.useBlurExponentialShadowMap = true;
  59319. }
  59320. if (parsedShadowGenerator.depthScale) {
  59321. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59322. }
  59323. if (parsedShadowGenerator.blurScale) {
  59324. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59325. }
  59326. if (parsedShadowGenerator.blurBoxOffset) {
  59327. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59328. }
  59329. if (parsedShadowGenerator.useKernelBlur) {
  59330. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59331. }
  59332. if (parsedShadowGenerator.blurKernel) {
  59333. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59334. }
  59335. if (parsedShadowGenerator.bias !== undefined) {
  59336. shadowGenerator.bias = parsedShadowGenerator.bias;
  59337. }
  59338. if (parsedShadowGenerator.darkness) {
  59339. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59340. }
  59341. if (parsedShadowGenerator.transparencyShadow) {
  59342. shadowGenerator.setTransparencyShadow(true);
  59343. }
  59344. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59345. return shadowGenerator;
  59346. };
  59347. ShadowGenerator._FILTER_NONE = 0;
  59348. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59349. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59350. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59351. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59352. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59353. return ShadowGenerator;
  59354. }());
  59355. BABYLON.ShadowGenerator = ShadowGenerator;
  59356. })(BABYLON || (BABYLON = {}));
  59357. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59358. var BABYLON;
  59359. (function (BABYLON) {
  59360. var DefaultLoadingScreen = /** @class */ (function () {
  59361. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59362. if (_loadingText === void 0) { _loadingText = ""; }
  59363. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59364. var _this = this;
  59365. this._renderingCanvas = _renderingCanvas;
  59366. this._loadingText = _loadingText;
  59367. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59368. // Resize
  59369. this._resizeLoadingUI = function () {
  59370. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59371. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59372. if (!_this._loadingDiv) {
  59373. return;
  59374. }
  59375. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59376. _this._loadingDiv.style.left = canvasRect.left + "px";
  59377. _this._loadingDiv.style.top = canvasRect.top + "px";
  59378. _this._loadingDiv.style.width = canvasRect.width + "px";
  59379. _this._loadingDiv.style.height = canvasRect.height + "px";
  59380. };
  59381. }
  59382. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59383. if (this._loadingDiv) {
  59384. // Do not add a loading screen if there is already one
  59385. return;
  59386. }
  59387. this._loadingDiv = document.createElement("div");
  59388. this._loadingDiv.id = "babylonjsLoadingDiv";
  59389. this._loadingDiv.style.opacity = "0";
  59390. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59391. this._loadingDiv.style.pointerEvents = "none";
  59392. // Loading text
  59393. this._loadingTextDiv = document.createElement("div");
  59394. this._loadingTextDiv.style.position = "absolute";
  59395. this._loadingTextDiv.style.left = "0";
  59396. this._loadingTextDiv.style.top = "50%";
  59397. this._loadingTextDiv.style.marginTop = "80px";
  59398. this._loadingTextDiv.style.width = "100%";
  59399. this._loadingTextDiv.style.height = "20px";
  59400. this._loadingTextDiv.style.fontFamily = "Arial";
  59401. this._loadingTextDiv.style.fontSize = "14px";
  59402. this._loadingTextDiv.style.color = "white";
  59403. this._loadingTextDiv.style.textAlign = "center";
  59404. this._loadingTextDiv.innerHTML = "Loading";
  59405. this._loadingDiv.appendChild(this._loadingTextDiv);
  59406. //set the predefined text
  59407. this._loadingTextDiv.innerHTML = this._loadingText;
  59408. // Generating keyframes
  59409. var style = document.createElement('style');
  59410. style.type = 'text/css';
  59411. 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 }";
  59412. style.innerHTML = keyFrames;
  59413. document.getElementsByTagName('head')[0].appendChild(style);
  59414. // Loading img
  59415. var imgBack = new Image();
  59416. 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";
  59417. imgBack.style.position = "absolute";
  59418. imgBack.style.left = "50%";
  59419. imgBack.style.top = "50%";
  59420. imgBack.style.marginLeft = "-60px";
  59421. imgBack.style.marginTop = "-60px";
  59422. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59423. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59424. imgBack.style.transformOrigin = "50% 50%";
  59425. imgBack.style.webkitTransformOrigin = "50% 50%";
  59426. this._loadingDiv.appendChild(imgBack);
  59427. this._resizeLoadingUI();
  59428. window.addEventListener("resize", this._resizeLoadingUI);
  59429. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59430. document.body.appendChild(this._loadingDiv);
  59431. this._loadingDiv.style.opacity = "1";
  59432. };
  59433. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59434. var _this = this;
  59435. if (!this._loadingDiv) {
  59436. return;
  59437. }
  59438. var onTransitionEnd = function () {
  59439. if (!_this._loadingDiv) {
  59440. return;
  59441. }
  59442. document.body.removeChild(_this._loadingDiv);
  59443. window.removeEventListener("resize", _this._resizeLoadingUI);
  59444. _this._loadingDiv = null;
  59445. };
  59446. this._loadingDiv.style.opacity = "0";
  59447. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59448. };
  59449. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59450. set: function (text) {
  59451. this._loadingText = text;
  59452. if (this._loadingTextDiv) {
  59453. this._loadingTextDiv.innerHTML = this._loadingText;
  59454. }
  59455. },
  59456. enumerable: true,
  59457. configurable: true
  59458. });
  59459. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59460. get: function () {
  59461. return this._loadingDivBackgroundColor;
  59462. },
  59463. set: function (color) {
  59464. this._loadingDivBackgroundColor = color;
  59465. if (!this._loadingDiv) {
  59466. return;
  59467. }
  59468. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59469. },
  59470. enumerable: true,
  59471. configurable: true
  59472. });
  59473. return DefaultLoadingScreen;
  59474. }());
  59475. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59476. })(BABYLON || (BABYLON = {}));
  59477. //# sourceMappingURL=babylon.loadingScreen.js.map
  59478. var BABYLON;
  59479. (function (BABYLON) {
  59480. var SceneLoaderProgressEvent = /** @class */ (function () {
  59481. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59482. this.lengthComputable = lengthComputable;
  59483. this.loaded = loaded;
  59484. this.total = total;
  59485. }
  59486. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59487. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59488. };
  59489. return SceneLoaderProgressEvent;
  59490. }());
  59491. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59492. var SceneLoader = /** @class */ (function () {
  59493. function SceneLoader() {
  59494. }
  59495. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59496. get: function () {
  59497. return 0;
  59498. },
  59499. enumerable: true,
  59500. configurable: true
  59501. });
  59502. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59503. get: function () {
  59504. return 1;
  59505. },
  59506. enumerable: true,
  59507. configurable: true
  59508. });
  59509. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59510. get: function () {
  59511. return 2;
  59512. },
  59513. enumerable: true,
  59514. configurable: true
  59515. });
  59516. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59517. get: function () {
  59518. return 3;
  59519. },
  59520. enumerable: true,
  59521. configurable: true
  59522. });
  59523. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59524. get: function () {
  59525. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59526. },
  59527. set: function (value) {
  59528. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59529. },
  59530. enumerable: true,
  59531. configurable: true
  59532. });
  59533. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59534. get: function () {
  59535. return SceneLoader._ShowLoadingScreen;
  59536. },
  59537. set: function (value) {
  59538. SceneLoader._ShowLoadingScreen = value;
  59539. },
  59540. enumerable: true,
  59541. configurable: true
  59542. });
  59543. Object.defineProperty(SceneLoader, "loggingLevel", {
  59544. get: function () {
  59545. return SceneLoader._loggingLevel;
  59546. },
  59547. set: function (value) {
  59548. SceneLoader._loggingLevel = value;
  59549. },
  59550. enumerable: true,
  59551. configurable: true
  59552. });
  59553. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59554. get: function () {
  59555. return SceneLoader._CleanBoneMatrixWeights;
  59556. },
  59557. set: function (value) {
  59558. SceneLoader._CleanBoneMatrixWeights = value;
  59559. },
  59560. enumerable: true,
  59561. configurable: true
  59562. });
  59563. SceneLoader._getDefaultPlugin = function () {
  59564. return SceneLoader._registeredPlugins[".babylon"];
  59565. };
  59566. SceneLoader._getPluginForExtension = function (extension) {
  59567. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59568. if (registeredPlugin) {
  59569. return registeredPlugin;
  59570. }
  59571. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59572. return SceneLoader._getDefaultPlugin();
  59573. };
  59574. SceneLoader._getPluginForDirectLoad = function (data) {
  59575. for (var extension in SceneLoader._registeredPlugins) {
  59576. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59577. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59578. return SceneLoader._registeredPlugins[extension];
  59579. }
  59580. }
  59581. return SceneLoader._getDefaultPlugin();
  59582. };
  59583. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59584. if (sceneFilename.name) {
  59585. sceneFilename = sceneFilename.name;
  59586. }
  59587. var queryStringPosition = sceneFilename.indexOf("?");
  59588. if (queryStringPosition !== -1) {
  59589. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59590. }
  59591. var dotPosition = sceneFilename.lastIndexOf(".");
  59592. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59593. return SceneLoader._getPluginForExtension(extension);
  59594. };
  59595. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59596. SceneLoader._getDirectLoad = function (sceneFilename) {
  59597. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59598. return sceneFilename.substr(5);
  59599. }
  59600. return null;
  59601. };
  59602. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59603. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59604. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59605. var plugin;
  59606. if (registeredPlugin.plugin.createPlugin) {
  59607. plugin = registeredPlugin.plugin.createPlugin();
  59608. }
  59609. else {
  59610. plugin = registeredPlugin.plugin;
  59611. }
  59612. var useArrayBuffer = registeredPlugin.isBinary;
  59613. var database;
  59614. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59615. var dataCallback = function (data, responseURL) {
  59616. if (scene.isDisposed) {
  59617. onError("Scene has been disposed");
  59618. return;
  59619. }
  59620. scene.database = database;
  59621. onSuccess(plugin, data, responseURL);
  59622. };
  59623. var request = null;
  59624. var pluginDisposed = false;
  59625. var onDisposeObservable = plugin.onDisposeObservable;
  59626. if (onDisposeObservable) {
  59627. onDisposeObservable.add(function () {
  59628. pluginDisposed = true;
  59629. if (request) {
  59630. request.abort();
  59631. request = null;
  59632. }
  59633. onDispose();
  59634. });
  59635. }
  59636. var manifestChecked = function () {
  59637. if (pluginDisposed) {
  59638. return;
  59639. }
  59640. var url = rootUrl + sceneFilename;
  59641. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59642. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59643. } : undefined, database, useArrayBuffer, function (request, exception) {
  59644. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59645. });
  59646. };
  59647. if (directLoad) {
  59648. dataCallback(directLoad);
  59649. return plugin;
  59650. }
  59651. if (rootUrl.indexOf("file:") === -1) {
  59652. if (scene.getEngine().enableOfflineSupport) {
  59653. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59654. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59655. }
  59656. else {
  59657. manifestChecked();
  59658. }
  59659. }
  59660. else {
  59661. var fileOrString = sceneFilename;
  59662. if (fileOrString.name) {
  59663. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59664. }
  59665. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59666. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59667. }
  59668. else {
  59669. onError("Unable to find file named " + sceneFilename);
  59670. }
  59671. }
  59672. return plugin;
  59673. };
  59674. // Public functions
  59675. SceneLoader.GetPluginForExtension = function (extension) {
  59676. return SceneLoader._getPluginForExtension(extension).plugin;
  59677. };
  59678. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59679. return !!SceneLoader._registeredPlugins[extension];
  59680. };
  59681. SceneLoader.RegisterPlugin = function (plugin) {
  59682. if (typeof plugin.extensions === "string") {
  59683. var extension = plugin.extensions;
  59684. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59685. plugin: plugin,
  59686. isBinary: false
  59687. };
  59688. }
  59689. else {
  59690. var extensions = plugin.extensions;
  59691. Object.keys(extensions).forEach(function (extension) {
  59692. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59693. plugin: plugin,
  59694. isBinary: extensions[extension].isBinary
  59695. };
  59696. });
  59697. }
  59698. };
  59699. /**
  59700. * Import meshes into a scene
  59701. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59702. * @param rootUrl a string that defines the root url for scene and resources
  59703. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59704. * @param scene the instance of BABYLON.Scene to append to
  59705. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59706. * @param onProgress a callback with a progress event for each file being loaded
  59707. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59708. * @param pluginExtension the extension used to determine the plugin
  59709. * @returns The loaded plugin
  59710. */
  59711. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59712. if (onSuccess === void 0) { onSuccess = null; }
  59713. if (onProgress === void 0) { onProgress = null; }
  59714. if (onError === void 0) { onError = null; }
  59715. if (pluginExtension === void 0) { pluginExtension = null; }
  59716. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59717. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59718. return null;
  59719. }
  59720. var loadingToken = {};
  59721. scene._addPendingData(loadingToken);
  59722. var disposeHandler = function () {
  59723. scene._removePendingData(loadingToken);
  59724. };
  59725. var errorHandler = function (message, exception) {
  59726. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59727. if (onError) {
  59728. onError(scene, errorMessage, exception);
  59729. }
  59730. else {
  59731. BABYLON.Tools.Error(errorMessage);
  59732. // should the exception be thrown?
  59733. }
  59734. disposeHandler();
  59735. };
  59736. var progressHandler = onProgress ? function (event) {
  59737. try {
  59738. onProgress(event);
  59739. }
  59740. catch (e) {
  59741. errorHandler("Error in onProgress callback", e);
  59742. }
  59743. } : undefined;
  59744. var successHandler = function (meshes, particleSystems, skeletons) {
  59745. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59746. if (onSuccess) {
  59747. try {
  59748. onSuccess(meshes, particleSystems, skeletons);
  59749. }
  59750. catch (e) {
  59751. errorHandler("Error in onSuccess callback", e);
  59752. }
  59753. }
  59754. scene._removePendingData(loadingToken);
  59755. };
  59756. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59757. if (plugin.rewriteRootURL) {
  59758. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59759. }
  59760. if (sceneFilename === "") {
  59761. if (sceneFilename === "") {
  59762. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59763. }
  59764. }
  59765. if (plugin.importMesh) {
  59766. var syncedPlugin = plugin;
  59767. var meshes = new Array();
  59768. var particleSystems = new Array();
  59769. var skeletons = new Array();
  59770. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59771. return;
  59772. }
  59773. scene.loadingPluginName = plugin.name;
  59774. successHandler(meshes, particleSystems, skeletons);
  59775. }
  59776. else {
  59777. var asyncedPlugin = plugin;
  59778. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59779. scene.loadingPluginName = plugin.name;
  59780. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59781. }).catch(function (error) {
  59782. errorHandler(error.message, error);
  59783. });
  59784. }
  59785. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59786. };
  59787. /**
  59788. * Import meshes into a scene
  59789. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59790. * @param rootUrl a string that defines the root url for scene and resources
  59791. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59792. * @param scene the instance of BABYLON.Scene to append to
  59793. * @param onProgress a callback with a progress event for each file being loaded
  59794. * @param pluginExtension the extension used to determine the plugin
  59795. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59796. */
  59797. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59798. if (onProgress === void 0) { onProgress = null; }
  59799. if (pluginExtension === void 0) { pluginExtension = null; }
  59800. return new Promise(function (resolve, reject) {
  59801. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59802. resolve({
  59803. meshes: meshes,
  59804. particleSystems: particleSystems,
  59805. skeletons: skeletons
  59806. });
  59807. }, onProgress, function (scene, message, exception) {
  59808. reject(exception || new Error(message));
  59809. });
  59810. });
  59811. };
  59812. /**
  59813. * Load a scene
  59814. * @param rootUrl a string that defines the root url for scene and resources
  59815. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59816. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59817. * @param onSuccess a callback with the scene when import succeeds
  59818. * @param onProgress a callback with a progress event for each file being loaded
  59819. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59820. * @param pluginExtension the extension used to determine the plugin
  59821. * @returns The loaded plugin
  59822. */
  59823. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59824. if (onSuccess === void 0) { onSuccess = null; }
  59825. if (onProgress === void 0) { onProgress = null; }
  59826. if (onError === void 0) { onError = null; }
  59827. if (pluginExtension === void 0) { pluginExtension = null; }
  59828. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59829. };
  59830. /**
  59831. * Load a scene
  59832. * @param rootUrl a string that defines the root url for scene and resources
  59833. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59834. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59835. * @param onProgress a callback with a progress event for each file being loaded
  59836. * @param pluginExtension the extension used to determine the plugin
  59837. * @returns The loaded scene
  59838. */
  59839. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59840. if (onProgress === void 0) { onProgress = null; }
  59841. if (pluginExtension === void 0) { pluginExtension = null; }
  59842. return new Promise(function (resolve, reject) {
  59843. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59844. resolve(scene);
  59845. }, onProgress, function (scene, message, exception) {
  59846. reject(exception || new Error(message));
  59847. }, pluginExtension);
  59848. });
  59849. };
  59850. /**
  59851. * Append a scene
  59852. * @param rootUrl a string that defines the root url for scene and resources
  59853. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59854. * @param scene is the instance of BABYLON.Scene to append to
  59855. * @param onSuccess a callback with the scene when import succeeds
  59856. * @param onProgress a callback with a progress event for each file being loaded
  59857. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59858. * @param pluginExtension the extension used to determine the plugin
  59859. * @returns The loaded plugin
  59860. */
  59861. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59862. if (onSuccess === void 0) { onSuccess = null; }
  59863. if (onProgress === void 0) { onProgress = null; }
  59864. if (onError === void 0) { onError = null; }
  59865. if (pluginExtension === void 0) { pluginExtension = null; }
  59866. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59867. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59868. return null;
  59869. }
  59870. if (SceneLoader.ShowLoadingScreen) {
  59871. scene.getEngine().displayLoadingUI();
  59872. }
  59873. var loadingToken = {};
  59874. scene._addPendingData(loadingToken);
  59875. var disposeHandler = function () {
  59876. scene._removePendingData(loadingToken);
  59877. scene.getEngine().hideLoadingUI();
  59878. };
  59879. var errorHandler = function (message, exception) {
  59880. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59881. if (onError) {
  59882. onError(scene, errorMessage, exception);
  59883. }
  59884. else {
  59885. BABYLON.Tools.Error(errorMessage);
  59886. // should the exception be thrown?
  59887. }
  59888. disposeHandler();
  59889. };
  59890. var progressHandler = onProgress ? function (event) {
  59891. try {
  59892. onProgress(event);
  59893. }
  59894. catch (e) {
  59895. errorHandler("Error in onProgress callback", e);
  59896. }
  59897. } : undefined;
  59898. var successHandler = function () {
  59899. if (onSuccess) {
  59900. try {
  59901. onSuccess(scene);
  59902. }
  59903. catch (e) {
  59904. errorHandler("Error in onSuccess callback", e);
  59905. }
  59906. }
  59907. scene._removePendingData(loadingToken);
  59908. };
  59909. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59910. if (sceneFilename === "") {
  59911. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59912. }
  59913. if (plugin.load) {
  59914. var syncedPlugin = plugin;
  59915. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59916. return;
  59917. }
  59918. scene.loadingPluginName = plugin.name;
  59919. successHandler();
  59920. }
  59921. else {
  59922. var asyncedPlugin = plugin;
  59923. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59924. scene.loadingPluginName = plugin.name;
  59925. successHandler();
  59926. }).catch(function (error) {
  59927. errorHandler(error.message, error);
  59928. });
  59929. }
  59930. if (SceneLoader.ShowLoadingScreen) {
  59931. scene.executeWhenReady(function () {
  59932. scene.getEngine().hideLoadingUI();
  59933. });
  59934. }
  59935. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59936. };
  59937. /**
  59938. * Append a scene
  59939. * @param rootUrl a string that defines the root url for scene and resources
  59940. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59941. * @param scene is the instance of BABYLON.Scene to append to
  59942. * @param onProgress a callback with a progress event for each file being loaded
  59943. * @param pluginExtension the extension used to determine the plugin
  59944. * @returns The given scene
  59945. */
  59946. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59947. if (onProgress === void 0) { onProgress = null; }
  59948. if (pluginExtension === void 0) { pluginExtension = null; }
  59949. return new Promise(function (resolve, reject) {
  59950. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59951. resolve(scene);
  59952. }, onProgress, function (scene, message, exception) {
  59953. reject(exception || new Error(message));
  59954. }, pluginExtension);
  59955. });
  59956. };
  59957. /**
  59958. * Load a scene into an asset container
  59959. * @param rootUrl a string that defines the root url for scene and resources
  59960. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59961. * @param scene is the instance of BABYLON.Scene to append to
  59962. * @param onSuccess a callback with the scene when import succeeds
  59963. * @param onProgress a callback with a progress event for each file being loaded
  59964. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59965. * @param pluginExtension the extension used to determine the plugin
  59966. * @returns The loaded plugin
  59967. */
  59968. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59969. if (onSuccess === void 0) { onSuccess = null; }
  59970. if (onProgress === void 0) { onProgress = null; }
  59971. if (onError === void 0) { onError = null; }
  59972. if (pluginExtension === void 0) { pluginExtension = null; }
  59973. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59974. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59975. return null;
  59976. }
  59977. var loadingToken = {};
  59978. scene._addPendingData(loadingToken);
  59979. var disposeHandler = function () {
  59980. scene._removePendingData(loadingToken);
  59981. };
  59982. var errorHandler = function (message, exception) {
  59983. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59984. if (onError) {
  59985. onError(scene, errorMessage, exception);
  59986. }
  59987. else {
  59988. BABYLON.Tools.Error(errorMessage);
  59989. // should the exception be thrown?
  59990. }
  59991. disposeHandler();
  59992. };
  59993. var progressHandler = onProgress ? function (event) {
  59994. try {
  59995. onProgress(event);
  59996. }
  59997. catch (e) {
  59998. errorHandler("Error in onProgress callback", e);
  59999. }
  60000. } : undefined;
  60001. var successHandler = function (assets) {
  60002. if (onSuccess) {
  60003. try {
  60004. onSuccess(assets);
  60005. }
  60006. catch (e) {
  60007. errorHandler("Error in onSuccess callback", e);
  60008. }
  60009. }
  60010. scene._removePendingData(loadingToken);
  60011. };
  60012. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60013. if (plugin.loadAssetContainer) {
  60014. var syncedPlugin = plugin;
  60015. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60016. if (!assetContainer) {
  60017. return;
  60018. }
  60019. scene.loadingPluginName = plugin.name;
  60020. successHandler(assetContainer);
  60021. }
  60022. else if (plugin.loadAssetContainerAsync) {
  60023. var asyncedPlugin = plugin;
  60024. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60025. scene.loadingPluginName = plugin.name;
  60026. successHandler(assetContainer);
  60027. }).catch(function (error) {
  60028. errorHandler(error.message, error);
  60029. });
  60030. }
  60031. else {
  60032. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60033. }
  60034. if (SceneLoader.ShowLoadingScreen) {
  60035. scene.executeWhenReady(function () {
  60036. scene.getEngine().hideLoadingUI();
  60037. });
  60038. }
  60039. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60040. };
  60041. /**
  60042. * Load a scene into an asset container
  60043. * @param rootUrl a string that defines the root url for scene and resources
  60044. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60045. * @param scene is the instance of BABYLON.Scene to append to
  60046. * @param onProgress a callback with a progress event for each file being loaded
  60047. * @param pluginExtension the extension used to determine the plugin
  60048. * @returns The loaded asset container
  60049. */
  60050. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60051. if (onProgress === void 0) { onProgress = null; }
  60052. if (pluginExtension === void 0) { pluginExtension = null; }
  60053. return new Promise(function (resolve, reject) {
  60054. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60055. resolve(assetContainer);
  60056. }, onProgress, function (scene, message, exception) {
  60057. reject(exception || new Error(message));
  60058. }, pluginExtension);
  60059. });
  60060. };
  60061. // Flags
  60062. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60063. SceneLoader._ShowLoadingScreen = true;
  60064. SceneLoader._CleanBoneMatrixWeights = false;
  60065. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60066. // Members
  60067. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60068. SceneLoader._registeredPlugins = {};
  60069. return SceneLoader;
  60070. }());
  60071. BABYLON.SceneLoader = SceneLoader;
  60072. ;
  60073. })(BABYLON || (BABYLON = {}));
  60074. //# sourceMappingURL=babylon.sceneLoader.js.map
  60075. var BABYLON;
  60076. (function (BABYLON) {
  60077. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60078. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60079. var parsedMaterial = parsedData.materials[index];
  60080. if (parsedMaterial.id === id) {
  60081. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60082. }
  60083. }
  60084. return null;
  60085. };
  60086. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60087. for (var i in names) {
  60088. if (mesh.name === names[i]) {
  60089. hierarchyIds.push(mesh.id);
  60090. return true;
  60091. }
  60092. }
  60093. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60094. hierarchyIds.push(mesh.id);
  60095. return true;
  60096. }
  60097. return false;
  60098. };
  60099. var logOperation = function (operation, producer) {
  60100. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60101. };
  60102. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60103. if (addToScene === void 0) { addToScene = false; }
  60104. var container = new BABYLON.AssetContainer(scene);
  60105. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60106. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60107. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60108. // and avoid problems with multiple concurrent .babylon loads.
  60109. var log = "importScene has failed JSON parse";
  60110. try {
  60111. var parsedData = JSON.parse(data);
  60112. log = "";
  60113. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60114. var index;
  60115. var cache;
  60116. // Lights
  60117. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60118. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60119. var parsedLight = parsedData.lights[index];
  60120. var light = BABYLON.Light.Parse(parsedLight, scene);
  60121. if (light) {
  60122. container.lights.push(light);
  60123. log += (index === 0 ? "\n\tLights:" : "");
  60124. log += "\n\t\t" + light.toString(fullDetails);
  60125. }
  60126. }
  60127. }
  60128. // Animations
  60129. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60130. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60131. var parsedAnimation = parsedData.animations[index];
  60132. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60133. scene.animations.push(animation);
  60134. container.animations.push(animation);
  60135. log += (index === 0 ? "\n\tAnimations:" : "");
  60136. log += "\n\t\t" + animation.toString(fullDetails);
  60137. }
  60138. }
  60139. // Materials
  60140. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60141. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60142. var parsedMaterial = parsedData.materials[index];
  60143. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60144. container.materials.push(mat);
  60145. log += (index === 0 ? "\n\tMaterials:" : "");
  60146. log += "\n\t\t" + mat.toString(fullDetails);
  60147. }
  60148. }
  60149. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60150. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60151. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60152. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60153. container.multiMaterials.push(mmat);
  60154. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60155. log += "\n\t\t" + mmat.toString(fullDetails);
  60156. }
  60157. }
  60158. // Morph targets
  60159. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60160. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60161. var managerData = _a[_i];
  60162. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60163. }
  60164. }
  60165. // Skeletons
  60166. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60167. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60168. var parsedSkeleton = parsedData.skeletons[index];
  60169. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60170. container.skeletons.push(skeleton);
  60171. log += (index === 0 ? "\n\tSkeletons:" : "");
  60172. log += "\n\t\t" + skeleton.toString(fullDetails);
  60173. }
  60174. }
  60175. // Geometries
  60176. var geometries = parsedData.geometries;
  60177. if (geometries !== undefined && geometries !== null) {
  60178. var addedGeometry = new Array();
  60179. // Boxes
  60180. var boxes = geometries.boxes;
  60181. if (boxes !== undefined && boxes !== null) {
  60182. for (index = 0, cache = boxes.length; index < cache; index++) {
  60183. var parsedBox = boxes[index];
  60184. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60185. }
  60186. }
  60187. // Spheres
  60188. var spheres = geometries.spheres;
  60189. if (spheres !== undefined && spheres !== null) {
  60190. for (index = 0, cache = spheres.length; index < cache; index++) {
  60191. var parsedSphere = spheres[index];
  60192. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60193. }
  60194. }
  60195. // Cylinders
  60196. var cylinders = geometries.cylinders;
  60197. if (cylinders !== undefined && cylinders !== null) {
  60198. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60199. var parsedCylinder = cylinders[index];
  60200. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60201. }
  60202. }
  60203. // Toruses
  60204. var toruses = geometries.toruses;
  60205. if (toruses !== undefined && toruses !== null) {
  60206. for (index = 0, cache = toruses.length; index < cache; index++) {
  60207. var parsedTorus = toruses[index];
  60208. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60209. }
  60210. }
  60211. // Grounds
  60212. var grounds = geometries.grounds;
  60213. if (grounds !== undefined && grounds !== null) {
  60214. for (index = 0, cache = grounds.length; index < cache; index++) {
  60215. var parsedGround = grounds[index];
  60216. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60217. }
  60218. }
  60219. // Planes
  60220. var planes = geometries.planes;
  60221. if (planes !== undefined && planes !== null) {
  60222. for (index = 0, cache = planes.length; index < cache; index++) {
  60223. var parsedPlane = planes[index];
  60224. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60225. }
  60226. }
  60227. // TorusKnots
  60228. var torusKnots = geometries.torusKnots;
  60229. if (torusKnots !== undefined && torusKnots !== null) {
  60230. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60231. var parsedTorusKnot = torusKnots[index];
  60232. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60233. }
  60234. }
  60235. // VertexData
  60236. var vertexData = geometries.vertexData;
  60237. if (vertexData !== undefined && vertexData !== null) {
  60238. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60239. var parsedVertexData = vertexData[index];
  60240. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60241. }
  60242. }
  60243. addedGeometry.forEach(function (g) {
  60244. if (g) {
  60245. container.geometries.push(g);
  60246. }
  60247. });
  60248. }
  60249. // Transform nodes
  60250. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60251. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60252. var parsedTransformNode = parsedData.transformNodes[index];
  60253. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60254. container.transformNodes.push(node);
  60255. }
  60256. }
  60257. // Meshes
  60258. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60259. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60260. var parsedMesh = parsedData.meshes[index];
  60261. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60262. container.meshes.push(mesh);
  60263. log += (index === 0 ? "\n\tMeshes:" : "");
  60264. log += "\n\t\t" + mesh.toString(fullDetails);
  60265. }
  60266. }
  60267. // Cameras
  60268. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60269. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60270. var parsedCamera = parsedData.cameras[index];
  60271. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60272. container.cameras.push(camera);
  60273. log += (index === 0 ? "\n\tCameras:" : "");
  60274. log += "\n\t\t" + camera.toString(fullDetails);
  60275. }
  60276. }
  60277. // Browsing all the graph to connect the dots
  60278. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60279. var camera = scene.cameras[index];
  60280. if (camera._waitingParentId) {
  60281. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60282. camera._waitingParentId = null;
  60283. }
  60284. }
  60285. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60286. var light_1 = scene.lights[index];
  60287. if (light_1 && light_1._waitingParentId) {
  60288. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60289. light_1._waitingParentId = null;
  60290. }
  60291. }
  60292. // Sounds
  60293. // TODO: add sound
  60294. var loadedSounds = [];
  60295. var loadedSound;
  60296. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60297. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60298. var parsedSound = parsedData.sounds[index];
  60299. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60300. if (!parsedSound.url)
  60301. parsedSound.url = parsedSound.name;
  60302. if (!loadedSounds[parsedSound.url]) {
  60303. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60304. loadedSounds[parsedSound.url] = loadedSound;
  60305. container.sounds.push(loadedSound);
  60306. }
  60307. else {
  60308. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60309. }
  60310. }
  60311. else {
  60312. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60313. }
  60314. }
  60315. }
  60316. loadedSounds = [];
  60317. // Connect parents & children and parse actions
  60318. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60319. var transformNode = scene.transformNodes[index];
  60320. if (transformNode._waitingParentId) {
  60321. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60322. transformNode._waitingParentId = null;
  60323. }
  60324. }
  60325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60326. var mesh = scene.meshes[index];
  60327. if (mesh._waitingParentId) {
  60328. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60329. mesh._waitingParentId = null;
  60330. }
  60331. if (mesh._waitingActions) {
  60332. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60333. mesh._waitingActions = null;
  60334. }
  60335. }
  60336. // freeze world matrix application
  60337. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60338. var currentMesh = scene.meshes[index];
  60339. if (currentMesh._waitingFreezeWorldMatrix) {
  60340. currentMesh.freezeWorldMatrix();
  60341. currentMesh._waitingFreezeWorldMatrix = null;
  60342. }
  60343. else {
  60344. currentMesh.computeWorldMatrix(true);
  60345. }
  60346. }
  60347. // Particles Systems
  60348. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60349. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60350. var parsedParticleSystem = parsedData.particleSystems[index];
  60351. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60352. container.particleSystems.push(ps);
  60353. }
  60354. }
  60355. // Lens flares
  60356. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60357. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60358. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60359. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60360. container.lensFlareSystems.push(lf);
  60361. }
  60362. }
  60363. // Shadows
  60364. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60365. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60366. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60367. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60368. container.shadowGenerators.push(sg);
  60369. }
  60370. }
  60371. // Lights exclusions / inclusions
  60372. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60373. var light_2 = scene.lights[index];
  60374. // Excluded check
  60375. if (light_2._excludedMeshesIds.length > 0) {
  60376. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60377. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60378. if (excludedMesh) {
  60379. light_2.excludedMeshes.push(excludedMesh);
  60380. }
  60381. }
  60382. light_2._excludedMeshesIds = [];
  60383. }
  60384. // Included check
  60385. if (light_2._includedOnlyMeshesIds.length > 0) {
  60386. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60387. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60388. if (includedOnlyMesh) {
  60389. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60390. }
  60391. }
  60392. light_2._includedOnlyMeshesIds = [];
  60393. }
  60394. }
  60395. // Actions (scene)
  60396. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60397. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60398. }
  60399. if (!addToScene) {
  60400. container.removeAllFromScene();
  60401. }
  60402. }
  60403. catch (err) {
  60404. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60405. if (onError) {
  60406. onError(msg, err);
  60407. }
  60408. else {
  60409. BABYLON.Tools.Log(msg);
  60410. throw err;
  60411. }
  60412. }
  60413. finally {
  60414. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60415. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60416. }
  60417. }
  60418. return container;
  60419. };
  60420. BABYLON.SceneLoader.RegisterPlugin({
  60421. name: "babylon.js",
  60422. extensions: ".babylon",
  60423. canDirectLoad: function (data) {
  60424. if (data.indexOf("babylon") !== -1) {
  60425. return true;
  60426. }
  60427. return false;
  60428. },
  60429. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60430. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60431. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60432. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60433. // and avoid problems with multiple concurrent .babylon loads.
  60434. var log = "importMesh has failed JSON parse";
  60435. try {
  60436. var parsedData = JSON.parse(data);
  60437. log = "";
  60438. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60439. if (!meshesNames) {
  60440. meshesNames = null;
  60441. }
  60442. else if (!Array.isArray(meshesNames)) {
  60443. meshesNames = [meshesNames];
  60444. }
  60445. var hierarchyIds = new Array();
  60446. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60447. var loadedSkeletonsIds = [];
  60448. var loadedMaterialsIds = [];
  60449. var index;
  60450. var cache;
  60451. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60452. var parsedMesh = parsedData.meshes[index];
  60453. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60454. if (meshesNames !== null) {
  60455. // Remove found mesh name from list.
  60456. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60457. }
  60458. //Geometry?
  60459. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60460. //does the file contain geometries?
  60461. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60462. //find the correct geometry and add it to the scene
  60463. var found = false;
  60464. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60465. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60466. return;
  60467. }
  60468. else {
  60469. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60470. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60471. switch (geometryType) {
  60472. case "boxes":
  60473. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60474. break;
  60475. case "spheres":
  60476. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60477. break;
  60478. case "cylinders":
  60479. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60480. break;
  60481. case "toruses":
  60482. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60483. break;
  60484. case "grounds":
  60485. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60486. break;
  60487. case "planes":
  60488. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60489. break;
  60490. case "torusKnots":
  60491. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60492. break;
  60493. case "vertexData":
  60494. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60495. break;
  60496. }
  60497. found = true;
  60498. }
  60499. });
  60500. }
  60501. });
  60502. if (found === false) {
  60503. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60504. }
  60505. }
  60506. }
  60507. // Material ?
  60508. if (parsedMesh.materialId) {
  60509. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60510. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60511. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60512. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60513. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60514. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60515. var subMatId = parsedMultiMaterial.materials[matIndex];
  60516. loadedMaterialsIds.push(subMatId);
  60517. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60518. if (mat) {
  60519. log += "\n\tMaterial " + mat.toString(fullDetails);
  60520. }
  60521. }
  60522. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60523. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60524. if (mmat) {
  60525. materialFound = true;
  60526. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60527. }
  60528. break;
  60529. }
  60530. }
  60531. }
  60532. if (materialFound === false) {
  60533. loadedMaterialsIds.push(parsedMesh.materialId);
  60534. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60535. if (!mat) {
  60536. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60537. }
  60538. else {
  60539. log += "\n\tMaterial " + mat.toString(fullDetails);
  60540. }
  60541. }
  60542. }
  60543. // Skeleton ?
  60544. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60545. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60546. if (skeletonAlreadyLoaded === false) {
  60547. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60548. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60549. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60550. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60551. skeletons.push(skeleton);
  60552. loadedSkeletonsIds.push(parsedSkeleton.id);
  60553. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60554. }
  60555. }
  60556. }
  60557. }
  60558. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60559. meshes.push(mesh);
  60560. log += "\n\tMesh " + mesh.toString(fullDetails);
  60561. }
  60562. }
  60563. // Connecting parents
  60564. var currentMesh;
  60565. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60566. currentMesh = scene.meshes[index];
  60567. if (currentMesh._waitingParentId) {
  60568. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60569. currentMesh._waitingParentId = null;
  60570. }
  60571. }
  60572. // freeze and compute world matrix application
  60573. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60574. currentMesh = scene.meshes[index];
  60575. if (currentMesh._waitingFreezeWorldMatrix) {
  60576. currentMesh.freezeWorldMatrix();
  60577. currentMesh._waitingFreezeWorldMatrix = null;
  60578. }
  60579. else {
  60580. currentMesh.computeWorldMatrix(true);
  60581. }
  60582. }
  60583. }
  60584. // Particles
  60585. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60586. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60587. var parsedParticleSystem = parsedData.particleSystems[index];
  60588. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60589. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60590. }
  60591. }
  60592. }
  60593. return true;
  60594. }
  60595. catch (err) {
  60596. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60597. if (onError) {
  60598. onError(msg, err);
  60599. }
  60600. else {
  60601. BABYLON.Tools.Log(msg);
  60602. throw err;
  60603. }
  60604. }
  60605. finally {
  60606. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60607. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60608. }
  60609. }
  60610. return false;
  60611. },
  60612. load: function (scene, data, rootUrl, onError) {
  60613. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60614. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60615. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60616. // and avoid problems with multiple concurrent .babylon loads.
  60617. var log = "importScene has failed JSON parse";
  60618. try {
  60619. var parsedData = JSON.parse(data);
  60620. log = "";
  60621. // Scene
  60622. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60623. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60624. }
  60625. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60626. scene.autoClear = parsedData.autoClear;
  60627. }
  60628. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60629. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60630. }
  60631. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60632. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60633. }
  60634. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60635. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60636. }
  60637. // Fog
  60638. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60639. scene.fogMode = parsedData.fogMode;
  60640. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60641. scene.fogStart = parsedData.fogStart;
  60642. scene.fogEnd = parsedData.fogEnd;
  60643. scene.fogDensity = parsedData.fogDensity;
  60644. log += "\tFog mode for scene: ";
  60645. switch (scene.fogMode) {
  60646. // getters not compiling, so using hardcoded
  60647. case 1:
  60648. log += "exp\n";
  60649. break;
  60650. case 2:
  60651. log += "exp2\n";
  60652. break;
  60653. case 3:
  60654. log += "linear\n";
  60655. break;
  60656. }
  60657. }
  60658. //Physics
  60659. if (parsedData.physicsEnabled) {
  60660. var physicsPlugin;
  60661. if (parsedData.physicsEngine === "cannon") {
  60662. physicsPlugin = new BABYLON.CannonJSPlugin();
  60663. }
  60664. else if (parsedData.physicsEngine === "oimo") {
  60665. physicsPlugin = new BABYLON.OimoJSPlugin();
  60666. }
  60667. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60668. //else - default engine, which is currently oimo
  60669. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60670. scene.enablePhysics(physicsGravity, physicsPlugin);
  60671. }
  60672. // Metadata
  60673. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60674. scene.metadata = parsedData.metadata;
  60675. }
  60676. //collisions, if defined. otherwise, default is true
  60677. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60678. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60679. }
  60680. scene.workerCollisions = !!parsedData.workerCollisions;
  60681. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60682. if (!container) {
  60683. return false;
  60684. }
  60685. if (parsedData.autoAnimate) {
  60686. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60687. }
  60688. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60689. scene.setActiveCameraByID(parsedData.activeCameraID);
  60690. }
  60691. // Environment texture
  60692. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60693. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60694. if (parsedData.createDefaultSkybox === true) {
  60695. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60696. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60697. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60698. }
  60699. }
  60700. // Finish
  60701. return true;
  60702. }
  60703. catch (err) {
  60704. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60705. if (onError) {
  60706. onError(msg, err);
  60707. }
  60708. else {
  60709. BABYLON.Tools.Log(msg);
  60710. throw err;
  60711. }
  60712. }
  60713. finally {
  60714. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60715. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60716. }
  60717. }
  60718. return false;
  60719. },
  60720. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60721. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60722. return container;
  60723. }
  60724. });
  60725. })(BABYLON || (BABYLON = {}));
  60726. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60727. var BABYLON;
  60728. (function (BABYLON) {
  60729. var FilesInput = /** @class */ (function () {
  60730. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60731. this.onProcessFileCallback = function () { return true; };
  60732. this._engine = engine;
  60733. this._currentScene = scene;
  60734. this._sceneLoadedCallback = sceneLoadedCallback;
  60735. this._progressCallback = progressCallback;
  60736. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60737. this._textureLoadingCallback = textureLoadingCallback;
  60738. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60739. this._onReloadCallback = onReloadCallback;
  60740. this._errorCallback = errorCallback;
  60741. }
  60742. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60743. var _this = this;
  60744. if (elementToMonitor) {
  60745. this._elementToMonitor = elementToMonitor;
  60746. this._dragEnterHandler = function (e) { _this.drag(e); };
  60747. this._dragOverHandler = function (e) { _this.drag(e); };
  60748. this._dropHandler = function (e) { _this.drop(e); };
  60749. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60750. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60751. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60752. }
  60753. };
  60754. FilesInput.prototype.dispose = function () {
  60755. if (!this._elementToMonitor) {
  60756. return;
  60757. }
  60758. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60759. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60760. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60761. };
  60762. FilesInput.prototype.renderFunction = function () {
  60763. if (this._additionalRenderLoopLogicCallback) {
  60764. this._additionalRenderLoopLogicCallback();
  60765. }
  60766. if (this._currentScene) {
  60767. if (this._textureLoadingCallback) {
  60768. var remaining = this._currentScene.getWaitingItemsCount();
  60769. if (remaining > 0) {
  60770. this._textureLoadingCallback(remaining);
  60771. }
  60772. }
  60773. this._currentScene.render();
  60774. }
  60775. };
  60776. FilesInput.prototype.drag = function (e) {
  60777. e.stopPropagation();
  60778. e.preventDefault();
  60779. };
  60780. FilesInput.prototype.drop = function (eventDrop) {
  60781. eventDrop.stopPropagation();
  60782. eventDrop.preventDefault();
  60783. this.loadFiles(eventDrop);
  60784. };
  60785. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60786. var _this = this;
  60787. var reader = folder.createReader();
  60788. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60789. reader.readEntries(function (entries) {
  60790. remaining.count += entries.length;
  60791. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60792. var entry = entries_1[_i];
  60793. if (entry.isFile) {
  60794. entry.file(function (file) {
  60795. file.correctName = relativePath + file.name;
  60796. files.push(file);
  60797. if (--remaining.count === 0) {
  60798. callback();
  60799. }
  60800. });
  60801. }
  60802. else if (entry.isDirectory) {
  60803. _this._traverseFolder(entry, files, remaining, callback);
  60804. }
  60805. }
  60806. if (--remaining.count) {
  60807. callback();
  60808. }
  60809. });
  60810. };
  60811. FilesInput.prototype._processFiles = function (files) {
  60812. for (var i = 0; i < files.length; i++) {
  60813. var name = files[i].correctName.toLowerCase();
  60814. var extension = name.split('.').pop();
  60815. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60816. continue;
  60817. }
  60818. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60819. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60820. this._sceneFileToLoad = files[i];
  60821. }
  60822. else {
  60823. FilesInput.FilesToLoad[name] = files[i];
  60824. }
  60825. }
  60826. };
  60827. FilesInput.prototype.loadFiles = function (event) {
  60828. var _this = this;
  60829. if (this._startingProcessingFilesCallback)
  60830. this._startingProcessingFilesCallback();
  60831. // Handling data transfer via drag'n'drop
  60832. if (event && event.dataTransfer && event.dataTransfer.files) {
  60833. this._filesToLoad = event.dataTransfer.files;
  60834. }
  60835. // Handling files from input files
  60836. if (event && event.target && event.target.files) {
  60837. this._filesToLoad = event.target.files;
  60838. }
  60839. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60840. var files_1 = new Array();
  60841. var folders = [];
  60842. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60843. for (var i = 0; i < this._filesToLoad.length; i++) {
  60844. var fileToLoad = this._filesToLoad[i];
  60845. var name_1 = fileToLoad.name.toLowerCase();
  60846. var entry = void 0;
  60847. fileToLoad.correctName = name_1;
  60848. if (items) {
  60849. var item = items[i];
  60850. if (item.getAsEntry) {
  60851. entry = item.getAsEntry();
  60852. }
  60853. else if (item.webkitGetAsEntry) {
  60854. entry = item.webkitGetAsEntry();
  60855. }
  60856. }
  60857. if (!entry) {
  60858. files_1.push(fileToLoad);
  60859. }
  60860. else {
  60861. if (entry.isDirectory) {
  60862. folders.push(entry);
  60863. }
  60864. else {
  60865. files_1.push(fileToLoad);
  60866. }
  60867. }
  60868. }
  60869. if (folders.length === 0) {
  60870. this._processFiles(files_1);
  60871. this._processReload();
  60872. }
  60873. else {
  60874. var remaining = { count: folders.length };
  60875. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60876. var folder = folders_1[_i];
  60877. this._traverseFolder(folder, files_1, remaining, function () {
  60878. _this._processFiles(files_1);
  60879. if (remaining.count === 0) {
  60880. _this._processReload();
  60881. }
  60882. });
  60883. }
  60884. }
  60885. }
  60886. };
  60887. FilesInput.prototype._processReload = function () {
  60888. if (this._onReloadCallback) {
  60889. this._onReloadCallback(this._sceneFileToLoad);
  60890. }
  60891. else {
  60892. this.reload();
  60893. }
  60894. };
  60895. FilesInput.prototype.reload = function () {
  60896. var _this = this;
  60897. // If a scene file has been provided
  60898. if (this._sceneFileToLoad) {
  60899. if (this._currentScene) {
  60900. if (BABYLON.Tools.errorsCount > 0) {
  60901. BABYLON.Tools.ClearLogCache();
  60902. }
  60903. this._engine.stopRenderLoop();
  60904. this._currentScene.dispose();
  60905. }
  60906. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60907. if (_this._progressCallback) {
  60908. _this._progressCallback(progress);
  60909. }
  60910. }).then(function (scene) {
  60911. _this._currentScene = scene;
  60912. if (_this._sceneLoadedCallback) {
  60913. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60914. }
  60915. // Wait for textures and shaders to be ready
  60916. _this._currentScene.executeWhenReady(function () {
  60917. _this._engine.runRenderLoop(function () {
  60918. _this.renderFunction();
  60919. });
  60920. });
  60921. }).catch(function (error) {
  60922. if (_this._errorCallback) {
  60923. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60924. }
  60925. });
  60926. }
  60927. else {
  60928. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60929. }
  60930. };
  60931. FilesInput.FilesToLoad = {};
  60932. return FilesInput;
  60933. }());
  60934. BABYLON.FilesInput = FilesInput;
  60935. })(BABYLON || (BABYLON = {}));
  60936. //# sourceMappingURL=babylon.filesInput.js.map
  60937. var BABYLON;
  60938. (function (BABYLON) {
  60939. /**
  60940. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60941. * The underlying implementation relies on an associative array to ensure the best performances.
  60942. * The value can be anything including 'null' but except 'undefined'
  60943. */
  60944. var StringDictionary = /** @class */ (function () {
  60945. function StringDictionary() {
  60946. this._count = 0;
  60947. this._data = {};
  60948. }
  60949. /**
  60950. * This will clear this dictionary and copy the content from the 'source' one.
  60951. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60952. * @param source the dictionary to take the content from and copy to this dictionary
  60953. */
  60954. StringDictionary.prototype.copyFrom = function (source) {
  60955. var _this = this;
  60956. this.clear();
  60957. source.forEach(function (t, v) { return _this.add(t, v); });
  60958. };
  60959. /**
  60960. * Get a value based from its key
  60961. * @param key the given key to get the matching value from
  60962. * @return the value if found, otherwise undefined is returned
  60963. */
  60964. StringDictionary.prototype.get = function (key) {
  60965. var val = this._data[key];
  60966. if (val !== undefined) {
  60967. return val;
  60968. }
  60969. return undefined;
  60970. };
  60971. /**
  60972. * Get a value from its key or add it if it doesn't exist.
  60973. * This method will ensure you that a given key/data will be present in the dictionary.
  60974. * @param key the given key to get the matching value from
  60975. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60976. * The factory will only be invoked if there's no data for the given key.
  60977. * @return the value corresponding to the key.
  60978. */
  60979. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60980. var val = this.get(key);
  60981. if (val !== undefined) {
  60982. return val;
  60983. }
  60984. val = factory(key);
  60985. if (val) {
  60986. this.add(key, val);
  60987. }
  60988. return val;
  60989. };
  60990. /**
  60991. * Get a value from its key if present in the dictionary otherwise add it
  60992. * @param key the key to get the value from
  60993. * @param val if there's no such key/value pair in the dictionary add it with this value
  60994. * @return the value corresponding to the key
  60995. */
  60996. StringDictionary.prototype.getOrAdd = function (key, val) {
  60997. var curVal = this.get(key);
  60998. if (curVal !== undefined) {
  60999. return curVal;
  61000. }
  61001. this.add(key, val);
  61002. return val;
  61003. };
  61004. /**
  61005. * Check if there's a given key in the dictionary
  61006. * @param key the key to check for
  61007. * @return true if the key is present, false otherwise
  61008. */
  61009. StringDictionary.prototype.contains = function (key) {
  61010. return this._data[key] !== undefined;
  61011. };
  61012. /**
  61013. * Add a new key and its corresponding value
  61014. * @param key the key to add
  61015. * @param value the value corresponding to the key
  61016. * @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
  61017. */
  61018. StringDictionary.prototype.add = function (key, value) {
  61019. if (this._data[key] !== undefined) {
  61020. return false;
  61021. }
  61022. this._data[key] = value;
  61023. ++this._count;
  61024. return true;
  61025. };
  61026. StringDictionary.prototype.set = function (key, value) {
  61027. if (this._data[key] === undefined) {
  61028. return false;
  61029. }
  61030. this._data[key] = value;
  61031. return true;
  61032. };
  61033. /**
  61034. * Get the element of the given key and remove it from the dictionary
  61035. * @param key
  61036. */
  61037. StringDictionary.prototype.getAndRemove = function (key) {
  61038. var val = this.get(key);
  61039. if (val !== undefined) {
  61040. delete this._data[key];
  61041. --this._count;
  61042. return val;
  61043. }
  61044. return null;
  61045. };
  61046. /**
  61047. * Remove a key/value from the dictionary.
  61048. * @param key the key to remove
  61049. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61050. */
  61051. StringDictionary.prototype.remove = function (key) {
  61052. if (this.contains(key)) {
  61053. delete this._data[key];
  61054. --this._count;
  61055. return true;
  61056. }
  61057. return false;
  61058. };
  61059. /**
  61060. * Clear the whole content of the dictionary
  61061. */
  61062. StringDictionary.prototype.clear = function () {
  61063. this._data = {};
  61064. this._count = 0;
  61065. };
  61066. Object.defineProperty(StringDictionary.prototype, "count", {
  61067. get: function () {
  61068. return this._count;
  61069. },
  61070. enumerable: true,
  61071. configurable: true
  61072. });
  61073. /**
  61074. * Execute a callback on each key/val of the dictionary.
  61075. * Note that you can remove any element in this dictionary in the callback implementation
  61076. * @param callback the callback to execute on a given key/value pair
  61077. */
  61078. StringDictionary.prototype.forEach = function (callback) {
  61079. for (var cur in this._data) {
  61080. var val = this._data[cur];
  61081. callback(cur, val);
  61082. }
  61083. };
  61084. /**
  61085. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61086. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61087. * Note that you can remove any element in this dictionary in the callback implementation
  61088. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61089. */
  61090. StringDictionary.prototype.first = function (callback) {
  61091. for (var cur in this._data) {
  61092. var val = this._data[cur];
  61093. var res = callback(cur, val);
  61094. if (res) {
  61095. return res;
  61096. }
  61097. }
  61098. return null;
  61099. };
  61100. return StringDictionary;
  61101. }());
  61102. BABYLON.StringDictionary = StringDictionary;
  61103. })(BABYLON || (BABYLON = {}));
  61104. //# sourceMappingURL=babylon.stringDictionary.js.map
  61105. var BABYLON;
  61106. (function (BABYLON) {
  61107. var Tags = /** @class */ (function () {
  61108. function Tags() {
  61109. }
  61110. Tags.EnableFor = function (obj) {
  61111. obj._tags = obj._tags || {};
  61112. obj.hasTags = function () {
  61113. return Tags.HasTags(obj);
  61114. };
  61115. obj.addTags = function (tagsString) {
  61116. return Tags.AddTagsTo(obj, tagsString);
  61117. };
  61118. obj.removeTags = function (tagsString) {
  61119. return Tags.RemoveTagsFrom(obj, tagsString);
  61120. };
  61121. obj.matchesTagsQuery = function (tagsQuery) {
  61122. return Tags.MatchesQuery(obj, tagsQuery);
  61123. };
  61124. };
  61125. Tags.DisableFor = function (obj) {
  61126. delete obj._tags;
  61127. delete obj.hasTags;
  61128. delete obj.addTags;
  61129. delete obj.removeTags;
  61130. delete obj.matchesTagsQuery;
  61131. };
  61132. Tags.HasTags = function (obj) {
  61133. if (!obj._tags) {
  61134. return false;
  61135. }
  61136. return !BABYLON.Tools.IsEmpty(obj._tags);
  61137. };
  61138. Tags.GetTags = function (obj, asString) {
  61139. if (asString === void 0) { asString = true; }
  61140. if (!obj._tags) {
  61141. return null;
  61142. }
  61143. if (asString) {
  61144. var tagsArray = [];
  61145. for (var tag in obj._tags) {
  61146. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61147. tagsArray.push(tag);
  61148. }
  61149. }
  61150. return tagsArray.join(" ");
  61151. }
  61152. else {
  61153. return obj._tags;
  61154. }
  61155. };
  61156. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61157. // a tag cannot start with '||', '&&', and '!'
  61158. // it cannot contain whitespaces
  61159. Tags.AddTagsTo = function (obj, tagsString) {
  61160. if (!tagsString) {
  61161. return;
  61162. }
  61163. if (typeof tagsString !== "string") {
  61164. return;
  61165. }
  61166. var tags = tagsString.split(" ");
  61167. tags.forEach(function (tag, index, array) {
  61168. Tags._AddTagTo(obj, tag);
  61169. });
  61170. };
  61171. Tags._AddTagTo = function (obj, tag) {
  61172. tag = tag.trim();
  61173. if (tag === "" || tag === "true" || tag === "false") {
  61174. return;
  61175. }
  61176. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61177. return;
  61178. }
  61179. Tags.EnableFor(obj);
  61180. obj._tags[tag] = true;
  61181. };
  61182. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61183. if (!Tags.HasTags(obj)) {
  61184. return;
  61185. }
  61186. var tags = tagsString.split(" ");
  61187. for (var t in tags) {
  61188. Tags._RemoveTagFrom(obj, tags[t]);
  61189. }
  61190. };
  61191. Tags._RemoveTagFrom = function (obj, tag) {
  61192. delete obj._tags[tag];
  61193. };
  61194. Tags.MatchesQuery = function (obj, tagsQuery) {
  61195. if (tagsQuery === undefined) {
  61196. return true;
  61197. }
  61198. if (tagsQuery === "") {
  61199. return Tags.HasTags(obj);
  61200. }
  61201. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61202. };
  61203. return Tags;
  61204. }());
  61205. BABYLON.Tags = Tags;
  61206. })(BABYLON || (BABYLON = {}));
  61207. //# sourceMappingURL=babylon.tags.js.map
  61208. var BABYLON;
  61209. (function (BABYLON) {
  61210. var AndOrNotEvaluator = /** @class */ (function () {
  61211. function AndOrNotEvaluator() {
  61212. }
  61213. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61214. if (!query.match(/\([^\(\)]*\)/g)) {
  61215. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61216. }
  61217. else {
  61218. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61219. // remove parenthesis
  61220. r = r.slice(1, r.length - 1);
  61221. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61222. });
  61223. }
  61224. if (query === "true") {
  61225. return true;
  61226. }
  61227. if (query === "false") {
  61228. return false;
  61229. }
  61230. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61231. };
  61232. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61233. evaluateCallback = evaluateCallback || (function (r) {
  61234. return r === "true" ? true : false;
  61235. });
  61236. var result;
  61237. var or = parenthesisContent.split("||");
  61238. for (var i in or) {
  61239. if (or.hasOwnProperty(i)) {
  61240. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61241. var and = ori.split("&&");
  61242. if (and.length > 1) {
  61243. for (var j = 0; j < and.length; ++j) {
  61244. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61245. if (andj !== "true" && andj !== "false") {
  61246. if (andj[0] === "!") {
  61247. result = !evaluateCallback(andj.substring(1));
  61248. }
  61249. else {
  61250. result = evaluateCallback(andj);
  61251. }
  61252. }
  61253. else {
  61254. result = andj === "true" ? true : false;
  61255. }
  61256. if (!result) {
  61257. ori = "false";
  61258. break;
  61259. }
  61260. }
  61261. }
  61262. if (result || ori === "true") {
  61263. result = true;
  61264. break;
  61265. }
  61266. // result equals false (or undefined)
  61267. if (ori !== "true" && ori !== "false") {
  61268. if (ori[0] === "!") {
  61269. result = !evaluateCallback(ori.substring(1));
  61270. }
  61271. else {
  61272. result = evaluateCallback(ori);
  61273. }
  61274. }
  61275. else {
  61276. result = ori === "true" ? true : false;
  61277. }
  61278. }
  61279. }
  61280. // the whole parenthesis scope is replaced by 'true' or 'false'
  61281. return result ? "true" : "false";
  61282. };
  61283. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61284. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61285. // remove whitespaces
  61286. r = r.replace(/[\s]/g, function () { return ""; });
  61287. return r.length % 2 ? "!" : "";
  61288. });
  61289. booleanString = booleanString.trim();
  61290. if (booleanString === "!true") {
  61291. booleanString = "false";
  61292. }
  61293. else if (booleanString === "!false") {
  61294. booleanString = "true";
  61295. }
  61296. return booleanString;
  61297. };
  61298. return AndOrNotEvaluator;
  61299. }());
  61300. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61301. })(BABYLON || (BABYLON = {}));
  61302. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61303. var BABYLON;
  61304. (function (BABYLON) {
  61305. var Database = /** @class */ (function () {
  61306. function Database(urlToScene, callbackManifestChecked) {
  61307. // Handling various flavors of prefixed version of IndexedDB
  61308. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61309. this.callbackManifestChecked = callbackManifestChecked;
  61310. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61311. this.db = null;
  61312. this._enableSceneOffline = false;
  61313. this._enableTexturesOffline = false;
  61314. this.manifestVersionFound = 0;
  61315. this.mustUpdateRessources = false;
  61316. this.hasReachedQuota = false;
  61317. if (!Database.IDBStorageEnabled) {
  61318. this.callbackManifestChecked(true);
  61319. }
  61320. else {
  61321. this.checkManifestFile();
  61322. }
  61323. }
  61324. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61325. get: function () {
  61326. return this._enableSceneOffline;
  61327. },
  61328. enumerable: true,
  61329. configurable: true
  61330. });
  61331. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61332. get: function () {
  61333. return this._enableTexturesOffline;
  61334. },
  61335. enumerable: true,
  61336. configurable: true
  61337. });
  61338. Database.prototype.checkManifestFile = function () {
  61339. var _this = this;
  61340. var noManifestFile = function () {
  61341. _this._enableSceneOffline = false;
  61342. _this._enableTexturesOffline = false;
  61343. _this.callbackManifestChecked(false);
  61344. };
  61345. var timeStampUsed = false;
  61346. var manifestURL = this.currentSceneUrl + ".manifest";
  61347. var xhr = new XMLHttpRequest();
  61348. if (navigator.onLine) {
  61349. // Adding a timestamp to by-pass browsers' cache
  61350. timeStampUsed = true;
  61351. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61352. }
  61353. xhr.open("GET", manifestURL, true);
  61354. xhr.addEventListener("load", function () {
  61355. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61356. try {
  61357. var manifestFile = JSON.parse(xhr.response);
  61358. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61359. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61360. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61361. _this.manifestVersionFound = manifestFile.version;
  61362. }
  61363. if (_this.callbackManifestChecked) {
  61364. _this.callbackManifestChecked(true);
  61365. }
  61366. }
  61367. catch (ex) {
  61368. noManifestFile();
  61369. }
  61370. }
  61371. else {
  61372. noManifestFile();
  61373. }
  61374. }, false);
  61375. xhr.addEventListener("error", function (event) {
  61376. if (timeStampUsed) {
  61377. timeStampUsed = false;
  61378. // Let's retry without the timeStamp
  61379. // It could fail when coupled with HTML5 Offline API
  61380. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61381. xhr.open("GET", retryManifestURL, true);
  61382. xhr.send();
  61383. }
  61384. else {
  61385. noManifestFile();
  61386. }
  61387. }, false);
  61388. try {
  61389. xhr.send();
  61390. }
  61391. catch (ex) {
  61392. BABYLON.Tools.Error("Error on XHR send request.");
  61393. this.callbackManifestChecked(false);
  61394. }
  61395. };
  61396. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61397. var _this = this;
  61398. var handleError = function () {
  61399. _this.isSupported = false;
  61400. if (errorCallback)
  61401. errorCallback();
  61402. };
  61403. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61404. // Your browser doesn't support IndexedDB
  61405. this.isSupported = false;
  61406. if (errorCallback)
  61407. errorCallback();
  61408. }
  61409. else {
  61410. // If the DB hasn't been opened or created yet
  61411. if (!this.db) {
  61412. this.hasReachedQuota = false;
  61413. this.isSupported = true;
  61414. var request = this.idbFactory.open("babylonjs", 1);
  61415. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61416. request.onerror = function (event) {
  61417. handleError();
  61418. };
  61419. // executes when a version change transaction cannot complete due to other active transactions
  61420. request.onblocked = function (event) {
  61421. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61422. handleError();
  61423. };
  61424. // DB has been opened successfully
  61425. request.onsuccess = function (event) {
  61426. _this.db = request.result;
  61427. successCallback();
  61428. };
  61429. // Initialization of the DB. Creating Scenes & Textures stores
  61430. request.onupgradeneeded = function (event) {
  61431. _this.db = (event.target).result;
  61432. if (_this.db) {
  61433. try {
  61434. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61435. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61436. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61437. }
  61438. catch (ex) {
  61439. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61440. handleError();
  61441. }
  61442. }
  61443. };
  61444. }
  61445. else {
  61446. if (successCallback)
  61447. successCallback();
  61448. }
  61449. }
  61450. };
  61451. Database.prototype.loadImageFromDB = function (url, image) {
  61452. var _this = this;
  61453. var completeURL = Database.ReturnFullUrlLocation(url);
  61454. var saveAndLoadImage = function () {
  61455. if (!_this.hasReachedQuota && _this.db !== null) {
  61456. // the texture is not yet in the DB, let's try to save it
  61457. _this._saveImageIntoDBAsync(completeURL, image);
  61458. }
  61459. else {
  61460. image.src = url;
  61461. }
  61462. };
  61463. if (!this.mustUpdateRessources) {
  61464. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61465. }
  61466. else {
  61467. saveAndLoadImage();
  61468. }
  61469. };
  61470. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61471. if (this.isSupported && this.db !== null) {
  61472. var texture;
  61473. var transaction = this.db.transaction(["textures"]);
  61474. transaction.onabort = function (event) {
  61475. image.src = url;
  61476. };
  61477. transaction.oncomplete = function (event) {
  61478. var blobTextureURL;
  61479. if (texture) {
  61480. var URL = window.URL || window.webkitURL;
  61481. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61482. image.onerror = function () {
  61483. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61484. image.src = url;
  61485. };
  61486. image.src = blobTextureURL;
  61487. }
  61488. else {
  61489. notInDBCallback();
  61490. }
  61491. };
  61492. var getRequest = transaction.objectStore("textures").get(url);
  61493. getRequest.onsuccess = function (event) {
  61494. texture = (event.target).result;
  61495. };
  61496. getRequest.onerror = function (event) {
  61497. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61498. image.src = url;
  61499. };
  61500. }
  61501. else {
  61502. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61503. image.src = url;
  61504. }
  61505. };
  61506. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61507. var _this = this;
  61508. if (this.isSupported) {
  61509. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61510. var generateBlobUrl = function () {
  61511. var blobTextureURL;
  61512. if (blob) {
  61513. var URL = window.URL || window.webkitURL;
  61514. try {
  61515. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61516. }
  61517. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61518. catch (ex) {
  61519. blobTextureURL = URL.createObjectURL(blob);
  61520. }
  61521. }
  61522. if (blobTextureURL) {
  61523. image.src = blobTextureURL;
  61524. }
  61525. };
  61526. if (Database.IsUASupportingBlobStorage) {
  61527. var xhr = new XMLHttpRequest(), blob;
  61528. xhr.open("GET", url, true);
  61529. xhr.responseType = "blob";
  61530. xhr.addEventListener("load", function () {
  61531. if (xhr.status === 200 && _this.db) {
  61532. // Blob as response (XHR2)
  61533. blob = xhr.response;
  61534. var transaction = _this.db.transaction(["textures"], "readwrite");
  61535. // the transaction could abort because of a QuotaExceededError error
  61536. transaction.onabort = function (event) {
  61537. try {
  61538. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61539. var srcElement = (event.srcElement || event.target);
  61540. var error = srcElement.error;
  61541. if (error && error.name === "QuotaExceededError") {
  61542. _this.hasReachedQuota = true;
  61543. }
  61544. }
  61545. catch (ex) { }
  61546. generateBlobUrl();
  61547. };
  61548. transaction.oncomplete = function (event) {
  61549. generateBlobUrl();
  61550. };
  61551. var newTexture = { textureUrl: url, data: blob };
  61552. try {
  61553. // Put the blob into the dabase
  61554. var addRequest = transaction.objectStore("textures").put(newTexture);
  61555. addRequest.onsuccess = function (event) {
  61556. };
  61557. addRequest.onerror = function (event) {
  61558. generateBlobUrl();
  61559. };
  61560. }
  61561. catch (ex) {
  61562. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61563. if (ex.code === 25) {
  61564. Database.IsUASupportingBlobStorage = false;
  61565. }
  61566. image.src = url;
  61567. }
  61568. }
  61569. else {
  61570. image.src = url;
  61571. }
  61572. }, false);
  61573. xhr.addEventListener("error", function (event) {
  61574. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61575. image.src = url;
  61576. }, false);
  61577. xhr.send();
  61578. }
  61579. else {
  61580. image.src = url;
  61581. }
  61582. }
  61583. else {
  61584. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61585. image.src = url;
  61586. }
  61587. };
  61588. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61589. var _this = this;
  61590. var updateVersion = function () {
  61591. // the version is not yet in the DB or we need to update it
  61592. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61593. };
  61594. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61595. };
  61596. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61597. var _this = this;
  61598. if (this.isSupported && this.db) {
  61599. var version;
  61600. try {
  61601. var transaction = this.db.transaction(["versions"]);
  61602. transaction.oncomplete = function (event) {
  61603. if (version) {
  61604. // If the version in the JSON file is > than the version in DB
  61605. if (_this.manifestVersionFound > version.data) {
  61606. _this.mustUpdateRessources = true;
  61607. updateInDBCallback();
  61608. }
  61609. else {
  61610. callback(version.data);
  61611. }
  61612. }
  61613. else {
  61614. _this.mustUpdateRessources = true;
  61615. updateInDBCallback();
  61616. }
  61617. };
  61618. transaction.onabort = function (event) {
  61619. callback(-1);
  61620. };
  61621. var getRequest = transaction.objectStore("versions").get(url);
  61622. getRequest.onsuccess = function (event) {
  61623. version = (event.target).result;
  61624. };
  61625. getRequest.onerror = function (event) {
  61626. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61627. callback(-1);
  61628. };
  61629. }
  61630. catch (ex) {
  61631. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61632. callback(-1);
  61633. }
  61634. }
  61635. else {
  61636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61637. callback(-1);
  61638. }
  61639. };
  61640. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61641. var _this = this;
  61642. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61643. try {
  61644. // Open a transaction to the database
  61645. var transaction = this.db.transaction(["versions"], "readwrite");
  61646. // the transaction could abort because of a QuotaExceededError error
  61647. transaction.onabort = function (event) {
  61648. try {
  61649. var error = event.srcElement['error'];
  61650. if (error && error.name === "QuotaExceededError") {
  61651. _this.hasReachedQuota = true;
  61652. }
  61653. }
  61654. catch (ex) { }
  61655. callback(-1);
  61656. };
  61657. transaction.oncomplete = function (event) {
  61658. callback(_this.manifestVersionFound);
  61659. };
  61660. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61661. // Put the scene into the database
  61662. var addRequest = transaction.objectStore("versions").put(newVersion);
  61663. addRequest.onsuccess = function (event) {
  61664. };
  61665. addRequest.onerror = function (event) {
  61666. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61667. };
  61668. }
  61669. catch (ex) {
  61670. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61671. callback(-1);
  61672. }
  61673. }
  61674. else {
  61675. callback(-1);
  61676. }
  61677. };
  61678. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61679. var _this = this;
  61680. var completeUrl = Database.ReturnFullUrlLocation(url);
  61681. var saveAndLoadFile = function () {
  61682. // the scene is not yet in the DB, let's try to save it
  61683. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61684. };
  61685. this._checkVersionFromDB(completeUrl, function (version) {
  61686. if (version !== -1) {
  61687. if (!_this.mustUpdateRessources) {
  61688. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61689. }
  61690. else {
  61691. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61692. }
  61693. }
  61694. else {
  61695. if (errorCallback) {
  61696. errorCallback();
  61697. }
  61698. }
  61699. });
  61700. };
  61701. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61702. if (this.isSupported && this.db) {
  61703. var targetStore;
  61704. if (url.indexOf(".babylon") !== -1) {
  61705. targetStore = "scenes";
  61706. }
  61707. else {
  61708. targetStore = "textures";
  61709. }
  61710. var file;
  61711. var transaction = this.db.transaction([targetStore]);
  61712. transaction.oncomplete = function (event) {
  61713. if (file) {
  61714. callback(file.data);
  61715. }
  61716. else {
  61717. notInDBCallback();
  61718. }
  61719. };
  61720. transaction.onabort = function (event) {
  61721. notInDBCallback();
  61722. };
  61723. var getRequest = transaction.objectStore(targetStore).get(url);
  61724. getRequest.onsuccess = function (event) {
  61725. file = (event.target).result;
  61726. };
  61727. getRequest.onerror = function (event) {
  61728. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61729. notInDBCallback();
  61730. };
  61731. }
  61732. else {
  61733. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61734. callback();
  61735. }
  61736. };
  61737. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61738. var _this = this;
  61739. if (this.isSupported) {
  61740. var targetStore;
  61741. if (url.indexOf(".babylon") !== -1) {
  61742. targetStore = "scenes";
  61743. }
  61744. else {
  61745. targetStore = "textures";
  61746. }
  61747. // Create XHR
  61748. var xhr = new XMLHttpRequest();
  61749. var fileData;
  61750. xhr.open("GET", url, true);
  61751. if (useArrayBuffer) {
  61752. xhr.responseType = "arraybuffer";
  61753. }
  61754. if (progressCallback) {
  61755. xhr.onprogress = progressCallback;
  61756. }
  61757. xhr.addEventListener("load", function () {
  61758. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61759. // Blob as response (XHR2)
  61760. //fileData = xhr.responseText;
  61761. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61762. if (!_this.hasReachedQuota && _this.db) {
  61763. // Open a transaction to the database
  61764. var transaction = _this.db.transaction([targetStore], "readwrite");
  61765. // the transaction could abort because of a QuotaExceededError error
  61766. transaction.onabort = function (event) {
  61767. try {
  61768. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61769. var error = event.srcElement['error'];
  61770. if (error && error.name === "QuotaExceededError") {
  61771. _this.hasReachedQuota = true;
  61772. }
  61773. }
  61774. catch (ex) { }
  61775. callback(fileData);
  61776. };
  61777. transaction.oncomplete = function (event) {
  61778. callback(fileData);
  61779. };
  61780. var newFile;
  61781. if (targetStore === "scenes") {
  61782. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61783. }
  61784. else {
  61785. newFile = { textureUrl: url, data: fileData };
  61786. }
  61787. try {
  61788. // Put the scene into the database
  61789. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61790. addRequest.onsuccess = function (event) {
  61791. };
  61792. addRequest.onerror = function (event) {
  61793. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61794. };
  61795. }
  61796. catch (ex) {
  61797. callback(fileData);
  61798. }
  61799. }
  61800. else {
  61801. callback(fileData);
  61802. }
  61803. }
  61804. else {
  61805. callback();
  61806. }
  61807. }, false);
  61808. xhr.addEventListener("error", function (event) {
  61809. BABYLON.Tools.Error("error on XHR request.");
  61810. callback();
  61811. }, false);
  61812. xhr.send();
  61813. }
  61814. else {
  61815. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61816. callback();
  61817. }
  61818. };
  61819. Database.IsUASupportingBlobStorage = true;
  61820. Database.IDBStorageEnabled = true;
  61821. Database.parseURL = function (url) {
  61822. var a = document.createElement('a');
  61823. a.href = url;
  61824. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61825. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61826. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61827. return absLocation;
  61828. };
  61829. Database.ReturnFullUrlLocation = function (url) {
  61830. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61831. return (Database.parseURL(window.location.href) + url);
  61832. }
  61833. else {
  61834. return url;
  61835. }
  61836. };
  61837. return Database;
  61838. }());
  61839. BABYLON.Database = Database;
  61840. })(BABYLON || (BABYLON = {}));
  61841. //# sourceMappingURL=babylon.database.js.map
  61842. var BABYLON;
  61843. (function (BABYLON) {
  61844. var FresnelParameters = /** @class */ (function () {
  61845. function FresnelParameters() {
  61846. this._isEnabled = true;
  61847. this.leftColor = BABYLON.Color3.White();
  61848. this.rightColor = BABYLON.Color3.Black();
  61849. this.bias = 0;
  61850. this.power = 1;
  61851. }
  61852. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61853. get: function () {
  61854. return this._isEnabled;
  61855. },
  61856. set: function (value) {
  61857. if (this._isEnabled === value) {
  61858. return;
  61859. }
  61860. this._isEnabled = value;
  61861. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61862. },
  61863. enumerable: true,
  61864. configurable: true
  61865. });
  61866. FresnelParameters.prototype.clone = function () {
  61867. var newFresnelParameters = new FresnelParameters();
  61868. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61869. return newFresnelParameters;
  61870. };
  61871. FresnelParameters.prototype.serialize = function () {
  61872. var serializationObject = {};
  61873. serializationObject.isEnabled = this.isEnabled;
  61874. serializationObject.leftColor = this.leftColor;
  61875. serializationObject.rightColor = this.rightColor;
  61876. serializationObject.bias = this.bias;
  61877. serializationObject.power = this.power;
  61878. return serializationObject;
  61879. };
  61880. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61881. var fresnelParameters = new FresnelParameters();
  61882. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61883. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61884. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61885. fresnelParameters.bias = parsedFresnelParameters.bias;
  61886. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61887. return fresnelParameters;
  61888. };
  61889. return FresnelParameters;
  61890. }());
  61891. BABYLON.FresnelParameters = FresnelParameters;
  61892. })(BABYLON || (BABYLON = {}));
  61893. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61894. var BABYLON;
  61895. (function (BABYLON) {
  61896. var MultiMaterial = /** @class */ (function (_super) {
  61897. __extends(MultiMaterial, _super);
  61898. function MultiMaterial(name, scene) {
  61899. var _this = _super.call(this, name, scene, true) || this;
  61900. scene.multiMaterials.push(_this);
  61901. _this.subMaterials = new Array();
  61902. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61903. return _this;
  61904. }
  61905. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61906. get: function () {
  61907. return this._subMaterials;
  61908. },
  61909. set: function (value) {
  61910. this._subMaterials = value;
  61911. this._hookArray(value);
  61912. },
  61913. enumerable: true,
  61914. configurable: true
  61915. });
  61916. MultiMaterial.prototype._hookArray = function (array) {
  61917. var _this = this;
  61918. var oldPush = array.push;
  61919. array.push = function () {
  61920. var items = [];
  61921. for (var _i = 0; _i < arguments.length; _i++) {
  61922. items[_i] = arguments[_i];
  61923. }
  61924. var result = oldPush.apply(array, items);
  61925. _this._markAllSubMeshesAsTexturesDirty();
  61926. return result;
  61927. };
  61928. var oldSplice = array.splice;
  61929. array.splice = function (index, deleteCount) {
  61930. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61931. _this._markAllSubMeshesAsTexturesDirty();
  61932. return deleted;
  61933. };
  61934. };
  61935. // Properties
  61936. MultiMaterial.prototype.getSubMaterial = function (index) {
  61937. if (index < 0 || index >= this.subMaterials.length) {
  61938. return this.getScene().defaultMaterial;
  61939. }
  61940. return this.subMaterials[index];
  61941. };
  61942. MultiMaterial.prototype.getActiveTextures = function () {
  61943. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61944. if (subMaterial) {
  61945. return subMaterial.getActiveTextures();
  61946. }
  61947. else {
  61948. return [];
  61949. }
  61950. }));
  61951. var _a;
  61952. };
  61953. // Methods
  61954. MultiMaterial.prototype.getClassName = function () {
  61955. return "MultiMaterial";
  61956. };
  61957. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61958. for (var index = 0; index < this.subMaterials.length; index++) {
  61959. var subMaterial = this.subMaterials[index];
  61960. if (subMaterial) {
  61961. if (subMaterial.storeEffectOnSubMeshes) {
  61962. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61963. return false;
  61964. }
  61965. continue;
  61966. }
  61967. if (!subMaterial.isReady(mesh)) {
  61968. return false;
  61969. }
  61970. }
  61971. }
  61972. return true;
  61973. };
  61974. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61975. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61976. for (var index = 0; index < this.subMaterials.length; index++) {
  61977. var subMaterial = null;
  61978. var current = this.subMaterials[index];
  61979. if (cloneChildren && current) {
  61980. subMaterial = current.clone(name + "-" + current.name);
  61981. }
  61982. else {
  61983. subMaterial = this.subMaterials[index];
  61984. }
  61985. newMultiMaterial.subMaterials.push(subMaterial);
  61986. }
  61987. return newMultiMaterial;
  61988. };
  61989. MultiMaterial.prototype.serialize = function () {
  61990. var serializationObject = {};
  61991. serializationObject.name = this.name;
  61992. serializationObject.id = this.id;
  61993. if (BABYLON.Tags) {
  61994. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61995. }
  61996. serializationObject.materials = [];
  61997. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61998. var subMat = this.subMaterials[matIndex];
  61999. if (subMat) {
  62000. serializationObject.materials.push(subMat.id);
  62001. }
  62002. else {
  62003. serializationObject.materials.push(null);
  62004. }
  62005. }
  62006. return serializationObject;
  62007. };
  62008. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62009. var scene = this.getScene();
  62010. if (!scene) {
  62011. return;
  62012. }
  62013. var index = scene.multiMaterials.indexOf(this);
  62014. if (index >= 0) {
  62015. scene.multiMaterials.splice(index, 1);
  62016. }
  62017. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62018. };
  62019. return MultiMaterial;
  62020. }(BABYLON.Material));
  62021. BABYLON.MultiMaterial = MultiMaterial;
  62022. })(BABYLON || (BABYLON = {}));
  62023. //# sourceMappingURL=babylon.multiMaterial.js.map
  62024. var BABYLON;
  62025. (function (BABYLON) {
  62026. var FreeCameraTouchInput = /** @class */ (function () {
  62027. function FreeCameraTouchInput() {
  62028. this._offsetX = null;
  62029. this._offsetY = null;
  62030. this._pointerPressed = new Array();
  62031. this.touchAngularSensibility = 200000.0;
  62032. this.touchMoveSensibility = 250.0;
  62033. }
  62034. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62035. var _this = this;
  62036. var previousPosition = null;
  62037. if (this._pointerInput === undefined) {
  62038. this._onLostFocus = function (evt) {
  62039. _this._offsetX = null;
  62040. _this._offsetY = null;
  62041. };
  62042. this._pointerInput = function (p, s) {
  62043. var evt = p.event;
  62044. if (evt.pointerType === "mouse") {
  62045. return;
  62046. }
  62047. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62048. if (!noPreventDefault) {
  62049. evt.preventDefault();
  62050. }
  62051. _this._pointerPressed.push(evt.pointerId);
  62052. if (_this._pointerPressed.length !== 1) {
  62053. return;
  62054. }
  62055. previousPosition = {
  62056. x: evt.clientX,
  62057. y: evt.clientY
  62058. };
  62059. }
  62060. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62061. if (!noPreventDefault) {
  62062. evt.preventDefault();
  62063. }
  62064. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62065. if (index === -1) {
  62066. return;
  62067. }
  62068. _this._pointerPressed.splice(index, 1);
  62069. if (index != 0) {
  62070. return;
  62071. }
  62072. previousPosition = null;
  62073. _this._offsetX = null;
  62074. _this._offsetY = null;
  62075. }
  62076. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62077. if (!noPreventDefault) {
  62078. evt.preventDefault();
  62079. }
  62080. if (!previousPosition) {
  62081. return;
  62082. }
  62083. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62084. if (index != 0) {
  62085. return;
  62086. }
  62087. _this._offsetX = evt.clientX - previousPosition.x;
  62088. _this._offsetY = -(evt.clientY - previousPosition.y);
  62089. }
  62090. };
  62091. }
  62092. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62093. if (this._onLostFocus) {
  62094. element.addEventListener("blur", this._onLostFocus);
  62095. }
  62096. };
  62097. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62098. if (this._pointerInput && element) {
  62099. if (this._observer) {
  62100. this.camera.getScene().onPointerObservable.remove(this._observer);
  62101. this._observer = null;
  62102. }
  62103. if (this._onLostFocus) {
  62104. element.removeEventListener("blur", this._onLostFocus);
  62105. this._onLostFocus = null;
  62106. }
  62107. this._pointerPressed = [];
  62108. this._offsetX = null;
  62109. this._offsetY = null;
  62110. }
  62111. };
  62112. FreeCameraTouchInput.prototype.checkInputs = function () {
  62113. if (this._offsetX && this._offsetY) {
  62114. var camera = this.camera;
  62115. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62116. if (this._pointerPressed.length > 1) {
  62117. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62118. }
  62119. else {
  62120. var speed = camera._computeLocalCameraSpeed();
  62121. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62122. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62123. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62124. }
  62125. }
  62126. };
  62127. FreeCameraTouchInput.prototype.getClassName = function () {
  62128. return "FreeCameraTouchInput";
  62129. };
  62130. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62131. return "touch";
  62132. };
  62133. __decorate([
  62134. BABYLON.serialize()
  62135. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62136. __decorate([
  62137. BABYLON.serialize()
  62138. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62139. return FreeCameraTouchInput;
  62140. }());
  62141. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62142. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62143. })(BABYLON || (BABYLON = {}));
  62144. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62145. var BABYLON;
  62146. (function (BABYLON) {
  62147. // We're mainly based on the logic defined into the FreeCamera code
  62148. var TouchCamera = /** @class */ (function (_super) {
  62149. __extends(TouchCamera, _super);
  62150. //-- end properties for backward compatibility for inputs
  62151. function TouchCamera(name, position, scene) {
  62152. var _this = _super.call(this, name, position, scene) || this;
  62153. _this.inputs.addTouch();
  62154. _this._setupInputs();
  62155. return _this;
  62156. }
  62157. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62158. //-- Begin properties for backward compatibility for inputs
  62159. get: function () {
  62160. var touch = this.inputs.attached["touch"];
  62161. if (touch)
  62162. return touch.touchAngularSensibility;
  62163. return 0;
  62164. },
  62165. set: function (value) {
  62166. var touch = this.inputs.attached["touch"];
  62167. if (touch)
  62168. touch.touchAngularSensibility = value;
  62169. },
  62170. enumerable: true,
  62171. configurable: true
  62172. });
  62173. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62174. get: function () {
  62175. var touch = this.inputs.attached["touch"];
  62176. if (touch)
  62177. return touch.touchMoveSensibility;
  62178. return 0;
  62179. },
  62180. set: function (value) {
  62181. var touch = this.inputs.attached["touch"];
  62182. if (touch)
  62183. touch.touchMoveSensibility = value;
  62184. },
  62185. enumerable: true,
  62186. configurable: true
  62187. });
  62188. TouchCamera.prototype.getClassName = function () {
  62189. return "TouchCamera";
  62190. };
  62191. TouchCamera.prototype._setupInputs = function () {
  62192. var mouse = this.inputs.attached["mouse"];
  62193. if (mouse) {
  62194. mouse.touchEnabled = false;
  62195. }
  62196. };
  62197. return TouchCamera;
  62198. }(BABYLON.FreeCamera));
  62199. BABYLON.TouchCamera = TouchCamera;
  62200. })(BABYLON || (BABYLON = {}));
  62201. //# sourceMappingURL=babylon.touchCamera.js.map
  62202. var BABYLON;
  62203. (function (BABYLON) {
  62204. var ProceduralTexture = /** @class */ (function (_super) {
  62205. __extends(ProceduralTexture, _super);
  62206. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62207. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62208. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62209. if (isCube === void 0) { isCube = false; }
  62210. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62211. _this.isCube = isCube;
  62212. _this.isEnabled = true;
  62213. _this._currentRefreshId = -1;
  62214. _this._refreshRate = 1;
  62215. _this._vertexBuffers = {};
  62216. _this._uniforms = new Array();
  62217. _this._samplers = new Array();
  62218. _this._textures = {};
  62219. _this._floats = {};
  62220. _this._floatsArrays = {};
  62221. _this._colors3 = {};
  62222. _this._colors4 = {};
  62223. _this._vectors2 = {};
  62224. _this._vectors3 = {};
  62225. _this._matrices = {};
  62226. _this._fallbackTextureUsed = false;
  62227. scene._proceduralTextures.push(_this);
  62228. _this._engine = scene.getEngine();
  62229. _this.name = name;
  62230. _this.isRenderTarget = true;
  62231. _this._size = size;
  62232. _this._generateMipMaps = generateMipMaps;
  62233. _this.setFragment(fragment);
  62234. _this._fallbackTexture = fallbackTexture;
  62235. if (isCube) {
  62236. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62237. _this.setFloat("face", 0);
  62238. }
  62239. else {
  62240. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62241. }
  62242. // VBO
  62243. var vertices = [];
  62244. vertices.push(1, 1);
  62245. vertices.push(-1, 1);
  62246. vertices.push(-1, -1);
  62247. vertices.push(1, -1);
  62248. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62249. _this._createIndexBuffer();
  62250. return _this;
  62251. }
  62252. ProceduralTexture.prototype._createIndexBuffer = function () {
  62253. var engine = this._engine;
  62254. // Indices
  62255. var indices = [];
  62256. indices.push(0);
  62257. indices.push(1);
  62258. indices.push(2);
  62259. indices.push(0);
  62260. indices.push(2);
  62261. indices.push(3);
  62262. this._indexBuffer = engine.createIndexBuffer(indices);
  62263. };
  62264. ProceduralTexture.prototype._rebuild = function () {
  62265. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62266. if (vb) {
  62267. vb._rebuild();
  62268. }
  62269. this._createIndexBuffer();
  62270. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62271. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62272. }
  62273. };
  62274. ProceduralTexture.prototype.reset = function () {
  62275. if (this._effect === undefined) {
  62276. return;
  62277. }
  62278. var engine = this._engine;
  62279. engine._releaseEffect(this._effect);
  62280. };
  62281. ProceduralTexture.prototype.isReady = function () {
  62282. var _this = this;
  62283. var engine = this._engine;
  62284. var shaders;
  62285. if (!this._fragment) {
  62286. return false;
  62287. }
  62288. if (this._fallbackTextureUsed) {
  62289. return true;
  62290. }
  62291. if (this._fragment.fragmentElement !== undefined) {
  62292. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62293. }
  62294. else {
  62295. shaders = { vertex: "procedural", fragment: this._fragment };
  62296. }
  62297. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62298. _this.releaseInternalTexture();
  62299. if (_this._fallbackTexture) {
  62300. _this._texture = _this._fallbackTexture._texture;
  62301. if (_this._texture) {
  62302. _this._texture.incrementReferences();
  62303. }
  62304. }
  62305. _this._fallbackTextureUsed = true;
  62306. });
  62307. return this._effect.isReady();
  62308. };
  62309. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62310. this._currentRefreshId = -1;
  62311. };
  62312. ProceduralTexture.prototype.setFragment = function (fragment) {
  62313. this._fragment = fragment;
  62314. };
  62315. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62316. get: function () {
  62317. return this._refreshRate;
  62318. },
  62319. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62320. set: function (value) {
  62321. this._refreshRate = value;
  62322. this.resetRefreshCounter();
  62323. },
  62324. enumerable: true,
  62325. configurable: true
  62326. });
  62327. ProceduralTexture.prototype._shouldRender = function () {
  62328. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62329. return false;
  62330. }
  62331. if (this._fallbackTextureUsed) {
  62332. return false;
  62333. }
  62334. if (this._currentRefreshId === -1) {
  62335. this._currentRefreshId = 1;
  62336. return true;
  62337. }
  62338. if (this.refreshRate === this._currentRefreshId) {
  62339. this._currentRefreshId = 1;
  62340. return true;
  62341. }
  62342. this._currentRefreshId++;
  62343. return false;
  62344. };
  62345. ProceduralTexture.prototype.getRenderSize = function () {
  62346. return this._size;
  62347. };
  62348. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62349. if (this._fallbackTextureUsed) {
  62350. return;
  62351. }
  62352. this.releaseInternalTexture();
  62353. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62354. };
  62355. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62356. if (this._uniforms.indexOf(uniformName) === -1) {
  62357. this._uniforms.push(uniformName);
  62358. }
  62359. };
  62360. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62361. if (this._samplers.indexOf(name) === -1) {
  62362. this._samplers.push(name);
  62363. }
  62364. this._textures[name] = texture;
  62365. return this;
  62366. };
  62367. ProceduralTexture.prototype.setFloat = function (name, value) {
  62368. this._checkUniform(name);
  62369. this._floats[name] = value;
  62370. return this;
  62371. };
  62372. ProceduralTexture.prototype.setFloats = function (name, value) {
  62373. this._checkUniform(name);
  62374. this._floatsArrays[name] = value;
  62375. return this;
  62376. };
  62377. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62378. this._checkUniform(name);
  62379. this._colors3[name] = value;
  62380. return this;
  62381. };
  62382. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62383. this._checkUniform(name);
  62384. this._colors4[name] = value;
  62385. return this;
  62386. };
  62387. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62388. this._checkUniform(name);
  62389. this._vectors2[name] = value;
  62390. return this;
  62391. };
  62392. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62393. this._checkUniform(name);
  62394. this._vectors3[name] = value;
  62395. return this;
  62396. };
  62397. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62398. this._checkUniform(name);
  62399. this._matrices[name] = value;
  62400. return this;
  62401. };
  62402. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62403. var scene = this.getScene();
  62404. if (!scene) {
  62405. return;
  62406. }
  62407. var engine = this._engine;
  62408. // Render
  62409. engine.enableEffect(this._effect);
  62410. engine.setState(false);
  62411. // Texture
  62412. for (var name in this._textures) {
  62413. this._effect.setTexture(name, this._textures[name]);
  62414. }
  62415. // Float
  62416. for (name in this._floats) {
  62417. this._effect.setFloat(name, this._floats[name]);
  62418. }
  62419. // Floats
  62420. for (name in this._floatsArrays) {
  62421. this._effect.setArray(name, this._floatsArrays[name]);
  62422. }
  62423. // Color3
  62424. for (name in this._colors3) {
  62425. this._effect.setColor3(name, this._colors3[name]);
  62426. }
  62427. // Color4
  62428. for (name in this._colors4) {
  62429. var color = this._colors4[name];
  62430. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62431. }
  62432. // Vector2
  62433. for (name in this._vectors2) {
  62434. this._effect.setVector2(name, this._vectors2[name]);
  62435. }
  62436. // Vector3
  62437. for (name in this._vectors3) {
  62438. this._effect.setVector3(name, this._vectors3[name]);
  62439. }
  62440. // Matrix
  62441. for (name in this._matrices) {
  62442. this._effect.setMatrix(name, this._matrices[name]);
  62443. }
  62444. if (!this._texture) {
  62445. return;
  62446. }
  62447. if (this.isCube) {
  62448. for (var face = 0; face < 6; face++) {
  62449. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62450. // VBOs
  62451. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62452. this._effect.setFloat("face", face);
  62453. // Clear
  62454. engine.clear(scene.clearColor, true, true, true);
  62455. // Draw order
  62456. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62457. // Mipmaps
  62458. if (face === 5) {
  62459. engine.generateMipMapsForCubemap(this._texture);
  62460. }
  62461. }
  62462. }
  62463. else {
  62464. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62465. // VBOs
  62466. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62467. // Clear
  62468. engine.clear(scene.clearColor, true, true, true);
  62469. // Draw order
  62470. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62471. }
  62472. // Unbind
  62473. engine.unBindFramebuffer(this._texture, this.isCube);
  62474. if (this.onGenerated) {
  62475. this.onGenerated();
  62476. }
  62477. };
  62478. ProceduralTexture.prototype.clone = function () {
  62479. var textureSize = this.getSize();
  62480. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62481. // Base texture
  62482. newTexture.hasAlpha = this.hasAlpha;
  62483. newTexture.level = this.level;
  62484. // RenderTarget Texture
  62485. newTexture.coordinatesMode = this.coordinatesMode;
  62486. return newTexture;
  62487. };
  62488. ProceduralTexture.prototype.dispose = function () {
  62489. var scene = this.getScene();
  62490. if (!scene) {
  62491. return;
  62492. }
  62493. var index = scene._proceduralTextures.indexOf(this);
  62494. if (index >= 0) {
  62495. scene._proceduralTextures.splice(index, 1);
  62496. }
  62497. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62498. if (vertexBuffer) {
  62499. vertexBuffer.dispose();
  62500. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62501. }
  62502. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62503. this._indexBuffer = null;
  62504. }
  62505. _super.prototype.dispose.call(this);
  62506. };
  62507. return ProceduralTexture;
  62508. }(BABYLON.Texture));
  62509. BABYLON.ProceduralTexture = ProceduralTexture;
  62510. })(BABYLON || (BABYLON = {}));
  62511. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62512. var BABYLON;
  62513. (function (BABYLON) {
  62514. var CustomProceduralTexture = /** @class */ (function (_super) {
  62515. __extends(CustomProceduralTexture, _super);
  62516. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62517. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62518. _this._animate = true;
  62519. _this._time = 0;
  62520. _this._texturePath = texturePath;
  62521. //Try to load json
  62522. _this.loadJson(texturePath);
  62523. _this.refreshRate = 1;
  62524. return _this;
  62525. }
  62526. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62527. var _this = this;
  62528. var noConfigFile = function () {
  62529. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62530. try {
  62531. _this.setFragment(_this._texturePath);
  62532. }
  62533. catch (ex) {
  62534. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62535. }
  62536. };
  62537. var configFileUrl = jsonUrl + "/config.json";
  62538. var xhr = new XMLHttpRequest();
  62539. xhr.open("GET", configFileUrl, true);
  62540. xhr.addEventListener("load", function () {
  62541. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62542. try {
  62543. _this._config = JSON.parse(xhr.response);
  62544. _this.updateShaderUniforms();
  62545. _this.updateTextures();
  62546. _this.setFragment(_this._texturePath + "/custom");
  62547. _this._animate = _this._config.animate;
  62548. _this.refreshRate = _this._config.refreshrate;
  62549. }
  62550. catch (ex) {
  62551. noConfigFile();
  62552. }
  62553. }
  62554. else {
  62555. noConfigFile();
  62556. }
  62557. }, false);
  62558. xhr.addEventListener("error", function () {
  62559. noConfigFile();
  62560. }, false);
  62561. try {
  62562. xhr.send();
  62563. }
  62564. catch (ex) {
  62565. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62566. }
  62567. };
  62568. CustomProceduralTexture.prototype.isReady = function () {
  62569. if (!_super.prototype.isReady.call(this)) {
  62570. return false;
  62571. }
  62572. for (var name in this._textures) {
  62573. var texture = this._textures[name];
  62574. if (!texture.isReady()) {
  62575. return false;
  62576. }
  62577. }
  62578. return true;
  62579. };
  62580. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62581. var scene = this.getScene();
  62582. if (this._animate && scene) {
  62583. this._time += scene.getAnimationRatio() * 0.03;
  62584. this.updateShaderUniforms();
  62585. }
  62586. _super.prototype.render.call(this, useCameraPostProcess);
  62587. };
  62588. CustomProceduralTexture.prototype.updateTextures = function () {
  62589. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62590. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62591. }
  62592. };
  62593. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62594. if (this._config) {
  62595. for (var j = 0; j < this._config.uniforms.length; j++) {
  62596. var uniform = this._config.uniforms[j];
  62597. switch (uniform.type) {
  62598. case "float":
  62599. this.setFloat(uniform.name, uniform.value);
  62600. break;
  62601. case "color3":
  62602. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62603. break;
  62604. case "color4":
  62605. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62606. break;
  62607. case "vector2":
  62608. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62609. break;
  62610. case "vector3":
  62611. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62612. break;
  62613. }
  62614. }
  62615. }
  62616. this.setFloat("time", this._time);
  62617. };
  62618. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62619. get: function () {
  62620. return this._animate;
  62621. },
  62622. set: function (value) {
  62623. this._animate = value;
  62624. },
  62625. enumerable: true,
  62626. configurable: true
  62627. });
  62628. return CustomProceduralTexture;
  62629. }(BABYLON.ProceduralTexture));
  62630. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62631. })(BABYLON || (BABYLON = {}));
  62632. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62633. var BABYLON;
  62634. (function (BABYLON) {
  62635. var FreeCameraGamepadInput = /** @class */ (function () {
  62636. function FreeCameraGamepadInput() {
  62637. this.gamepadAngularSensibility = 200;
  62638. this.gamepadMoveSensibility = 40;
  62639. // private members
  62640. this._cameraTransform = BABYLON.Matrix.Identity();
  62641. this._deltaTransform = BABYLON.Vector3.Zero();
  62642. this._vector3 = BABYLON.Vector3.Zero();
  62643. this._vector2 = BABYLON.Vector2.Zero();
  62644. }
  62645. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62646. var _this = this;
  62647. var manager = this.camera.getScene().gamepadManager;
  62648. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62649. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62650. // prioritize XBOX gamepads.
  62651. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62652. _this.gamepad = gamepad;
  62653. }
  62654. }
  62655. });
  62656. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62657. if (_this.gamepad === gamepad) {
  62658. _this.gamepad = null;
  62659. }
  62660. });
  62661. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62662. };
  62663. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62664. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62665. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62666. this.gamepad = null;
  62667. };
  62668. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62669. if (this.gamepad && this.gamepad.leftStick) {
  62670. var camera = this.camera;
  62671. var LSValues = this.gamepad.leftStick;
  62672. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62673. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62674. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62675. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62676. var RSValues = this.gamepad.rightStick;
  62677. if (RSValues) {
  62678. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62679. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62680. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62681. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62682. }
  62683. else {
  62684. RSValues = { x: 0, y: 0 };
  62685. }
  62686. if (!camera.rotationQuaternion) {
  62687. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62688. }
  62689. else {
  62690. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62691. }
  62692. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62693. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62694. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62695. camera.cameraDirection.addInPlace(this._deltaTransform);
  62696. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62697. camera.cameraRotation.addInPlace(this._vector2);
  62698. }
  62699. };
  62700. FreeCameraGamepadInput.prototype.getClassName = function () {
  62701. return "FreeCameraGamepadInput";
  62702. };
  62703. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62704. return "gamepad";
  62705. };
  62706. __decorate([
  62707. BABYLON.serialize()
  62708. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62709. __decorate([
  62710. BABYLON.serialize()
  62711. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62712. return FreeCameraGamepadInput;
  62713. }());
  62714. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62715. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62716. })(BABYLON || (BABYLON = {}));
  62717. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62718. var BABYLON;
  62719. (function (BABYLON) {
  62720. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62721. function ArcRotateCameraGamepadInput() {
  62722. this.gamepadRotationSensibility = 80;
  62723. this.gamepadMoveSensibility = 40;
  62724. }
  62725. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62726. var _this = this;
  62727. var manager = this.camera.getScene().gamepadManager;
  62728. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62729. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62730. // prioritize XBOX gamepads.
  62731. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62732. _this.gamepad = gamepad;
  62733. }
  62734. }
  62735. });
  62736. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62737. if (_this.gamepad === gamepad) {
  62738. _this.gamepad = null;
  62739. }
  62740. });
  62741. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62742. };
  62743. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62744. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62745. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62746. this.gamepad = null;
  62747. };
  62748. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62749. if (this.gamepad) {
  62750. var camera = this.camera;
  62751. var RSValues = this.gamepad.rightStick;
  62752. if (RSValues) {
  62753. if (RSValues.x != 0) {
  62754. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62755. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62756. camera.inertialAlphaOffset += normalizedRX;
  62757. }
  62758. }
  62759. if (RSValues.y != 0) {
  62760. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62761. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62762. camera.inertialBetaOffset += normalizedRY;
  62763. }
  62764. }
  62765. }
  62766. var LSValues = this.gamepad.leftStick;
  62767. if (LSValues && LSValues.y != 0) {
  62768. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62769. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62770. this.camera.inertialRadiusOffset -= normalizedLY;
  62771. }
  62772. }
  62773. }
  62774. };
  62775. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62776. return "ArcRotateCameraGamepadInput";
  62777. };
  62778. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62779. return "gamepad";
  62780. };
  62781. __decorate([
  62782. BABYLON.serialize()
  62783. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62784. __decorate([
  62785. BABYLON.serialize()
  62786. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62787. return ArcRotateCameraGamepadInput;
  62788. }());
  62789. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62790. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62791. })(BABYLON || (BABYLON = {}));
  62792. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62793. var BABYLON;
  62794. (function (BABYLON) {
  62795. var GamepadManager = /** @class */ (function () {
  62796. function GamepadManager(_scene) {
  62797. var _this = this;
  62798. this._scene = _scene;
  62799. this._babylonGamepads = [];
  62800. this._oneGamepadConnected = false;
  62801. this._isMonitoring = false;
  62802. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62803. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62804. this._gamepadEventSupported = false;
  62805. }
  62806. else {
  62807. this._gamepadEventSupported = 'GamepadEvent' in window;
  62808. this._gamepadSupport = (navigator.getGamepads ||
  62809. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62810. }
  62811. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62812. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62813. for (var i in _this._babylonGamepads) {
  62814. var gamepad = _this._babylonGamepads[i];
  62815. if (gamepad && gamepad._isConnected) {
  62816. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62817. }
  62818. }
  62819. });
  62820. this._onGamepadConnectedEvent = function (evt) {
  62821. var gamepad = evt.gamepad;
  62822. if (gamepad.index in _this._babylonGamepads) {
  62823. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62824. return;
  62825. }
  62826. }
  62827. var newGamepad;
  62828. if (_this._babylonGamepads[gamepad.index]) {
  62829. newGamepad = _this._babylonGamepads[gamepad.index];
  62830. newGamepad.browserGamepad = gamepad;
  62831. newGamepad._isConnected = true;
  62832. }
  62833. else {
  62834. newGamepad = _this._addNewGamepad(gamepad);
  62835. }
  62836. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62837. _this._startMonitoringGamepads();
  62838. };
  62839. this._onGamepadDisconnectedEvent = function (evt) {
  62840. var gamepad = evt.gamepad;
  62841. // Remove the gamepad from the list of gamepads to monitor.
  62842. for (var i in _this._babylonGamepads) {
  62843. if (_this._babylonGamepads[i].index === gamepad.index) {
  62844. var disconnectedGamepad = _this._babylonGamepads[i];
  62845. disconnectedGamepad._isConnected = false;
  62846. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62847. break;
  62848. }
  62849. }
  62850. };
  62851. if (this._gamepadSupport) {
  62852. //first add already-connected gamepads
  62853. this._updateGamepadObjects();
  62854. if (this._babylonGamepads.length) {
  62855. this._startMonitoringGamepads();
  62856. }
  62857. // Checking if the gamepad connected event is supported (like in Firefox)
  62858. if (this._gamepadEventSupported) {
  62859. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62860. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62861. }
  62862. else {
  62863. this._startMonitoringGamepads();
  62864. }
  62865. }
  62866. }
  62867. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62868. get: function () {
  62869. return this._babylonGamepads;
  62870. },
  62871. enumerable: true,
  62872. configurable: true
  62873. });
  62874. GamepadManager.prototype.getGamepadByType = function (type) {
  62875. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62876. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62877. var gamepad = _a[_i];
  62878. if (gamepad && gamepad.type === type) {
  62879. return gamepad;
  62880. }
  62881. }
  62882. return null;
  62883. };
  62884. GamepadManager.prototype.dispose = function () {
  62885. if (this._gamepadEventSupported) {
  62886. if (this._onGamepadConnectedEvent) {
  62887. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62888. }
  62889. if (this._onGamepadDisconnectedEvent) {
  62890. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62891. }
  62892. this._onGamepadConnectedEvent = null;
  62893. this._onGamepadDisconnectedEvent = null;
  62894. }
  62895. this._babylonGamepads.forEach(function (gamepad) {
  62896. gamepad.dispose();
  62897. });
  62898. this.onGamepadConnectedObservable.clear();
  62899. this.onGamepadDisconnectedObservable.clear();
  62900. this._oneGamepadConnected = false;
  62901. this._stopMonitoringGamepads();
  62902. this._babylonGamepads = [];
  62903. };
  62904. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62905. if (!this._oneGamepadConnected) {
  62906. this._oneGamepadConnected = true;
  62907. }
  62908. var newGamepad;
  62909. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62910. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62911. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62912. }
  62913. else if (gamepad.pose) {
  62914. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62915. }
  62916. else {
  62917. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62918. }
  62919. this._babylonGamepads[newGamepad.index] = newGamepad;
  62920. return newGamepad;
  62921. };
  62922. GamepadManager.prototype._startMonitoringGamepads = function () {
  62923. if (!this._isMonitoring) {
  62924. this._isMonitoring = true;
  62925. //back-comp
  62926. if (!this._scene) {
  62927. this._checkGamepadsStatus();
  62928. }
  62929. }
  62930. };
  62931. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62932. this._isMonitoring = false;
  62933. };
  62934. GamepadManager.prototype._checkGamepadsStatus = function () {
  62935. var _this = this;
  62936. // Hack to be compatible Chrome
  62937. this._updateGamepadObjects();
  62938. for (var i in this._babylonGamepads) {
  62939. var gamepad = this._babylonGamepads[i];
  62940. if (!gamepad || !gamepad.isConnected) {
  62941. continue;
  62942. }
  62943. gamepad.update();
  62944. }
  62945. if (this._isMonitoring && !this._scene) {
  62946. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62947. }
  62948. };
  62949. // This function is called only on Chrome, which does not properly support
  62950. // connection/disconnection events and forces you to recopy again the gamepad object
  62951. GamepadManager.prototype._updateGamepadObjects = function () {
  62952. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62953. for (var i = 0; i < gamepads.length; i++) {
  62954. if (gamepads[i]) {
  62955. if (!this._babylonGamepads[gamepads[i].index]) {
  62956. var newGamepad = this._addNewGamepad(gamepads[i]);
  62957. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62958. }
  62959. else {
  62960. // Forced to copy again this object for Chrome for unknown reason
  62961. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62962. if (!this._babylonGamepads[i].isConnected) {
  62963. this._babylonGamepads[i]._isConnected = true;
  62964. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62965. }
  62966. }
  62967. }
  62968. }
  62969. };
  62970. return GamepadManager;
  62971. }());
  62972. BABYLON.GamepadManager = GamepadManager;
  62973. })(BABYLON || (BABYLON = {}));
  62974. //# sourceMappingURL=babylon.gamepadManager.js.map
  62975. var BABYLON;
  62976. (function (BABYLON) {
  62977. var StickValues = /** @class */ (function () {
  62978. function StickValues(x, y) {
  62979. this.x = x;
  62980. this.y = y;
  62981. }
  62982. return StickValues;
  62983. }());
  62984. BABYLON.StickValues = StickValues;
  62985. var Gamepad = /** @class */ (function () {
  62986. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62987. if (leftStickX === void 0) { leftStickX = 0; }
  62988. if (leftStickY === void 0) { leftStickY = 1; }
  62989. if (rightStickX === void 0) { rightStickX = 2; }
  62990. if (rightStickY === void 0) { rightStickY = 3; }
  62991. this.id = id;
  62992. this.index = index;
  62993. this.browserGamepad = browserGamepad;
  62994. this._isConnected = true;
  62995. this._invertLeftStickY = false;
  62996. this.type = Gamepad.GAMEPAD;
  62997. this._leftStickAxisX = leftStickX;
  62998. this._leftStickAxisY = leftStickY;
  62999. this._rightStickAxisX = rightStickX;
  63000. this._rightStickAxisY = rightStickY;
  63001. if (this.browserGamepad.axes.length >= 2) {
  63002. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63003. }
  63004. if (this.browserGamepad.axes.length >= 4) {
  63005. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63006. }
  63007. }
  63008. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63009. get: function () {
  63010. return this._isConnected;
  63011. },
  63012. enumerable: true,
  63013. configurable: true
  63014. });
  63015. Gamepad.prototype.onleftstickchanged = function (callback) {
  63016. this._onleftstickchanged = callback;
  63017. };
  63018. Gamepad.prototype.onrightstickchanged = function (callback) {
  63019. this._onrightstickchanged = callback;
  63020. };
  63021. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63022. get: function () {
  63023. return this._leftStick;
  63024. },
  63025. set: function (newValues) {
  63026. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63027. this._onleftstickchanged(newValues);
  63028. }
  63029. this._leftStick = newValues;
  63030. },
  63031. enumerable: true,
  63032. configurable: true
  63033. });
  63034. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63035. get: function () {
  63036. return this._rightStick;
  63037. },
  63038. set: function (newValues) {
  63039. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63040. this._onrightstickchanged(newValues);
  63041. }
  63042. this._rightStick = newValues;
  63043. },
  63044. enumerable: true,
  63045. configurable: true
  63046. });
  63047. Gamepad.prototype.update = function () {
  63048. if (this._leftStick) {
  63049. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63050. if (this._invertLeftStickY) {
  63051. this.leftStick.y *= -1;
  63052. }
  63053. }
  63054. if (this._rightStick) {
  63055. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63056. }
  63057. };
  63058. Gamepad.prototype.dispose = function () {
  63059. };
  63060. Gamepad.GAMEPAD = 0;
  63061. Gamepad.GENERIC = 1;
  63062. Gamepad.XBOX = 2;
  63063. Gamepad.POSE_ENABLED = 3;
  63064. return Gamepad;
  63065. }());
  63066. BABYLON.Gamepad = Gamepad;
  63067. var GenericPad = /** @class */ (function (_super) {
  63068. __extends(GenericPad, _super);
  63069. function GenericPad(id, index, browserGamepad) {
  63070. var _this = _super.call(this, id, index, browserGamepad) || this;
  63071. _this.onButtonDownObservable = new BABYLON.Observable();
  63072. _this.onButtonUpObservable = new BABYLON.Observable();
  63073. _this.type = Gamepad.GENERIC;
  63074. _this._buttons = new Array(browserGamepad.buttons.length);
  63075. return _this;
  63076. }
  63077. GenericPad.prototype.onbuttondown = function (callback) {
  63078. this._onbuttondown = callback;
  63079. };
  63080. GenericPad.prototype.onbuttonup = function (callback) {
  63081. this._onbuttonup = callback;
  63082. };
  63083. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63084. if (newValue !== currentValue) {
  63085. if (newValue === 1) {
  63086. if (this._onbuttondown) {
  63087. this._onbuttondown(buttonIndex);
  63088. }
  63089. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63090. }
  63091. if (newValue === 0) {
  63092. if (this._onbuttonup) {
  63093. this._onbuttonup(buttonIndex);
  63094. }
  63095. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63096. }
  63097. }
  63098. return newValue;
  63099. };
  63100. GenericPad.prototype.update = function () {
  63101. _super.prototype.update.call(this);
  63102. for (var index = 0; index < this._buttons.length; index++) {
  63103. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63104. }
  63105. };
  63106. GenericPad.prototype.dispose = function () {
  63107. _super.prototype.dispose.call(this);
  63108. this.onButtonDownObservable.clear();
  63109. this.onButtonUpObservable.clear();
  63110. };
  63111. return GenericPad;
  63112. }(Gamepad));
  63113. BABYLON.GenericPad = GenericPad;
  63114. })(BABYLON || (BABYLON = {}));
  63115. //# sourceMappingURL=babylon.gamepad.js.map
  63116. var BABYLON;
  63117. (function (BABYLON) {
  63118. var Xbox360Button;
  63119. (function (Xbox360Button) {
  63120. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63121. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63122. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63123. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63124. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63125. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63126. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63127. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63128. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63129. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63130. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63131. var Xbox360Dpad;
  63132. (function (Xbox360Dpad) {
  63133. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63134. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63135. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63136. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63137. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63138. var Xbox360Pad = /** @class */ (function (_super) {
  63139. __extends(Xbox360Pad, _super);
  63140. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63141. if (xboxOne === void 0) { xboxOne = false; }
  63142. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63143. _this._leftTrigger = 0;
  63144. _this._rightTrigger = 0;
  63145. _this.onButtonDownObservable = new BABYLON.Observable();
  63146. _this.onButtonUpObservable = new BABYLON.Observable();
  63147. _this.onPadDownObservable = new BABYLON.Observable();
  63148. _this.onPadUpObservable = new BABYLON.Observable();
  63149. _this._buttonA = 0;
  63150. _this._buttonB = 0;
  63151. _this._buttonX = 0;
  63152. _this._buttonY = 0;
  63153. _this._buttonBack = 0;
  63154. _this._buttonStart = 0;
  63155. _this._buttonLB = 0;
  63156. _this._buttonRB = 0;
  63157. _this._buttonLeftStick = 0;
  63158. _this._buttonRightStick = 0;
  63159. _this._dPadUp = 0;
  63160. _this._dPadDown = 0;
  63161. _this._dPadLeft = 0;
  63162. _this._dPadRight = 0;
  63163. _this._isXboxOnePad = false;
  63164. _this.type = BABYLON.Gamepad.XBOX;
  63165. _this._isXboxOnePad = xboxOne;
  63166. return _this;
  63167. }
  63168. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63169. this._onlefttriggerchanged = callback;
  63170. };
  63171. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63172. this._onrighttriggerchanged = callback;
  63173. };
  63174. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63175. get: function () {
  63176. return this._leftTrigger;
  63177. },
  63178. set: function (newValue) {
  63179. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63180. this._onlefttriggerchanged(newValue);
  63181. }
  63182. this._leftTrigger = newValue;
  63183. },
  63184. enumerable: true,
  63185. configurable: true
  63186. });
  63187. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63188. get: function () {
  63189. return this._rightTrigger;
  63190. },
  63191. set: function (newValue) {
  63192. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63193. this._onrighttriggerchanged(newValue);
  63194. }
  63195. this._rightTrigger = newValue;
  63196. },
  63197. enumerable: true,
  63198. configurable: true
  63199. });
  63200. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63201. this._onbuttondown = callback;
  63202. };
  63203. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63204. this._onbuttonup = callback;
  63205. };
  63206. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63207. this._ondpaddown = callback;
  63208. };
  63209. Xbox360Pad.prototype.ondpadup = function (callback) {
  63210. this._ondpadup = callback;
  63211. };
  63212. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63213. if (newValue !== currentValue) {
  63214. if (newValue === 1) {
  63215. if (this._onbuttondown) {
  63216. this._onbuttondown(buttonType);
  63217. }
  63218. this.onButtonDownObservable.notifyObservers(buttonType);
  63219. }
  63220. if (newValue === 0) {
  63221. if (this._onbuttonup) {
  63222. this._onbuttonup(buttonType);
  63223. }
  63224. this.onButtonUpObservable.notifyObservers(buttonType);
  63225. }
  63226. }
  63227. return newValue;
  63228. };
  63229. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63230. if (newValue !== currentValue) {
  63231. if (newValue === 1) {
  63232. if (this._ondpaddown) {
  63233. this._ondpaddown(buttonType);
  63234. }
  63235. this.onPadDownObservable.notifyObservers(buttonType);
  63236. }
  63237. if (newValue === 0) {
  63238. if (this._ondpadup) {
  63239. this._ondpadup(buttonType);
  63240. }
  63241. this.onPadUpObservable.notifyObservers(buttonType);
  63242. }
  63243. }
  63244. return newValue;
  63245. };
  63246. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63247. get: function () {
  63248. return this._buttonA;
  63249. },
  63250. set: function (value) {
  63251. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63252. },
  63253. enumerable: true,
  63254. configurable: true
  63255. });
  63256. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63257. get: function () {
  63258. return this._buttonB;
  63259. },
  63260. set: function (value) {
  63261. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63262. },
  63263. enumerable: true,
  63264. configurable: true
  63265. });
  63266. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63267. get: function () {
  63268. return this._buttonX;
  63269. },
  63270. set: function (value) {
  63271. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63272. },
  63273. enumerable: true,
  63274. configurable: true
  63275. });
  63276. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63277. get: function () {
  63278. return this._buttonY;
  63279. },
  63280. set: function (value) {
  63281. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63287. get: function () {
  63288. return this._buttonStart;
  63289. },
  63290. set: function (value) {
  63291. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63297. get: function () {
  63298. return this._buttonBack;
  63299. },
  63300. set: function (value) {
  63301. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63307. get: function () {
  63308. return this._buttonLB;
  63309. },
  63310. set: function (value) {
  63311. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63312. },
  63313. enumerable: true,
  63314. configurable: true
  63315. });
  63316. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63317. get: function () {
  63318. return this._buttonRB;
  63319. },
  63320. set: function (value) {
  63321. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63322. },
  63323. enumerable: true,
  63324. configurable: true
  63325. });
  63326. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63327. get: function () {
  63328. return this._buttonLeftStick;
  63329. },
  63330. set: function (value) {
  63331. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63332. },
  63333. enumerable: true,
  63334. configurable: true
  63335. });
  63336. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63337. get: function () {
  63338. return this._buttonRightStick;
  63339. },
  63340. set: function (value) {
  63341. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63342. },
  63343. enumerable: true,
  63344. configurable: true
  63345. });
  63346. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63347. get: function () {
  63348. return this._dPadUp;
  63349. },
  63350. set: function (value) {
  63351. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63352. },
  63353. enumerable: true,
  63354. configurable: true
  63355. });
  63356. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63357. get: function () {
  63358. return this._dPadDown;
  63359. },
  63360. set: function (value) {
  63361. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63362. },
  63363. enumerable: true,
  63364. configurable: true
  63365. });
  63366. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63367. get: function () {
  63368. return this._dPadLeft;
  63369. },
  63370. set: function (value) {
  63371. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63372. },
  63373. enumerable: true,
  63374. configurable: true
  63375. });
  63376. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63377. get: function () {
  63378. return this._dPadRight;
  63379. },
  63380. set: function (value) {
  63381. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63382. },
  63383. enumerable: true,
  63384. configurable: true
  63385. });
  63386. Xbox360Pad.prototype.update = function () {
  63387. _super.prototype.update.call(this);
  63388. if (this._isXboxOnePad) {
  63389. this.buttonA = this.browserGamepad.buttons[0].value;
  63390. this.buttonB = this.browserGamepad.buttons[1].value;
  63391. this.buttonX = this.browserGamepad.buttons[2].value;
  63392. this.buttonY = this.browserGamepad.buttons[3].value;
  63393. this.buttonLB = this.browserGamepad.buttons[4].value;
  63394. this.buttonRB = this.browserGamepad.buttons[5].value;
  63395. this.leftTrigger = this.browserGamepad.axes[2];
  63396. this.rightTrigger = this.browserGamepad.axes[5];
  63397. this.buttonBack = this.browserGamepad.buttons[9].value;
  63398. this.buttonStart = this.browserGamepad.buttons[8].value;
  63399. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63400. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63401. this.dPadUp = this.browserGamepad.buttons[11].value;
  63402. this.dPadDown = this.browserGamepad.buttons[12].value;
  63403. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63404. this.dPadRight = this.browserGamepad.buttons[14].value;
  63405. }
  63406. else {
  63407. this.buttonA = this.browserGamepad.buttons[0].value;
  63408. this.buttonB = this.browserGamepad.buttons[1].value;
  63409. this.buttonX = this.browserGamepad.buttons[2].value;
  63410. this.buttonY = this.browserGamepad.buttons[3].value;
  63411. this.buttonLB = this.browserGamepad.buttons[4].value;
  63412. this.buttonRB = this.browserGamepad.buttons[5].value;
  63413. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63414. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63415. this.buttonBack = this.browserGamepad.buttons[8].value;
  63416. this.buttonStart = this.browserGamepad.buttons[9].value;
  63417. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63418. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63419. this.dPadUp = this.browserGamepad.buttons[12].value;
  63420. this.dPadDown = this.browserGamepad.buttons[13].value;
  63421. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63422. this.dPadRight = this.browserGamepad.buttons[15].value;
  63423. }
  63424. };
  63425. Xbox360Pad.prototype.dispose = function () {
  63426. _super.prototype.dispose.call(this);
  63427. this.onButtonDownObservable.clear();
  63428. this.onButtonUpObservable.clear();
  63429. this.onPadDownObservable.clear();
  63430. this.onPadUpObservable.clear();
  63431. };
  63432. return Xbox360Pad;
  63433. }(BABYLON.Gamepad));
  63434. BABYLON.Xbox360Pad = Xbox360Pad;
  63435. })(BABYLON || (BABYLON = {}));
  63436. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63437. var BABYLON;
  63438. (function (BABYLON) {
  63439. var PoseEnabledControllerType;
  63440. (function (PoseEnabledControllerType) {
  63441. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63442. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63443. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63444. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63445. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63446. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63447. var PoseEnabledControllerHelper = /** @class */ (function () {
  63448. function PoseEnabledControllerHelper() {
  63449. }
  63450. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63451. // Oculus Touch
  63452. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63453. return new BABYLON.OculusTouchController(vrGamepad);
  63454. }
  63455. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63456. return new BABYLON.WindowsMotionController(vrGamepad);
  63457. }
  63458. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63459. return new BABYLON.ViveController(vrGamepad);
  63460. }
  63461. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63462. return new BABYLON.GearVRController(vrGamepad);
  63463. }
  63464. else {
  63465. return new BABYLON.GenericController(vrGamepad);
  63466. }
  63467. };
  63468. return PoseEnabledControllerHelper;
  63469. }());
  63470. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63471. var PoseEnabledController = /** @class */ (function (_super) {
  63472. __extends(PoseEnabledController, _super);
  63473. function PoseEnabledController(browserGamepad) {
  63474. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63475. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63476. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63477. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63478. // Represents device position and rotation in babylon space
  63479. _this.devicePosition = BABYLON.Vector3.Zero();
  63480. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63481. _this.deviceScaleFactor = 1;
  63482. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63483. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63484. _this._workingMatrix = BABYLON.Matrix.Identity();
  63485. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63486. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63487. _this.position = BABYLON.Vector3.Zero();
  63488. _this.rotationQuaternion = new BABYLON.Quaternion();
  63489. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63490. _this._calculatedRotation = new BABYLON.Quaternion();
  63491. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63492. return _this;
  63493. }
  63494. PoseEnabledController.prototype.update = function () {
  63495. _super.prototype.update.call(this);
  63496. var pose = this.browserGamepad.pose;
  63497. this.updateFromDevice(pose);
  63498. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63499. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63500. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63501. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63502. if (this._mesh) {
  63503. this._mesh.position.copyFrom(this.devicePosition);
  63504. if (this._mesh.rotationQuaternion) {
  63505. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63506. }
  63507. }
  63508. };
  63509. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63510. if (poseData) {
  63511. this.rawPose = poseData;
  63512. if (poseData.position) {
  63513. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63514. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63515. this._deviceRoomPosition.z *= -1;
  63516. }
  63517. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63518. this._calculatedPosition.addInPlace(this.position);
  63519. }
  63520. var pose = this.rawPose;
  63521. if (poseData.orientation && pose.orientation) {
  63522. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63523. if (this._mesh) {
  63524. if (this._mesh.getScene().useRightHandedSystem) {
  63525. this._deviceRoomRotationQuaternion.z *= -1;
  63526. this._deviceRoomRotationQuaternion.w *= -1;
  63527. }
  63528. else {
  63529. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63530. }
  63531. }
  63532. // if the camera is set, rotate to the camera's rotation
  63533. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63534. }
  63535. }
  63536. };
  63537. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63538. if (this._mesh) {
  63539. this._mesh.parent = null;
  63540. }
  63541. this._mesh = mesh;
  63542. if (this._poseControlledCamera) {
  63543. this._mesh.parent = this._poseControlledCamera;
  63544. }
  63545. if (!this._mesh.rotationQuaternion) {
  63546. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63547. }
  63548. };
  63549. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63550. this._poseControlledCamera = camera;
  63551. if (this._mesh) {
  63552. this._mesh.parent = this._poseControlledCamera;
  63553. }
  63554. };
  63555. PoseEnabledController.prototype.dispose = function () {
  63556. if (this._mesh) {
  63557. this._mesh.dispose();
  63558. }
  63559. this._mesh = null;
  63560. _super.prototype.dispose.call(this);
  63561. };
  63562. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63563. get: function () {
  63564. return this._mesh;
  63565. },
  63566. enumerable: true,
  63567. configurable: true
  63568. });
  63569. PoseEnabledController.prototype.getForwardRay = function (length) {
  63570. if (length === void 0) { length = 100; }
  63571. if (!this.mesh) {
  63572. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63573. }
  63574. var m = this.mesh.getWorldMatrix();
  63575. var origin = m.getTranslation();
  63576. var forward = new BABYLON.Vector3(0, 0, -1);
  63577. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63578. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63579. return new BABYLON.Ray(origin, direction, length);
  63580. };
  63581. return PoseEnabledController;
  63582. }(BABYLON.Gamepad));
  63583. BABYLON.PoseEnabledController = PoseEnabledController;
  63584. })(BABYLON || (BABYLON = {}));
  63585. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63586. var BABYLON;
  63587. (function (BABYLON) {
  63588. var WebVRController = /** @class */ (function (_super) {
  63589. __extends(WebVRController, _super);
  63590. function WebVRController(vrGamepad) {
  63591. var _this = _super.call(this, vrGamepad) || this;
  63592. // Observables
  63593. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63594. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63595. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63596. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63597. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63598. _this.pad = { x: 0, y: 0 };
  63599. // avoid GC, store state in a tmp object
  63600. _this._changes = {
  63601. pressChanged: false,
  63602. touchChanged: false,
  63603. valueChanged: false,
  63604. changed: false
  63605. };
  63606. _this._buttons = new Array(vrGamepad.buttons.length);
  63607. _this.hand = vrGamepad.hand;
  63608. return _this;
  63609. }
  63610. WebVRController.prototype.onButtonStateChange = function (callback) {
  63611. this._onButtonStateChange = callback;
  63612. };
  63613. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63614. get: function () {
  63615. return this._defaultModel;
  63616. },
  63617. enumerable: true,
  63618. configurable: true
  63619. });
  63620. WebVRController.prototype.update = function () {
  63621. _super.prototype.update.call(this);
  63622. for (var index = 0; index < this._buttons.length; index++) {
  63623. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63624. }
  63625. ;
  63626. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63627. this.pad.x = this.leftStick.x;
  63628. this.pad.y = this.leftStick.y;
  63629. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63630. }
  63631. };
  63632. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63633. if (!newState) {
  63634. newState = {
  63635. pressed: false,
  63636. touched: false,
  63637. value: 0
  63638. };
  63639. }
  63640. if (!currentState) {
  63641. this._buttons[buttonIndex] = {
  63642. pressed: newState.pressed,
  63643. touched: newState.touched,
  63644. value: newState.value
  63645. };
  63646. return;
  63647. }
  63648. this._checkChanges(newState, currentState);
  63649. if (this._changes.changed) {
  63650. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63651. this.handleButtonChange(buttonIndex, newState, this._changes);
  63652. }
  63653. this._buttons[buttonIndex].pressed = newState.pressed;
  63654. this._buttons[buttonIndex].touched = newState.touched;
  63655. // oculus triggers are never 0, thou not touched.
  63656. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63657. };
  63658. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63659. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63660. this._changes.touchChanged = newState.touched !== currentState.touched;
  63661. this._changes.valueChanged = newState.value !== currentState.value;
  63662. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63663. return this._changes;
  63664. };
  63665. WebVRController.prototype.dispose = function () {
  63666. _super.prototype.dispose.call(this);
  63667. this.onTriggerStateChangedObservable.clear();
  63668. this.onMainButtonStateChangedObservable.clear();
  63669. this.onSecondaryButtonStateChangedObservable.clear();
  63670. this.onPadStateChangedObservable.clear();
  63671. this.onPadValuesChangedObservable.clear();
  63672. };
  63673. return WebVRController;
  63674. }(BABYLON.PoseEnabledController));
  63675. BABYLON.WebVRController = WebVRController;
  63676. })(BABYLON || (BABYLON = {}));
  63677. //# sourceMappingURL=babylon.webVRController.js.map
  63678. var BABYLON;
  63679. (function (BABYLON) {
  63680. var OculusTouchController = /** @class */ (function (_super) {
  63681. __extends(OculusTouchController, _super);
  63682. function OculusTouchController(vrGamepad) {
  63683. var _this = _super.call(this, vrGamepad) || this;
  63684. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63685. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63686. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63687. return _this;
  63688. }
  63689. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63690. var _this = this;
  63691. var meshName;
  63692. // Hand
  63693. if (this.hand === 'left') {
  63694. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63695. }
  63696. else {
  63697. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63698. }
  63699. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63700. /*
  63701. Parent Mesh name: oculus_touch_left
  63702. - body
  63703. - trigger
  63704. - thumbstick
  63705. - grip
  63706. - button_y
  63707. - button_x
  63708. - button_enter
  63709. */
  63710. _this._defaultModel = newMeshes[1];
  63711. _this.attachToMesh(_this._defaultModel);
  63712. if (meshLoaded) {
  63713. meshLoaded(_this._defaultModel);
  63714. }
  63715. });
  63716. };
  63717. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63718. // helper getters for left and right hand.
  63719. get: function () {
  63720. if (this.hand === 'right') {
  63721. return this.onMainButtonStateChangedObservable;
  63722. }
  63723. else {
  63724. throw new Error('No A button on left hand');
  63725. }
  63726. },
  63727. enumerable: true,
  63728. configurable: true
  63729. });
  63730. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63731. get: function () {
  63732. if (this.hand === 'right') {
  63733. return this.onSecondaryButtonStateChangedObservable;
  63734. }
  63735. else {
  63736. throw new Error('No B button on left hand');
  63737. }
  63738. },
  63739. enumerable: true,
  63740. configurable: true
  63741. });
  63742. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63743. get: function () {
  63744. if (this.hand === 'left') {
  63745. return this.onMainButtonStateChangedObservable;
  63746. }
  63747. else {
  63748. throw new Error('No X button on right hand');
  63749. }
  63750. },
  63751. enumerable: true,
  63752. configurable: true
  63753. });
  63754. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63755. get: function () {
  63756. if (this.hand === 'left') {
  63757. return this.onSecondaryButtonStateChangedObservable;
  63758. }
  63759. else {
  63760. throw new Error('No Y button on right hand');
  63761. }
  63762. },
  63763. enumerable: true,
  63764. configurable: true
  63765. });
  63766. /*
  63767. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63768. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63769. 2) secondary trigger (same)
  63770. 3) A (right) X (left), touch, pressed = value
  63771. 4) B / Y
  63772. 5) thumb rest
  63773. */
  63774. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63775. var notifyObject = state; //{ state: state, changes: changes };
  63776. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63777. switch (buttonIdx) {
  63778. case 0:
  63779. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63780. return;
  63781. case 1:// index trigger
  63782. if (this._defaultModel) {
  63783. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63784. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63785. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63786. }
  63787. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63788. return;
  63789. case 2:// secondary trigger
  63790. if (this._defaultModel) {
  63791. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63792. }
  63793. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63794. return;
  63795. case 3:
  63796. if (this._defaultModel) {
  63797. if (notifyObject.pressed) {
  63798. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63799. }
  63800. else {
  63801. (this._defaultModel.getChildren()[1]).position.y = 0;
  63802. }
  63803. }
  63804. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63805. return;
  63806. case 4:
  63807. if (this._defaultModel) {
  63808. if (notifyObject.pressed) {
  63809. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63810. }
  63811. else {
  63812. (this._defaultModel.getChildren()[2]).position.y = 0;
  63813. }
  63814. }
  63815. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63816. return;
  63817. case 5:
  63818. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63819. return;
  63820. }
  63821. };
  63822. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63823. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63824. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63825. return OculusTouchController;
  63826. }(BABYLON.WebVRController));
  63827. BABYLON.OculusTouchController = OculusTouchController;
  63828. })(BABYLON || (BABYLON = {}));
  63829. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63830. var BABYLON;
  63831. (function (BABYLON) {
  63832. var ViveController = /** @class */ (function (_super) {
  63833. __extends(ViveController, _super);
  63834. function ViveController(vrGamepad) {
  63835. var _this = _super.call(this, vrGamepad) || this;
  63836. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63837. _this._invertLeftStickY = true;
  63838. return _this;
  63839. }
  63840. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63841. var _this = this;
  63842. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63843. /*
  63844. Parent Mesh name: ViveWand
  63845. - body
  63846. - r_gripper
  63847. - l_gripper
  63848. - menu_button
  63849. - system_button
  63850. - trackpad
  63851. - trigger
  63852. - LED
  63853. */
  63854. _this._defaultModel = newMeshes[1];
  63855. _this.attachToMesh(_this._defaultModel);
  63856. if (meshLoaded) {
  63857. meshLoaded(_this._defaultModel);
  63858. }
  63859. });
  63860. };
  63861. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63862. get: function () {
  63863. return this.onMainButtonStateChangedObservable;
  63864. },
  63865. enumerable: true,
  63866. configurable: true
  63867. });
  63868. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63869. get: function () {
  63870. return this.onMainButtonStateChangedObservable;
  63871. },
  63872. enumerable: true,
  63873. configurable: true
  63874. });
  63875. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63876. get: function () {
  63877. return this.onSecondaryButtonStateChangedObservable;
  63878. },
  63879. enumerable: true,
  63880. configurable: true
  63881. });
  63882. /**
  63883. * Vive mapping:
  63884. * 0: touchpad
  63885. * 1: trigger
  63886. * 2: left AND right buttons
  63887. * 3: menu button
  63888. */
  63889. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63890. var notifyObject = state; //{ state: state, changes: changes };
  63891. switch (buttonIdx) {
  63892. case 0:
  63893. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63894. return;
  63895. case 1:// index trigger
  63896. if (this._defaultModel) {
  63897. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63898. }
  63899. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63900. return;
  63901. case 2:// left AND right button
  63902. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63903. return;
  63904. case 3:
  63905. if (this._defaultModel) {
  63906. if (notifyObject.pressed) {
  63907. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63908. }
  63909. else {
  63910. (this._defaultModel.getChildren()[2]).position.y = 0;
  63911. }
  63912. }
  63913. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63914. return;
  63915. }
  63916. };
  63917. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63918. ViveController.MODEL_FILENAME = 'wand.babylon';
  63919. return ViveController;
  63920. }(BABYLON.WebVRController));
  63921. BABYLON.ViveController = ViveController;
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.viveController.js.map
  63924. var BABYLON;
  63925. (function (BABYLON) {
  63926. var GenericController = /** @class */ (function (_super) {
  63927. __extends(GenericController, _super);
  63928. function GenericController(vrGamepad) {
  63929. return _super.call(this, vrGamepad) || this;
  63930. }
  63931. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63932. var _this = this;
  63933. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63934. _this._defaultModel = newMeshes[1];
  63935. _this.attachToMesh(_this._defaultModel);
  63936. if (meshLoaded) {
  63937. meshLoaded(_this._defaultModel);
  63938. }
  63939. });
  63940. };
  63941. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63942. console.log("Button id: " + buttonIdx + "state: ");
  63943. console.dir(state);
  63944. };
  63945. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63946. GenericController.MODEL_FILENAME = 'generic.babylon';
  63947. return GenericController;
  63948. }(BABYLON.WebVRController));
  63949. BABYLON.GenericController = GenericController;
  63950. })(BABYLON || (BABYLON = {}));
  63951. //# sourceMappingURL=babylon.genericController.js.map
  63952. var BABYLON;
  63953. (function (BABYLON) {
  63954. var LoadedMeshInfo = /** @class */ (function () {
  63955. function LoadedMeshInfo() {
  63956. this.buttonMeshes = {};
  63957. this.axisMeshes = {};
  63958. }
  63959. return LoadedMeshInfo;
  63960. }());
  63961. var WindowsMotionController = /** @class */ (function (_super) {
  63962. __extends(WindowsMotionController, _super);
  63963. function WindowsMotionController(vrGamepad) {
  63964. var _this = _super.call(this, vrGamepad) || this;
  63965. _this._mapping = {
  63966. // Semantic button names
  63967. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63968. // A mapping of the button name to glTF model node name
  63969. // that should be transformed by button value.
  63970. buttonMeshNames: {
  63971. 'trigger': 'SELECT',
  63972. 'menu': 'MENU',
  63973. 'grip': 'GRASP',
  63974. 'thumbstick': 'THUMBSTICK_PRESS',
  63975. 'trackpad': 'TOUCHPAD_PRESS'
  63976. },
  63977. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63978. buttonObservableNames: {
  63979. 'trigger': 'onTriggerStateChangedObservable',
  63980. 'menu': 'onSecondaryButtonStateChangedObservable',
  63981. 'grip': 'onMainButtonStateChangedObservable',
  63982. 'thumbstick': 'onPadStateChangedObservable',
  63983. 'trackpad': 'onTrackpadChangedObservable'
  63984. },
  63985. // A mapping of the axis name to glTF model node name
  63986. // that should be transformed by axis value.
  63987. // This array mirrors the browserGamepad.axes array, such that
  63988. // the mesh corresponding to axis 0 is in this array index 0.
  63989. axisMeshNames: [
  63990. 'THUMBSTICK_X',
  63991. 'THUMBSTICK_Y',
  63992. 'TOUCHPAD_TOUCH_X',
  63993. 'TOUCHPAD_TOUCH_Y'
  63994. ],
  63995. pointingPoseMeshName: 'POINTING_POSE'
  63996. };
  63997. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63998. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63999. _this.trackpad = { x: 0, y: 0 };
  64000. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64001. _this._loadedMeshInfo = null;
  64002. return _this;
  64003. }
  64004. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64005. get: function () {
  64006. return this.onTriggerStateChangedObservable;
  64007. },
  64008. enumerable: true,
  64009. configurable: true
  64010. });
  64011. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64012. get: function () {
  64013. return this.onSecondaryButtonStateChangedObservable;
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64019. get: function () {
  64020. return this.onMainButtonStateChangedObservable;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64026. get: function () {
  64027. return this.onPadStateChangedObservable;
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64033. get: function () {
  64034. return this.onTrackpadChangedObservable;
  64035. },
  64036. enumerable: true,
  64037. configurable: true
  64038. });
  64039. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64040. get: function () {
  64041. return this.onTrackpadValuesChangedObservable;
  64042. },
  64043. enumerable: true,
  64044. configurable: true
  64045. });
  64046. /**
  64047. * Called once per frame by the engine.
  64048. */
  64049. WindowsMotionController.prototype.update = function () {
  64050. _super.prototype.update.call(this);
  64051. // Only need to animate axes if there is a loaded mesh
  64052. if (this._loadedMeshInfo) {
  64053. if (this.browserGamepad.axes) {
  64054. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64055. this.trackpad.x = this.browserGamepad["axes"][2];
  64056. this.trackpad.y = this.browserGamepad["axes"][3];
  64057. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64058. }
  64059. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64060. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64061. }
  64062. }
  64063. }
  64064. };
  64065. /**
  64066. * Called once for each button that changed state since the last frame
  64067. * @param buttonIdx Which button index changed
  64068. * @param state New state of the button
  64069. * @param changes Which properties on the state changed since last frame
  64070. */
  64071. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64072. var buttonName = this._mapping.buttons[buttonIdx];
  64073. if (!buttonName) {
  64074. return;
  64075. }
  64076. // Only emit events for buttons that we know how to map from index to name
  64077. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64078. if (observable) {
  64079. observable.notifyObservers(state);
  64080. }
  64081. this.lerpButtonTransform(buttonName, state.value);
  64082. };
  64083. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64084. // If there is no loaded mesh, there is nothing to transform.
  64085. if (!this._loadedMeshInfo) {
  64086. return;
  64087. }
  64088. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64089. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64090. return;
  64091. }
  64092. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64093. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64094. };
  64095. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64096. if (!this._loadedMeshInfo) {
  64097. return;
  64098. }
  64099. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64100. if (!meshInfo) {
  64101. return;
  64102. }
  64103. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64104. return;
  64105. }
  64106. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64107. var lerpValue = axisValue * 0.5 + 0.5;
  64108. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64109. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64110. };
  64111. /**
  64112. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64113. * @param scene scene in which to add meshes
  64114. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64115. */
  64116. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64117. var _this = this;
  64118. if (forceDefault === void 0) { forceDefault = false; }
  64119. var path;
  64120. var filename;
  64121. // Checking if GLB loader is present
  64122. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64123. // Determine the device specific folder based on the ID suffix
  64124. var device = 'default';
  64125. if (this.id && !forceDefault) {
  64126. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64127. device = ((match && match[0]) || device);
  64128. }
  64129. // Hand
  64130. if (this.hand === 'left') {
  64131. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64132. }
  64133. else {
  64134. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64135. }
  64136. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64137. }
  64138. else {
  64139. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64140. path = BABYLON.GenericController.MODEL_BASE_URL;
  64141. filename = BABYLON.GenericController.MODEL_FILENAME;
  64142. }
  64143. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64144. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64145. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64146. if (!_this._loadedMeshInfo) {
  64147. return;
  64148. }
  64149. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64150. _this.attachToMesh(_this._defaultModel);
  64151. if (meshLoaded) {
  64152. meshLoaded(_this._defaultModel);
  64153. }
  64154. }, null, function (scene, message) {
  64155. BABYLON.Tools.Log(message);
  64156. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64157. if (!forceDefault) {
  64158. _this.initControllerMesh(scene, meshLoaded, true);
  64159. }
  64160. });
  64161. };
  64162. /**
  64163. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64164. * can be transformed by button presses and axes values, based on this._mapping.
  64165. *
  64166. * @param scene scene in which the meshes exist
  64167. * @param meshes list of meshes that make up the controller model to process
  64168. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64169. */
  64170. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64171. var loadedMeshInfo = null;
  64172. // Create a new mesh to contain the glTF hierarchy
  64173. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64174. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64175. var childMesh = null;
  64176. for (var i = 0; i < meshes.length; i++) {
  64177. var mesh = meshes[i];
  64178. if (!mesh.parent) {
  64179. // Exclude controller meshes from picking results
  64180. mesh.isPickable = false;
  64181. // Handle root node, attach to the new parentMesh
  64182. childMesh = mesh;
  64183. break;
  64184. }
  64185. }
  64186. if (childMesh) {
  64187. childMesh.setParent(parentMesh);
  64188. // Create our mesh info. Note that this method will always return non-null.
  64189. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64190. }
  64191. else {
  64192. BABYLON.Tools.Warn('Could not find root node in model file.');
  64193. }
  64194. return loadedMeshInfo;
  64195. };
  64196. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64197. var loadedMeshInfo = new LoadedMeshInfo();
  64198. var i;
  64199. loadedMeshInfo.rootNode = rootNode;
  64200. // Reset the caches
  64201. loadedMeshInfo.buttonMeshes = {};
  64202. loadedMeshInfo.axisMeshes = {};
  64203. // Button Meshes
  64204. for (i = 0; i < this._mapping.buttons.length; i++) {
  64205. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64206. if (!buttonMeshName) {
  64207. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64208. continue;
  64209. }
  64210. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64211. if (!buttonMesh) {
  64212. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64213. continue;
  64214. }
  64215. var buttonMeshInfo = {
  64216. index: i,
  64217. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64218. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64219. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64220. };
  64221. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64222. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64223. }
  64224. else {
  64225. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64226. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64227. '(VALUE: ' + !!buttonMeshInfo.value +
  64228. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64229. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64230. ')');
  64231. }
  64232. }
  64233. // Axis Meshes
  64234. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64235. var axisMeshName = this._mapping.axisMeshNames[i];
  64236. if (!axisMeshName) {
  64237. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64238. continue;
  64239. }
  64240. var axisMesh = getChildByName(rootNode, axisMeshName);
  64241. if (!axisMesh) {
  64242. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64243. continue;
  64244. }
  64245. var axisMeshInfo = {
  64246. index: i,
  64247. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64248. min: getImmediateChildByName(axisMesh, 'MIN'),
  64249. max: getImmediateChildByName(axisMesh, 'MAX')
  64250. };
  64251. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64252. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64253. }
  64254. else {
  64255. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64256. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64257. '(VALUE: ' + !!axisMeshInfo.value +
  64258. ', MIN: ' + !!axisMeshInfo.min +
  64259. ', MAX:' + !!axisMeshInfo.max +
  64260. ')');
  64261. }
  64262. }
  64263. // Pointing Ray
  64264. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64265. if (!loadedMeshInfo.pointingPoseNode) {
  64266. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64267. }
  64268. return loadedMeshInfo;
  64269. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64270. function getChildByName(node, name) {
  64271. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64272. }
  64273. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64274. function getImmediateChildByName(node, name) {
  64275. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64276. }
  64277. };
  64278. WindowsMotionController.prototype.getForwardRay = function (length) {
  64279. if (length === void 0) { length = 100; }
  64280. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64281. return _super.prototype.getForwardRay.call(this, length);
  64282. }
  64283. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64284. var origin = m.getTranslation();
  64285. var forward = new BABYLON.Vector3(0, 0, -1);
  64286. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64287. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64288. return new BABYLON.Ray(origin, direction, length);
  64289. };
  64290. WindowsMotionController.prototype.dispose = function () {
  64291. _super.prototype.dispose.call(this);
  64292. this.onTrackpadChangedObservable.clear();
  64293. };
  64294. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64295. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64296. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64297. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64298. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64299. return WindowsMotionController;
  64300. }(BABYLON.WebVRController));
  64301. BABYLON.WindowsMotionController = WindowsMotionController;
  64302. })(BABYLON || (BABYLON = {}));
  64303. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64304. var BABYLON;
  64305. (function (BABYLON) {
  64306. var GearVRController = /** @class */ (function (_super) {
  64307. __extends(GearVRController, _super);
  64308. function GearVRController(vrGamepad) {
  64309. var _this = _super.call(this, vrGamepad) || this;
  64310. _this._buttonIndexToObservableNameMap = [
  64311. 'onTrackpadChangedObservable',
  64312. 'onTriggerStateChangedObservable' // Trigger
  64313. ];
  64314. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64315. return _this;
  64316. }
  64317. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64318. var _this = this;
  64319. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64320. _this._defaultModel = newMeshes[1];
  64321. _this.attachToMesh(_this._defaultModel);
  64322. if (meshLoaded) {
  64323. meshLoaded(_this._defaultModel);
  64324. }
  64325. });
  64326. };
  64327. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64328. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64329. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64330. // Only emit events for buttons that we know how to map from index to observable
  64331. var observable = this[observableName];
  64332. if (observable) {
  64333. observable.notifyObservers(state);
  64334. }
  64335. }
  64336. };
  64337. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64338. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64339. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64340. return GearVRController;
  64341. }(BABYLON.WebVRController));
  64342. BABYLON.GearVRController = GearVRController;
  64343. })(BABYLON || (BABYLON = {}));
  64344. //# sourceMappingURL=babylon.gearVRController.js.map
  64345. var BABYLON;
  64346. (function (BABYLON) {
  64347. var FollowCamera = /** @class */ (function (_super) {
  64348. __extends(FollowCamera, _super);
  64349. function FollowCamera(name, position, scene, lockedTarget) {
  64350. if (lockedTarget === void 0) { lockedTarget = null; }
  64351. var _this = _super.call(this, name, position, scene) || this;
  64352. _this.radius = 12;
  64353. _this.rotationOffset = 0;
  64354. _this.heightOffset = 4;
  64355. _this.cameraAcceleration = 0.05;
  64356. _this.maxCameraSpeed = 20;
  64357. _this.lockedTarget = lockedTarget;
  64358. return _this;
  64359. }
  64360. FollowCamera.prototype.getRadians = function (degrees) {
  64361. return degrees * Math.PI / 180;
  64362. };
  64363. FollowCamera.prototype.follow = function (cameraTarget) {
  64364. if (!cameraTarget)
  64365. return;
  64366. var yRotation;
  64367. if (cameraTarget.rotationQuaternion) {
  64368. var rotMatrix = new BABYLON.Matrix();
  64369. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64370. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64371. }
  64372. else {
  64373. yRotation = cameraTarget.rotation.y;
  64374. }
  64375. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64376. var targetPosition = cameraTarget.getAbsolutePosition();
  64377. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64378. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64379. var dx = targetX - this.position.x;
  64380. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64381. var dz = (targetZ) - this.position.z;
  64382. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64383. var vy = dy * this.cameraAcceleration;
  64384. var vz = dz * this.cameraAcceleration * 2;
  64385. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64386. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64387. }
  64388. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64389. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64390. }
  64391. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64392. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64393. }
  64394. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64395. this.setTarget(targetPosition);
  64396. };
  64397. FollowCamera.prototype._checkInputs = function () {
  64398. _super.prototype._checkInputs.call(this);
  64399. if (this.lockedTarget) {
  64400. this.follow(this.lockedTarget);
  64401. }
  64402. };
  64403. FollowCamera.prototype.getClassName = function () {
  64404. return "FollowCamera";
  64405. };
  64406. __decorate([
  64407. BABYLON.serialize()
  64408. ], FollowCamera.prototype, "radius", void 0);
  64409. __decorate([
  64410. BABYLON.serialize()
  64411. ], FollowCamera.prototype, "rotationOffset", void 0);
  64412. __decorate([
  64413. BABYLON.serialize()
  64414. ], FollowCamera.prototype, "heightOffset", void 0);
  64415. __decorate([
  64416. BABYLON.serialize()
  64417. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64418. __decorate([
  64419. BABYLON.serialize()
  64420. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64421. __decorate([
  64422. BABYLON.serializeAsMeshReference("lockedTargetId")
  64423. ], FollowCamera.prototype, "lockedTarget", void 0);
  64424. return FollowCamera;
  64425. }(BABYLON.TargetCamera));
  64426. BABYLON.FollowCamera = FollowCamera;
  64427. var ArcFollowCamera = /** @class */ (function (_super) {
  64428. __extends(ArcFollowCamera, _super);
  64429. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64430. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64431. _this.alpha = alpha;
  64432. _this.beta = beta;
  64433. _this.radius = radius;
  64434. _this.target = target;
  64435. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64436. _this.follow();
  64437. return _this;
  64438. }
  64439. ArcFollowCamera.prototype.follow = function () {
  64440. if (!this.target) {
  64441. return;
  64442. }
  64443. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64444. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64445. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64446. var targetPosition = this.target.getAbsolutePosition();
  64447. this.position = targetPosition.add(this._cartesianCoordinates);
  64448. this.setTarget(targetPosition);
  64449. };
  64450. ArcFollowCamera.prototype._checkInputs = function () {
  64451. _super.prototype._checkInputs.call(this);
  64452. this.follow();
  64453. };
  64454. ArcFollowCamera.prototype.getClassName = function () {
  64455. return "ArcFollowCamera";
  64456. };
  64457. return ArcFollowCamera;
  64458. }(BABYLON.TargetCamera));
  64459. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64460. })(BABYLON || (BABYLON = {}));
  64461. //# sourceMappingURL=babylon.followCamera.js.map
  64462. var BABYLON;
  64463. (function (BABYLON) {
  64464. // We're mainly based on the logic defined into the FreeCamera code
  64465. var UniversalCamera = /** @class */ (function (_super) {
  64466. __extends(UniversalCamera, _super);
  64467. //-- end properties for backward compatibility for inputs
  64468. function UniversalCamera(name, position, scene) {
  64469. var _this = _super.call(this, name, position, scene) || this;
  64470. _this.inputs.addGamepad();
  64471. return _this;
  64472. }
  64473. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64474. //-- Begin properties for backward compatibility for inputs
  64475. get: function () {
  64476. var gamepad = this.inputs.attached["gamepad"];
  64477. if (gamepad)
  64478. return gamepad.gamepadAngularSensibility;
  64479. return 0;
  64480. },
  64481. set: function (value) {
  64482. var gamepad = this.inputs.attached["gamepad"];
  64483. if (gamepad)
  64484. gamepad.gamepadAngularSensibility = value;
  64485. },
  64486. enumerable: true,
  64487. configurable: true
  64488. });
  64489. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64490. get: function () {
  64491. var gamepad = this.inputs.attached["gamepad"];
  64492. if (gamepad)
  64493. return gamepad.gamepadMoveSensibility;
  64494. return 0;
  64495. },
  64496. set: function (value) {
  64497. var gamepad = this.inputs.attached["gamepad"];
  64498. if (gamepad)
  64499. gamepad.gamepadMoveSensibility = value;
  64500. },
  64501. enumerable: true,
  64502. configurable: true
  64503. });
  64504. UniversalCamera.prototype.getClassName = function () {
  64505. return "UniversalCamera";
  64506. };
  64507. return UniversalCamera;
  64508. }(BABYLON.TouchCamera));
  64509. BABYLON.UniversalCamera = UniversalCamera;
  64510. })(BABYLON || (BABYLON = {}));
  64511. //# sourceMappingURL=babylon.universalCamera.js.map
  64512. var BABYLON;
  64513. (function (BABYLON) {
  64514. // We're mainly based on the logic defined into the FreeCamera code
  64515. var GamepadCamera = /** @class */ (function (_super) {
  64516. __extends(GamepadCamera, _super);
  64517. //-- end properties for backward compatibility for inputs
  64518. function GamepadCamera(name, position, scene) {
  64519. return _super.call(this, name, position, scene) || this;
  64520. }
  64521. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64522. //-- Begin properties for backward compatibility for inputs
  64523. get: function () {
  64524. var gamepad = this.inputs.attached["gamepad"];
  64525. if (gamepad)
  64526. return gamepad.gamepadAngularSensibility;
  64527. return 0;
  64528. },
  64529. set: function (value) {
  64530. var gamepad = this.inputs.attached["gamepad"];
  64531. if (gamepad)
  64532. gamepad.gamepadAngularSensibility = value;
  64533. },
  64534. enumerable: true,
  64535. configurable: true
  64536. });
  64537. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64538. get: function () {
  64539. var gamepad = this.inputs.attached["gamepad"];
  64540. if (gamepad)
  64541. return gamepad.gamepadMoveSensibility;
  64542. return 0;
  64543. },
  64544. set: function (value) {
  64545. var gamepad = this.inputs.attached["gamepad"];
  64546. if (gamepad)
  64547. gamepad.gamepadMoveSensibility = value;
  64548. },
  64549. enumerable: true,
  64550. configurable: true
  64551. });
  64552. GamepadCamera.prototype.getClassName = function () {
  64553. return "GamepadCamera";
  64554. };
  64555. return GamepadCamera;
  64556. }(BABYLON.UniversalCamera));
  64557. BABYLON.GamepadCamera = GamepadCamera;
  64558. })(BABYLON || (BABYLON = {}));
  64559. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64560. var BABYLON;
  64561. (function (BABYLON) {
  64562. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64563. function PostProcessRenderPipelineManager() {
  64564. this._renderPipelines = {};
  64565. }
  64566. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64567. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64568. };
  64569. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64570. if (unique === void 0) { unique = false; }
  64571. var renderPipeline = this._renderPipelines[renderPipelineName];
  64572. if (!renderPipeline) {
  64573. return;
  64574. }
  64575. renderPipeline._attachCameras(cameras, unique);
  64576. };
  64577. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64578. var renderPipeline = this._renderPipelines[renderPipelineName];
  64579. if (!renderPipeline) {
  64580. return;
  64581. }
  64582. renderPipeline._detachCameras(cameras);
  64583. };
  64584. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64585. var renderPipeline = this._renderPipelines[renderPipelineName];
  64586. if (!renderPipeline) {
  64587. return;
  64588. }
  64589. renderPipeline._enableEffect(renderEffectName, cameras);
  64590. };
  64591. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64592. var renderPipeline = this._renderPipelines[renderPipelineName];
  64593. if (!renderPipeline) {
  64594. return;
  64595. }
  64596. renderPipeline._disableEffect(renderEffectName, cameras);
  64597. };
  64598. PostProcessRenderPipelineManager.prototype.update = function () {
  64599. for (var renderPipelineName in this._renderPipelines) {
  64600. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64601. var pipeline = this._renderPipelines[renderPipelineName];
  64602. if (!pipeline.isSupported) {
  64603. pipeline.dispose();
  64604. delete this._renderPipelines[renderPipelineName];
  64605. }
  64606. else {
  64607. pipeline._update();
  64608. }
  64609. }
  64610. }
  64611. };
  64612. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64613. for (var renderPipelineName in this._renderPipelines) {
  64614. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64615. var pipeline = this._renderPipelines[renderPipelineName];
  64616. pipeline._rebuild();
  64617. }
  64618. }
  64619. };
  64620. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64621. for (var renderPipelineName in this._renderPipelines) {
  64622. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64623. var pipeline = this._renderPipelines[renderPipelineName];
  64624. pipeline.dispose();
  64625. }
  64626. }
  64627. };
  64628. return PostProcessRenderPipelineManager;
  64629. }());
  64630. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64631. })(BABYLON || (BABYLON = {}));
  64632. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64633. var BABYLON;
  64634. (function (BABYLON) {
  64635. /**
  64636. * This represents a set of one or more post processes in Babylon.
  64637. * A post process can be used to apply a shader to a texture after it is rendered.
  64638. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64639. */
  64640. var PostProcessRenderEffect = /** @class */ (function () {
  64641. /**
  64642. * Instantiates a post process render effect.
  64643. * A post process can be used to apply a shader to a texture after it is rendered.
  64644. * @param engine The engine the effect is tied to
  64645. * @param name The name of the effect
  64646. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64647. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64648. */
  64649. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64650. this._name = name;
  64651. this._singleInstance = singleInstance || true;
  64652. this._getPostProcesses = getPostProcesses;
  64653. this._cameras = {};
  64654. this._indicesForCamera = {};
  64655. this._postProcesses = {};
  64656. }
  64657. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64658. /**
  64659. * Checks if all the post processes in the effect are supported.
  64660. */
  64661. get: function () {
  64662. for (var index in this._postProcesses) {
  64663. for (var ppIndex in this._postProcesses[index]) {
  64664. if (!this._postProcesses[index][ppIndex].isSupported) {
  64665. return false;
  64666. }
  64667. }
  64668. }
  64669. return true;
  64670. },
  64671. enumerable: true,
  64672. configurable: true
  64673. });
  64674. /**
  64675. * Updates the current state of the effect
  64676. */
  64677. PostProcessRenderEffect.prototype._update = function () {
  64678. };
  64679. /**
  64680. * Attaches the effect on cameras
  64681. * @param cameras The camera to attach to.
  64682. */
  64683. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64684. var _this = this;
  64685. var cameraKey;
  64686. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64687. if (!cams) {
  64688. return;
  64689. }
  64690. for (var i = 0; i < cams.length; i++) {
  64691. var camera = cams[i];
  64692. var cameraName = camera.name;
  64693. if (this._singleInstance) {
  64694. cameraKey = 0;
  64695. }
  64696. else {
  64697. cameraKey = cameraName;
  64698. }
  64699. if (!this._postProcesses[cameraKey]) {
  64700. var postProcess = this._getPostProcesses();
  64701. if (postProcess) {
  64702. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64703. }
  64704. }
  64705. if (!this._indicesForCamera[cameraName]) {
  64706. this._indicesForCamera[cameraName] = [];
  64707. }
  64708. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64709. var index = camera.attachPostProcess(postProcess);
  64710. _this._indicesForCamera[cameraName].push(index);
  64711. });
  64712. if (!this._cameras[cameraName]) {
  64713. this._cameras[cameraName] = camera;
  64714. }
  64715. }
  64716. };
  64717. /**
  64718. * Detatches the effect on cameras
  64719. * @param cameras The camera to detatch from.
  64720. */
  64721. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64722. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64723. if (!cams) {
  64724. return;
  64725. }
  64726. for (var i = 0; i < cams.length; i++) {
  64727. var camera = cams[i];
  64728. var cameraName = camera.name;
  64729. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64730. camera.detachPostProcess(postProcess);
  64731. });
  64732. if (this._cameras[cameraName]) {
  64733. //this._indicesForCamera.splice(index, 1);
  64734. this._cameras[cameraName] = null;
  64735. }
  64736. }
  64737. };
  64738. /**
  64739. * Enables the effect on given cameras
  64740. * @param cameras The camera to enable.
  64741. */
  64742. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64743. var _this = this;
  64744. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64745. if (!cams) {
  64746. return;
  64747. }
  64748. for (var i = 0; i < cams.length; i++) {
  64749. var camera = cams[i];
  64750. var cameraName = camera.name;
  64751. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64752. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64753. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64754. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64755. });
  64756. }
  64757. }
  64758. }
  64759. };
  64760. /**
  64761. * Disables the effect on the given cameras
  64762. * @param cameras The camera to disable.
  64763. */
  64764. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64765. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64766. if (!cams) {
  64767. return;
  64768. }
  64769. for (var i = 0; i < cams.length; i++) {
  64770. var camera = cams[i];
  64771. var cameraName = camera.name;
  64772. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64773. camera.detachPostProcess(postProcess);
  64774. });
  64775. }
  64776. };
  64777. /**
  64778. * Gets a list of the post processes contained in the effect.
  64779. * @param camera The camera to get the post processes on.
  64780. * @returns The list of the post processes in the effect.
  64781. */
  64782. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64783. if (this._singleInstance) {
  64784. return this._postProcesses[0];
  64785. }
  64786. else {
  64787. if (!camera) {
  64788. return null;
  64789. }
  64790. return this._postProcesses[camera.name];
  64791. }
  64792. };
  64793. return PostProcessRenderEffect;
  64794. }());
  64795. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64796. })(BABYLON || (BABYLON = {}));
  64797. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64798. var BABYLON;
  64799. (function (BABYLON) {
  64800. var PostProcessRenderPipeline = /** @class */ (function () {
  64801. function PostProcessRenderPipeline(engine, name) {
  64802. this._name = name;
  64803. this._renderEffects = {};
  64804. this._renderEffectsForIsolatedPass = new Array();
  64805. this._cameras = [];
  64806. }
  64807. PostProcessRenderPipeline.prototype.getClassName = function () {
  64808. return "PostProcessRenderPipeline";
  64809. };
  64810. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64811. get: function () {
  64812. for (var renderEffectName in this._renderEffects) {
  64813. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64814. if (!this._renderEffects[renderEffectName].isSupported) {
  64815. return false;
  64816. }
  64817. }
  64818. }
  64819. return true;
  64820. },
  64821. enumerable: true,
  64822. configurable: true
  64823. });
  64824. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64825. this._renderEffects[renderEffect._name] = renderEffect;
  64826. };
  64827. // private
  64828. PostProcessRenderPipeline.prototype._rebuild = function () {
  64829. };
  64830. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64831. var renderEffects = this._renderEffects[renderEffectName];
  64832. if (!renderEffects) {
  64833. return;
  64834. }
  64835. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64836. };
  64837. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64838. var renderEffects = this._renderEffects[renderEffectName];
  64839. if (!renderEffects) {
  64840. return;
  64841. }
  64842. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64843. };
  64844. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64846. if (!cams) {
  64847. return;
  64848. }
  64849. var indicesToDelete = [];
  64850. var i;
  64851. for (i = 0; i < cams.length; i++) {
  64852. var camera = cams[i];
  64853. var cameraName = camera.name;
  64854. if (this._cameras.indexOf(camera) === -1) {
  64855. this._cameras[cameraName] = camera;
  64856. }
  64857. else if (unique) {
  64858. indicesToDelete.push(i);
  64859. }
  64860. }
  64861. for (i = 0; i < indicesToDelete.length; i++) {
  64862. cameras.splice(indicesToDelete[i], 1);
  64863. }
  64864. for (var renderEffectName in this._renderEffects) {
  64865. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64866. this._renderEffects[renderEffectName]._attachCameras(cams);
  64867. }
  64868. }
  64869. };
  64870. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64871. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64872. if (!cams) {
  64873. return;
  64874. }
  64875. for (var renderEffectName in this._renderEffects) {
  64876. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64877. this._renderEffects[renderEffectName]._detachCameras(cams);
  64878. }
  64879. }
  64880. for (var i = 0; i < cams.length; i++) {
  64881. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64882. }
  64883. };
  64884. PostProcessRenderPipeline.prototype._update = function () {
  64885. for (var renderEffectName in this._renderEffects) {
  64886. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64887. this._renderEffects[renderEffectName]._update();
  64888. }
  64889. }
  64890. for (var i = 0; i < this._cameras.length; i++) {
  64891. var cameraName = this._cameras[i].name;
  64892. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64893. this._renderEffectsForIsolatedPass[cameraName]._update();
  64894. }
  64895. }
  64896. };
  64897. PostProcessRenderPipeline.prototype._reset = function () {
  64898. this._renderEffects = {};
  64899. this._renderEffectsForIsolatedPass = new Array();
  64900. };
  64901. PostProcessRenderPipeline.prototype.dispose = function () {
  64902. // Must be implemented by children
  64903. };
  64904. __decorate([
  64905. BABYLON.serialize()
  64906. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64907. return PostProcessRenderPipeline;
  64908. }());
  64909. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64910. })(BABYLON || (BABYLON = {}));
  64911. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64912. var BABYLON;
  64913. (function (BABYLON) {
  64914. var DepthRenderer = /** @class */ (function () {
  64915. function DepthRenderer(scene, type) {
  64916. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64917. var _this = this;
  64918. this._scene = scene;
  64919. var engine = scene.getEngine();
  64920. // Render target
  64921. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64922. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64923. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64924. this._depthMap.refreshRate = 1;
  64925. this._depthMap.renderParticles = false;
  64926. this._depthMap.renderList = null;
  64927. // set default depth value to 1.0 (far away)
  64928. this._depthMap.onClearObservable.add(function (engine) {
  64929. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64930. });
  64931. // Custom render function
  64932. var renderSubMesh = function (subMesh) {
  64933. var mesh = subMesh.getRenderingMesh();
  64934. var scene = _this._scene;
  64935. var engine = scene.getEngine();
  64936. var material = subMesh.getMaterial();
  64937. if (!material) {
  64938. return;
  64939. }
  64940. // Culling and reverse (right handed system)
  64941. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64942. // Managing instances
  64943. var batch = mesh._getInstancesRenderList(subMesh._id);
  64944. if (batch.mustReturn) {
  64945. return;
  64946. }
  64947. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64948. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64949. engine.enableEffect(_this._effect);
  64950. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64951. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64952. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64953. // Alpha test
  64954. if (material && material.needAlphaTesting()) {
  64955. var alphaTexture = material.getAlphaTestTexture();
  64956. if (alphaTexture) {
  64957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64959. }
  64960. }
  64961. // Bones
  64962. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64963. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64964. }
  64965. // Draw
  64966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64967. }
  64968. };
  64969. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64970. var index;
  64971. if (depthOnlySubMeshes.length) {
  64972. engine.setColorWrite(false);
  64973. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64974. renderSubMesh(depthOnlySubMeshes.data[index]);
  64975. }
  64976. engine.setColorWrite(true);
  64977. }
  64978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64979. renderSubMesh(opaqueSubMeshes.data[index]);
  64980. }
  64981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64982. renderSubMesh(alphaTestSubMeshes.data[index]);
  64983. }
  64984. };
  64985. }
  64986. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64987. var material = subMesh.getMaterial();
  64988. if (material.disableDepthWrite) {
  64989. return false;
  64990. }
  64991. var defines = [];
  64992. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64993. var mesh = subMesh.getMesh();
  64994. // Alpha test
  64995. if (material && material.needAlphaTesting()) {
  64996. defines.push("#define ALPHATEST");
  64997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64998. attribs.push(BABYLON.VertexBuffer.UVKind);
  64999. defines.push("#define UV1");
  65000. }
  65001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65003. defines.push("#define UV2");
  65004. }
  65005. }
  65006. // Bones
  65007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65010. if (mesh.numBoneInfluencers > 4) {
  65011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65013. }
  65014. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65015. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65016. }
  65017. else {
  65018. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65019. }
  65020. // Instances
  65021. if (useInstances) {
  65022. defines.push("#define INSTANCES");
  65023. attribs.push("world0");
  65024. attribs.push("world1");
  65025. attribs.push("world2");
  65026. attribs.push("world3");
  65027. }
  65028. // Get correct effect
  65029. var join = defines.join("\n");
  65030. if (this._cachedDefines !== join) {
  65031. this._cachedDefines = join;
  65032. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65033. }
  65034. return this._effect.isReady();
  65035. };
  65036. DepthRenderer.prototype.getDepthMap = function () {
  65037. return this._depthMap;
  65038. };
  65039. // Methods
  65040. DepthRenderer.prototype.dispose = function () {
  65041. this._depthMap.dispose();
  65042. };
  65043. return DepthRenderer;
  65044. }());
  65045. BABYLON.DepthRenderer = DepthRenderer;
  65046. })(BABYLON || (BABYLON = {}));
  65047. //# sourceMappingURL=babylon.depthRenderer.js.map
  65048. var BABYLON;
  65049. (function (BABYLON) {
  65050. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65051. __extends(SSAORenderingPipeline, _super);
  65052. /**
  65053. * @constructor
  65054. * @param {string} name - The rendering pipeline name
  65055. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65056. * @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 }
  65057. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65058. */
  65059. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65060. var _this = _super.call(this, scene.getEngine(), name) || this;
  65061. // Members
  65062. /**
  65063. * The PassPostProcess id in the pipeline that contains the original scene color
  65064. * @type {string}
  65065. */
  65066. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65067. /**
  65068. * The SSAO PostProcess id in the pipeline
  65069. * @type {string}
  65070. */
  65071. _this.SSAORenderEffect = "SSAORenderEffect";
  65072. /**
  65073. * The horizontal blur PostProcess id in the pipeline
  65074. * @type {string}
  65075. */
  65076. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65077. /**
  65078. * The vertical blur PostProcess id in the pipeline
  65079. * @type {string}
  65080. */
  65081. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65082. /**
  65083. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65084. * @type {string}
  65085. */
  65086. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65087. /**
  65088. * The output strength of the SSAO post-process. Default value is 1.0.
  65089. * @type {number}
  65090. */
  65091. _this.totalStrength = 1.0;
  65092. /**
  65093. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65094. * @type {number}
  65095. */
  65096. _this.radius = 0.0001;
  65097. /**
  65098. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65099. * Must not be equal to fallOff and superior to fallOff.
  65100. * Default value is 0.975
  65101. * @type {number}
  65102. */
  65103. _this.area = 0.0075;
  65104. /**
  65105. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65106. * Must not be equal to area and inferior to area.
  65107. * Default value is 0.0
  65108. * @type {number}
  65109. */
  65110. _this.fallOff = 0.000001;
  65111. /**
  65112. * The base color of the SSAO post-process
  65113. * The final result is "base + ssao" between [0, 1]
  65114. * @type {number}
  65115. */
  65116. _this.base = 0.5;
  65117. _this._firstUpdate = true;
  65118. _this._scene = scene;
  65119. // Set up assets
  65120. _this._createRandomTexture();
  65121. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65122. var ssaoRatio = ratio.ssaoRatio || ratio;
  65123. var combineRatio = ratio.combineRatio || ratio;
  65124. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65125. _this._createSSAOPostProcess(ssaoRatio);
  65126. _this._createBlurPostProcess(ssaoRatio);
  65127. _this._createSSAOCombinePostProcess(combineRatio);
  65128. // Set up pipeline
  65129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65131. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65134. // Finish
  65135. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65136. if (cameras)
  65137. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65138. return _this;
  65139. }
  65140. // Public Methods
  65141. /**
  65142. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65143. */
  65144. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65145. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65146. for (var i = 0; i < this._scene.cameras.length; i++) {
  65147. var camera = this._scene.cameras[i];
  65148. this._originalColorPostProcess.dispose(camera);
  65149. this._ssaoPostProcess.dispose(camera);
  65150. this._blurHPostProcess.dispose(camera);
  65151. this._blurVPostProcess.dispose(camera);
  65152. this._ssaoCombinePostProcess.dispose(camera);
  65153. }
  65154. this._randomTexture.dispose();
  65155. if (disableDepthRender)
  65156. this._scene.disableDepthRenderer();
  65157. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65158. _super.prototype.dispose.call(this);
  65159. };
  65160. // Private Methods
  65161. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65162. var _this = this;
  65163. var size = 16;
  65164. 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);
  65165. 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);
  65166. this._blurHPostProcess.onActivateObservable.add(function () {
  65167. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65168. _this._blurHPostProcess.kernel = size * dw;
  65169. });
  65170. this._blurVPostProcess.onActivateObservable.add(function () {
  65171. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65172. _this._blurVPostProcess.kernel = size * dw;
  65173. });
  65174. };
  65175. SSAORenderingPipeline.prototype._rebuild = function () {
  65176. this._firstUpdate = true;
  65177. _super.prototype._rebuild.call(this);
  65178. };
  65179. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65180. var _this = this;
  65181. var numSamples = 16;
  65182. var sampleSphere = [
  65183. 0.5381, 0.1856, -0.4319,
  65184. 0.1379, 0.2486, 0.4430,
  65185. 0.3371, 0.5679, -0.0057,
  65186. -0.6999, -0.0451, -0.0019,
  65187. 0.0689, -0.1598, -0.8547,
  65188. 0.0560, 0.0069, -0.1843,
  65189. -0.0146, 0.1402, 0.0762,
  65190. 0.0100, -0.1924, -0.0344,
  65191. -0.3577, -0.5301, -0.4358,
  65192. -0.3169, 0.1063, 0.0158,
  65193. 0.0103, -0.5869, 0.0046,
  65194. -0.0897, -0.4940, 0.3287,
  65195. 0.7119, -0.0154, -0.0918,
  65196. -0.0533, 0.0596, -0.5411,
  65197. 0.0352, -0.0631, 0.5460,
  65198. -0.4776, 0.2847, -0.0271
  65199. ];
  65200. var samplesFactor = 1.0 / numSamples;
  65201. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65202. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65203. "area", "fallOff", "base", "range", "viewport"
  65204. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65205. this._ssaoPostProcess.onApply = function (effect) {
  65206. if (_this._firstUpdate) {
  65207. effect.setArray3("sampleSphere", sampleSphere);
  65208. effect.setFloat("samplesFactor", samplesFactor);
  65209. effect.setFloat("randTextureTiles", 4.0);
  65210. }
  65211. effect.setFloat("totalStrength", _this.totalStrength);
  65212. effect.setFloat("radius", _this.radius);
  65213. effect.setFloat("area", _this.area);
  65214. effect.setFloat("fallOff", _this.fallOff);
  65215. effect.setFloat("base", _this.base);
  65216. effect.setTexture("textureSampler", _this._depthTexture);
  65217. effect.setTexture("randomSampler", _this._randomTexture);
  65218. };
  65219. };
  65220. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65221. var _this = this;
  65222. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65223. this._ssaoCombinePostProcess.onApply = function (effect) {
  65224. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65225. };
  65226. };
  65227. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65228. var size = 512;
  65229. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65230. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65231. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65232. var context = this._randomTexture.getContext();
  65233. var rand = function (min, max) {
  65234. return Math.random() * (max - min) + min;
  65235. };
  65236. var randVector = BABYLON.Vector3.Zero();
  65237. for (var x = 0; x < size; x++) {
  65238. for (var y = 0; y < size; y++) {
  65239. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65240. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65241. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65242. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65243. context.fillRect(x, y, 1, 1);
  65244. }
  65245. }
  65246. this._randomTexture.update(false);
  65247. };
  65248. __decorate([
  65249. BABYLON.serialize()
  65250. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65251. __decorate([
  65252. BABYLON.serialize()
  65253. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65254. __decorate([
  65255. BABYLON.serialize()
  65256. ], SSAORenderingPipeline.prototype, "area", void 0);
  65257. __decorate([
  65258. BABYLON.serialize()
  65259. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65260. __decorate([
  65261. BABYLON.serialize()
  65262. ], SSAORenderingPipeline.prototype, "base", void 0);
  65263. return SSAORenderingPipeline;
  65264. }(BABYLON.PostProcessRenderPipeline));
  65265. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65266. })(BABYLON || (BABYLON = {}));
  65267. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65268. var BABYLON;
  65269. (function (BABYLON) {
  65270. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65271. __extends(SSAO2RenderingPipeline, _super);
  65272. /**
  65273. * @constructor
  65274. * @param {string} name - The rendering pipeline name
  65275. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65276. * @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 }
  65277. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65278. */
  65279. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65280. var _this = _super.call(this, scene.getEngine(), name) || this;
  65281. // Members
  65282. /**
  65283. * The PassPostProcess id in the pipeline that contains the original scene color
  65284. * @type {string}
  65285. */
  65286. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65287. /**
  65288. * The SSAO PostProcess id in the pipeline
  65289. * @type {string}
  65290. */
  65291. _this.SSAORenderEffect = "SSAORenderEffect";
  65292. /**
  65293. * The horizontal blur PostProcess id in the pipeline
  65294. * @type {string}
  65295. */
  65296. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65297. /**
  65298. * The vertical blur PostProcess id in the pipeline
  65299. * @type {string}
  65300. */
  65301. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65302. /**
  65303. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65304. * @type {string}
  65305. */
  65306. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65307. /**
  65308. * The output strength of the SSAO post-process. Default value is 1.0.
  65309. * @type {number}
  65310. */
  65311. _this.totalStrength = 1.0;
  65312. /**
  65313. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65314. * @type {number}
  65315. */
  65316. _this.maxZ = 100.0;
  65317. /**
  65318. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65319. * @type {number}
  65320. */
  65321. _this.minZAspect = 0.2;
  65322. /**
  65323. * Number of samples used for the SSAO calculations. Default value is 8
  65324. * @type {number}
  65325. */
  65326. _this._samples = 8;
  65327. /**
  65328. * Are we using bilateral blur ?
  65329. * @type {boolean}
  65330. */
  65331. _this._expensiveBlur = true;
  65332. /**
  65333. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65334. * @type {number}
  65335. */
  65336. _this.radius = 2.0;
  65337. /**
  65338. * The base color of the SSAO post-process
  65339. * The final result is "base + ssao" between [0, 1]
  65340. * @type {number}
  65341. */
  65342. _this.base = 0.1;
  65343. _this._firstUpdate = true;
  65344. _this._scene = scene;
  65345. if (!_this.isSupported) {
  65346. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65347. return _this;
  65348. }
  65349. var ssaoRatio = ratio.ssaoRatio || ratio;
  65350. var blurRatio = ratio.blurRatio || ratio;
  65351. // Set up assets
  65352. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65353. _this._createRandomTexture();
  65354. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65355. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65356. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65357. _this._createSSAOPostProcess(1.0);
  65358. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65359. _this._createSSAOCombinePostProcess(blurRatio);
  65360. // Set up pipeline
  65361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65362. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65363. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65364. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65365. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65366. // Finish
  65367. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65368. if (cameras)
  65369. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65370. return _this;
  65371. }
  65372. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65373. get: function () {
  65374. return this._samples;
  65375. },
  65376. set: function (n) {
  65377. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65378. this._samples = n;
  65379. this._sampleSphere = this._generateHemisphere();
  65380. this._firstUpdate = true;
  65381. },
  65382. enumerable: true,
  65383. configurable: true
  65384. });
  65385. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65386. get: function () {
  65387. return this._expensiveBlur;
  65388. },
  65389. set: function (b) {
  65390. 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"]);
  65391. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65392. this._expensiveBlur = b;
  65393. this._firstUpdate = true;
  65394. },
  65395. enumerable: true,
  65396. configurable: true
  65397. });
  65398. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65399. /**
  65400. * Support test.
  65401. * @type {boolean}
  65402. */
  65403. get: function () {
  65404. var engine = BABYLON.Engine.LastCreatedEngine;
  65405. if (!engine) {
  65406. return false;
  65407. }
  65408. return engine.getCaps().drawBuffersExtension;
  65409. },
  65410. enumerable: true,
  65411. configurable: true
  65412. });
  65413. // Public Methods
  65414. /**
  65415. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65416. */
  65417. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65418. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65419. for (var i = 0; i < this._scene.cameras.length; i++) {
  65420. var camera = this._scene.cameras[i];
  65421. this._originalColorPostProcess.dispose(camera);
  65422. this._ssaoPostProcess.dispose(camera);
  65423. this._blurHPostProcess.dispose(camera);
  65424. this._blurVPostProcess.dispose(camera);
  65425. this._ssaoCombinePostProcess.dispose(camera);
  65426. }
  65427. this._randomTexture.dispose();
  65428. if (disableGeometryBufferRenderer)
  65429. this._scene.disableGeometryBufferRenderer();
  65430. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65431. _super.prototype.dispose.call(this);
  65432. };
  65433. // Private Methods
  65434. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65435. var _this = this;
  65436. this._samplerOffsets = [];
  65437. var expensive = this.expensiveBlur;
  65438. for (var i = -8; i < 8; i++) {
  65439. this._samplerOffsets.push(i * 2 + 0.5);
  65440. }
  65441. 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");
  65442. this._blurHPostProcess.onApply = function (effect) {
  65443. if (!_this._scene.activeCamera) {
  65444. return;
  65445. }
  65446. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65447. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65448. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65449. effect.setFloat("radius", _this.radius);
  65450. effect.setTexture("depthSampler", _this._depthTexture);
  65451. if (_this._firstUpdate) {
  65452. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65453. }
  65454. };
  65455. 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");
  65456. this._blurVPostProcess.onApply = function (effect) {
  65457. if (!_this._scene.activeCamera) {
  65458. return;
  65459. }
  65460. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65461. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65462. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65463. effect.setFloat("radius", _this.radius);
  65464. effect.setTexture("depthSampler", _this._depthTexture);
  65465. if (_this._firstUpdate) {
  65466. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65467. _this._firstUpdate = false;
  65468. }
  65469. };
  65470. };
  65471. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65472. this._firstUpdate = true;
  65473. _super.prototype._rebuild.call(this);
  65474. };
  65475. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65476. var numSamples = this.samples;
  65477. var result = [];
  65478. var vector, scale;
  65479. var rand = function (min, max) {
  65480. return Math.random() * (max - min) + min;
  65481. };
  65482. var i = 0;
  65483. while (i < numSamples) {
  65484. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65485. vector.normalize();
  65486. scale = i / numSamples;
  65487. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65488. vector.scaleInPlace(scale);
  65489. result.push(vector.x, vector.y, vector.z);
  65490. i++;
  65491. }
  65492. return result;
  65493. };
  65494. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65495. var _this = this;
  65496. var numSamples = this.samples;
  65497. this._sampleSphere = this._generateHemisphere();
  65498. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65499. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65500. "base", "range", "projection", "near", "far", "texelSize",
  65501. "xViewport", "yViewport", "maxZ", "minZAspect"
  65502. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65503. this._ssaoPostProcess.onApply = function (effect) {
  65504. if (_this._firstUpdate) {
  65505. effect.setArray3("sampleSphere", _this._sampleSphere);
  65506. effect.setFloat("randTextureTiles", 4.0);
  65507. }
  65508. if (!_this._scene.activeCamera) {
  65509. return;
  65510. }
  65511. effect.setFloat("samplesFactor", 1 / _this.samples);
  65512. effect.setFloat("totalStrength", _this.totalStrength);
  65513. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65514. effect.setFloat("radius", _this.radius);
  65515. effect.setFloat("maxZ", _this.maxZ);
  65516. effect.setFloat("minZAspect", _this.minZAspect);
  65517. effect.setFloat("base", _this.base);
  65518. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65519. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65520. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65521. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65522. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65523. effect.setTexture("textureSampler", _this._depthTexture);
  65524. effect.setTexture("normalSampler", _this._normalTexture);
  65525. effect.setTexture("randomSampler", _this._randomTexture);
  65526. };
  65527. };
  65528. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65529. var _this = this;
  65530. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65531. this._ssaoCombinePostProcess.onApply = function (effect) {
  65532. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65533. };
  65534. };
  65535. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65536. var size = 512;
  65537. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65538. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65539. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65540. var context = this._randomTexture.getContext();
  65541. var rand = function (min, max) {
  65542. return Math.random() * (max - min) + min;
  65543. };
  65544. var randVector = BABYLON.Vector3.Zero();
  65545. for (var x = 0; x < size; x++) {
  65546. for (var y = 0; y < size; y++) {
  65547. randVector.x = rand(0.0, 1.0);
  65548. randVector.y = rand(0.0, 1.0);
  65549. randVector.z = 0.0;
  65550. randVector.normalize();
  65551. randVector.scaleInPlace(255);
  65552. randVector.x = Math.floor(randVector.x);
  65553. randVector.y = Math.floor(randVector.y);
  65554. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65555. context.fillRect(x, y, 1, 1);
  65556. }
  65557. }
  65558. this._randomTexture.update(false);
  65559. };
  65560. __decorate([
  65561. BABYLON.serialize()
  65562. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65563. __decorate([
  65564. BABYLON.serialize()
  65565. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65566. __decorate([
  65567. BABYLON.serialize()
  65568. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65569. __decorate([
  65570. BABYLON.serialize("samples")
  65571. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65572. __decorate([
  65573. BABYLON.serialize("expensiveBlur")
  65574. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65575. __decorate([
  65576. BABYLON.serialize()
  65577. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65578. __decorate([
  65579. BABYLON.serialize()
  65580. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65581. return SSAO2RenderingPipeline;
  65582. }(BABYLON.PostProcessRenderPipeline));
  65583. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65584. })(BABYLON || (BABYLON = {}));
  65585. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65586. // BABYLON.JS Chromatic Aberration GLSL Shader
  65587. // Author: Olivier Guyot
  65588. // Separates very slightly R, G and B colors on the edges of the screen
  65589. // Inspired by Francois Tarlier & Martins Upitis
  65590. var BABYLON;
  65591. (function (BABYLON) {
  65592. var LensRenderingPipeline = /** @class */ (function (_super) {
  65593. __extends(LensRenderingPipeline, _super);
  65594. /**
  65595. * @constructor
  65596. *
  65597. * Effect parameters are as follow:
  65598. * {
  65599. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65600. * edge_blur: number; // from 0 to x (1 for realism)
  65601. * distortion: number; // from 0 to x (1 for realism)
  65602. * grain_amount: number; // from 0 to 1
  65603. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65604. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65605. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65606. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65607. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65608. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65609. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65610. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65611. * }
  65612. * Note: if an effect parameter is unset, effect is disabled
  65613. *
  65614. * @param {string} name - The rendering pipeline name
  65615. * @param {object} parameters - An object containing all parameters (see above)
  65616. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65617. * @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)
  65618. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65619. */
  65620. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65621. if (ratio === void 0) { ratio = 1.0; }
  65622. var _this = _super.call(this, scene.getEngine(), name) || this;
  65623. // Lens effects can be of the following:
  65624. // - chromatic aberration (slight shift of RGB colors)
  65625. // - blur on the edge of the lens
  65626. // - lens distortion
  65627. // - depth-of-field blur & highlights enhancing
  65628. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65629. // - grain effect (noise or custom texture)
  65630. // Two additional texture samplers are needed:
  65631. // - depth map (for depth-of-field)
  65632. // - grain texture
  65633. /**
  65634. * The chromatic aberration PostProcess id in the pipeline
  65635. * @type {string}
  65636. */
  65637. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65638. /**
  65639. * The highlights enhancing PostProcess id in the pipeline
  65640. * @type {string}
  65641. */
  65642. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65643. /**
  65644. * The depth-of-field PostProcess id in the pipeline
  65645. * @type {string}
  65646. */
  65647. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65648. _this._scene = scene;
  65649. // Fetch texture samplers
  65650. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65651. if (parameters.grain_texture) {
  65652. _this._grainTexture = parameters.grain_texture;
  65653. }
  65654. else {
  65655. _this._createGrainTexture();
  65656. }
  65657. // save parameters
  65658. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65659. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65660. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65661. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65662. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65663. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65664. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65665. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65666. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65667. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65668. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65669. // Create effects
  65670. _this._createChromaticAberrationPostProcess(ratio);
  65671. _this._createHighlightsPostProcess(ratio);
  65672. _this._createDepthOfFieldPostProcess(ratio / 4);
  65673. // Set up pipeline
  65674. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65675. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65676. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65677. if (_this._highlightsGain === -1) {
  65678. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65679. }
  65680. // Finish
  65681. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65682. if (cameras) {
  65683. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65684. }
  65685. return _this;
  65686. }
  65687. // public methods (self explanatory)
  65688. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65689. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65690. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65691. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65692. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65693. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65694. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65695. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65696. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65697. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65698. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65699. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65700. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65701. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65702. };
  65703. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65704. this._highlightsPostProcess.updateEffect();
  65705. };
  65706. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65707. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65708. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65709. this._highlightsGain = amount;
  65710. };
  65711. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65712. if (this._highlightsGain === -1) {
  65713. this._highlightsGain = 1.0;
  65714. }
  65715. this._highlightsThreshold = amount;
  65716. };
  65717. LensRenderingPipeline.prototype.disableHighlights = function () {
  65718. this._highlightsGain = -1;
  65719. };
  65720. /**
  65721. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65722. */
  65723. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65724. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65725. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65726. this._chromaticAberrationPostProcess = null;
  65727. this._highlightsPostProcess = null;
  65728. this._depthOfFieldPostProcess = null;
  65729. this._grainTexture.dispose();
  65730. if (disableDepthRender)
  65731. this._scene.disableDepthRenderer();
  65732. };
  65733. // colors shifting and distortion
  65734. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65735. var _this = this;
  65736. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65737. [], // samplers
  65738. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65739. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65740. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65741. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65742. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65743. };
  65744. };
  65745. // highlights enhancing
  65746. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65747. var _this = this;
  65748. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65749. [], // samplers
  65750. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65751. this._highlightsPostProcess.onApply = function (effect) {
  65752. effect.setFloat('gain', _this._highlightsGain);
  65753. effect.setFloat('threshold', _this._highlightsThreshold);
  65754. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65755. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65756. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65757. };
  65758. };
  65759. // colors shifting and distortion
  65760. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65761. var _this = this;
  65762. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65763. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65764. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65765. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65766. this._depthOfFieldPostProcess.onApply = function (effect) {
  65767. effect.setTexture("depthSampler", _this._depthTexture);
  65768. effect.setTexture("grainSampler", _this._grainTexture);
  65769. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65770. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65771. effect.setFloat('grain_amount', _this._grainAmount);
  65772. effect.setBool('blur_noise', _this._blurNoise);
  65773. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65774. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65775. effect.setFloat('distortion', _this._distortion);
  65776. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65777. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65778. effect.setFloat('aperture', _this._dofAperture);
  65779. effect.setFloat('darken', _this._dofDarken);
  65780. effect.setFloat('edge_blur', _this._edgeBlur);
  65781. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65782. if (_this._scene.activeCamera) {
  65783. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65784. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65785. }
  65786. };
  65787. };
  65788. // creates a black and white random noise texture, 512x512
  65789. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65790. var size = 512;
  65791. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65792. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65793. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65794. var context = this._grainTexture.getContext();
  65795. var rand = function (min, max) {
  65796. return Math.random() * (max - min) + min;
  65797. };
  65798. var value;
  65799. for (var x = 0; x < size; x++) {
  65800. for (var y = 0; y < size; y++) {
  65801. value = Math.floor(rand(0.42, 0.58) * 255);
  65802. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65803. context.fillRect(x, y, 1, 1);
  65804. }
  65805. }
  65806. this._grainTexture.update(false);
  65807. };
  65808. return LensRenderingPipeline;
  65809. }(BABYLON.PostProcessRenderPipeline));
  65810. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65811. })(BABYLON || (BABYLON = {}));
  65812. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65813. var BABYLON;
  65814. (function (BABYLON) {
  65815. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65816. __extends(StandardRenderingPipeline, _super);
  65817. /**
  65818. * @constructor
  65819. * @param {string} name - The rendering pipeline name
  65820. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65821. * @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)
  65822. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65823. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65824. */
  65825. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65826. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65827. var _this = _super.call(this, scene.getEngine(), name) || this;
  65828. _this.downSampleX4PostProcess = null;
  65829. _this.brightPassPostProcess = null;
  65830. _this.blurHPostProcesses = [];
  65831. _this.blurVPostProcesses = [];
  65832. _this.textureAdderPostProcess = null;
  65833. _this.volumetricLightPostProcess = null;
  65834. _this.volumetricLightSmoothXPostProcess = null;
  65835. _this.volumetricLightSmoothYPostProcess = null;
  65836. _this.volumetricLightMergePostProces = null;
  65837. _this.volumetricLightFinalPostProcess = null;
  65838. _this.luminancePostProcess = null;
  65839. _this.luminanceDownSamplePostProcesses = [];
  65840. _this.hdrPostProcess = null;
  65841. _this.textureAdderFinalPostProcess = null;
  65842. _this.lensFlareFinalPostProcess = null;
  65843. _this.hdrFinalPostProcess = null;
  65844. _this.lensFlarePostProcess = null;
  65845. _this.lensFlareComposePostProcess = null;
  65846. _this.motionBlurPostProcess = null;
  65847. _this.depthOfFieldPostProcess = null;
  65848. // Values
  65849. _this.brightThreshold = 1.0;
  65850. _this.blurWidth = 512.0;
  65851. _this.horizontalBlur = false;
  65852. _this.exposure = 1.0;
  65853. _this.lensTexture = null;
  65854. _this.volumetricLightCoefficient = 0.2;
  65855. _this.volumetricLightPower = 4.0;
  65856. _this.volumetricLightBlurScale = 64.0;
  65857. _this.sourceLight = null;
  65858. _this.hdrMinimumLuminance = 1.0;
  65859. _this.hdrDecreaseRate = 0.5;
  65860. _this.hdrIncreaseRate = 0.5;
  65861. _this.lensColorTexture = null;
  65862. _this.lensFlareStrength = 20.0;
  65863. _this.lensFlareGhostDispersal = 1.4;
  65864. _this.lensFlareHaloWidth = 0.7;
  65865. _this.lensFlareDistortionStrength = 16.0;
  65866. _this.lensStarTexture = null;
  65867. _this.lensFlareDirtTexture = null;
  65868. _this.depthOfFieldDistance = 10.0;
  65869. _this.depthOfFieldBlurWidth = 64.0;
  65870. _this.motionStrength = 1.0;
  65871. // IAnimatable
  65872. _this.animations = [];
  65873. _this._currentDepthOfFieldSource = null;
  65874. _this._hdrCurrentLuminance = 1.0;
  65875. // Getters and setters
  65876. _this._bloomEnabled = true;
  65877. _this._depthOfFieldEnabled = false;
  65878. _this._vlsEnabled = false;
  65879. _this._lensFlareEnabled = false;
  65880. _this._hdrEnabled = false;
  65881. _this._motionBlurEnabled = false;
  65882. _this._motionBlurSamples = 64.0;
  65883. _this._volumetricLightStepsCount = 50.0;
  65884. _this._cameras = cameras || [];
  65885. // Initialize
  65886. _this._scene = scene;
  65887. _this._basePostProcess = originalPostProcess;
  65888. _this._ratio = ratio;
  65889. // Misc
  65890. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65891. // Finish
  65892. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65893. _this._buildPipeline();
  65894. return _this;
  65895. }
  65896. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65897. get: function () {
  65898. return this._bloomEnabled;
  65899. },
  65900. set: function (enabled) {
  65901. if (this._bloomEnabled === enabled) {
  65902. return;
  65903. }
  65904. this._bloomEnabled = enabled;
  65905. this._buildPipeline();
  65906. },
  65907. enumerable: true,
  65908. configurable: true
  65909. });
  65910. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65911. get: function () {
  65912. return this._depthOfFieldEnabled;
  65913. },
  65914. set: function (enabled) {
  65915. if (this._depthOfFieldEnabled === enabled) {
  65916. return;
  65917. }
  65918. this._depthOfFieldEnabled = enabled;
  65919. this._buildPipeline();
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65925. get: function () {
  65926. return this._lensFlareEnabled;
  65927. },
  65928. set: function (enabled) {
  65929. if (this._lensFlareEnabled === enabled) {
  65930. return;
  65931. }
  65932. this._lensFlareEnabled = enabled;
  65933. this._buildPipeline();
  65934. },
  65935. enumerable: true,
  65936. configurable: true
  65937. });
  65938. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65939. get: function () {
  65940. return this._hdrEnabled;
  65941. },
  65942. set: function (enabled) {
  65943. if (this._hdrEnabled === enabled) {
  65944. return;
  65945. }
  65946. this._hdrEnabled = enabled;
  65947. this._buildPipeline();
  65948. },
  65949. enumerable: true,
  65950. configurable: true
  65951. });
  65952. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65953. get: function () {
  65954. return this._vlsEnabled;
  65955. },
  65956. set: function (enabled) {
  65957. if (this._vlsEnabled === enabled) {
  65958. return;
  65959. }
  65960. if (enabled) {
  65961. var geometry = this._scene.enableGeometryBufferRenderer();
  65962. if (!geometry) {
  65963. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65964. return;
  65965. }
  65966. }
  65967. this._vlsEnabled = enabled;
  65968. this._buildPipeline();
  65969. },
  65970. enumerable: true,
  65971. configurable: true
  65972. });
  65973. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65974. get: function () {
  65975. return this._motionBlurEnabled;
  65976. },
  65977. set: function (enabled) {
  65978. if (this._motionBlurEnabled === enabled) {
  65979. return;
  65980. }
  65981. this._motionBlurEnabled = enabled;
  65982. this._buildPipeline();
  65983. },
  65984. enumerable: true,
  65985. configurable: true
  65986. });
  65987. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65988. get: function () {
  65989. return this._volumetricLightStepsCount;
  65990. },
  65991. set: function (count) {
  65992. if (this.volumetricLightPostProcess) {
  65993. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65994. }
  65995. this._volumetricLightStepsCount = count;
  65996. },
  65997. enumerable: true,
  65998. configurable: true
  65999. });
  66000. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66001. get: function () {
  66002. return this._motionBlurSamples;
  66003. },
  66004. set: function (samples) {
  66005. if (this.motionBlurPostProcess) {
  66006. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66007. }
  66008. this._motionBlurSamples = samples;
  66009. },
  66010. enumerable: true,
  66011. configurable: true
  66012. });
  66013. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66014. var _this = this;
  66015. var ratio = this._ratio;
  66016. var scene = this._scene;
  66017. this._disposePostProcesses();
  66018. this._reset();
  66019. // Create pass post-process
  66020. if (!this._basePostProcess) {
  66021. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66022. this.originalPostProcess.onApply = function (effect) {
  66023. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66024. };
  66025. }
  66026. else {
  66027. this.originalPostProcess = this._basePostProcess;
  66028. }
  66029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66030. this._currentDepthOfFieldSource = this.originalPostProcess;
  66031. if (this._vlsEnabled) {
  66032. // Create volumetric light
  66033. this._createVolumetricLightPostProcess(scene, ratio);
  66034. // Create volumetric light final post-process
  66035. 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);
  66036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66037. }
  66038. if (this._bloomEnabled) {
  66039. // Create down sample X4 post-process
  66040. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66041. // Create bright pass post-process
  66042. this._createBrightPassPostProcess(scene, ratio / 2);
  66043. // Create gaussian blur post-processes (down sampling blurs)
  66044. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66045. // Create texture adder post-process
  66046. this._createTextureAdderPostProcess(scene, ratio);
  66047. // Create depth-of-field source post-process
  66048. 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);
  66049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66050. }
  66051. if (this._lensFlareEnabled) {
  66052. // Create lens flare post-process
  66053. this._createLensFlarePostProcess(scene, ratio);
  66054. // Create depth-of-field source post-process post lens-flare and disable it now
  66055. 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);
  66056. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66057. }
  66058. if (this._hdrEnabled) {
  66059. // Create luminance
  66060. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66061. // Create HDR
  66062. this._createHdrPostProcess(scene, ratio);
  66063. // Create depth-of-field source post-process post hdr and disable it now
  66064. 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);
  66065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66066. }
  66067. if (this._depthOfFieldEnabled) {
  66068. // Create gaussian blur used by depth-of-field
  66069. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66070. // Create depth-of-field post-process
  66071. this._createDepthOfFieldPostProcess(scene, ratio);
  66072. }
  66073. if (this._motionBlurEnabled) {
  66074. // Create motion blur post-process
  66075. this._createMotionBlurPostProcess(scene, ratio);
  66076. }
  66077. if (this._cameras !== null) {
  66078. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66079. }
  66080. };
  66081. // Down Sample X4 Post-Processs
  66082. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66083. var _this = this;
  66084. var downSampleX4Offsets = new Array(32);
  66085. 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);
  66086. this.downSampleX4PostProcess.onApply = function (effect) {
  66087. var id = 0;
  66088. var width = _this.downSampleX4PostProcess.width;
  66089. var height = _this.downSampleX4PostProcess.height;
  66090. for (var i = -2; i < 2; i++) {
  66091. for (var j = -2; j < 2; j++) {
  66092. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66093. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66094. id += 2;
  66095. }
  66096. }
  66097. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66098. };
  66099. // Add to pipeline
  66100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66101. };
  66102. // Brightpass Post-Process
  66103. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66104. var _this = this;
  66105. var brightOffsets = new Array(8);
  66106. 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);
  66107. this.brightPassPostProcess.onApply = function (effect) {
  66108. var sU = (1.0 / _this.brightPassPostProcess.width);
  66109. var sV = (1.0 / _this.brightPassPostProcess.height);
  66110. brightOffsets[0] = -0.5 * sU;
  66111. brightOffsets[1] = 0.5 * sV;
  66112. brightOffsets[2] = 0.5 * sU;
  66113. brightOffsets[3] = 0.5 * sV;
  66114. brightOffsets[4] = -0.5 * sU;
  66115. brightOffsets[5] = -0.5 * sV;
  66116. brightOffsets[6] = 0.5 * sU;
  66117. brightOffsets[7] = -0.5 * sV;
  66118. effect.setArray2("dsOffsets", brightOffsets);
  66119. effect.setFloat("brightThreshold", _this.brightThreshold);
  66120. };
  66121. // Add to pipeline
  66122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66123. };
  66124. // Create blur H&V post-processes
  66125. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66126. var _this = this;
  66127. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66128. var engine = scene.getEngine();
  66129. 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);
  66130. 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);
  66131. blurX.onActivateObservable.add(function () {
  66132. var dw = blurX.width / engine.getRenderWidth();
  66133. blurX.kernel = _this[blurWidthKey] * dw;
  66134. });
  66135. blurY.onActivateObservable.add(function () {
  66136. var dw = blurY.height / engine.getRenderHeight();
  66137. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66138. });
  66139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66141. this.blurHPostProcesses.push(blurX);
  66142. this.blurVPostProcesses.push(blurY);
  66143. };
  66144. // Create texture adder post-process
  66145. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66146. var _this = this;
  66147. 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);
  66148. this.textureAdderPostProcess.onApply = function (effect) {
  66149. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66150. effect.setTexture("lensSampler", _this.lensTexture);
  66151. effect.setFloat("exposure", _this.exposure);
  66152. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66153. };
  66154. // Add to pipeline
  66155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66156. };
  66157. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66158. var _this = this;
  66159. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66160. geometryRenderer.enablePosition = true;
  66161. var geometry = geometryRenderer.getGBuffer();
  66162. // Base post-process
  66163. 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));
  66164. var depthValues = BABYLON.Vector2.Zero();
  66165. this.volumetricLightPostProcess.onApply = function (effect) {
  66166. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66167. var generator = _this.sourceLight.getShadowGenerator();
  66168. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66169. effect.setTexture("positionSampler", geometry.textures[2]);
  66170. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66171. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66172. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66173. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66174. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66175. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66176. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66177. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66178. effect.setVector2("depthValues", depthValues);
  66179. }
  66180. };
  66181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66182. // Smooth
  66183. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66184. // Merge
  66185. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66186. this.volumetricLightMergePostProces.onApply = function (effect) {
  66187. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66188. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66189. };
  66190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66191. };
  66192. // Create luminance
  66193. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66194. var _this = this;
  66195. // Create luminance
  66196. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66197. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66198. var offsets = [];
  66199. this.luminancePostProcess.onApply = function (effect) {
  66200. var sU = (1.0 / _this.luminancePostProcess.width);
  66201. var sV = (1.0 / _this.luminancePostProcess.height);
  66202. offsets[0] = -0.5 * sU;
  66203. offsets[1] = 0.5 * sV;
  66204. offsets[2] = 0.5 * sU;
  66205. offsets[3] = 0.5 * sV;
  66206. offsets[4] = -0.5 * sU;
  66207. offsets[5] = -0.5 * sV;
  66208. offsets[6] = 0.5 * sU;
  66209. offsets[7] = -0.5 * sV;
  66210. effect.setArray2("lumOffsets", offsets);
  66211. };
  66212. // Add to pipeline
  66213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66214. // Create down sample luminance
  66215. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66216. var size = Math.pow(3, i);
  66217. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66218. if (i === 0) {
  66219. defines += "#define FINAL_DOWN_SAMPLER";
  66220. }
  66221. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66222. this.luminanceDownSamplePostProcesses.push(postProcess);
  66223. }
  66224. // Create callbacks and add effects
  66225. var lastLuminance = this.luminancePostProcess;
  66226. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66227. var downSampleOffsets = new Array(18);
  66228. pp.onApply = function (effect) {
  66229. if (!lastLuminance) {
  66230. return;
  66231. }
  66232. var id = 0;
  66233. for (var x = -1; x < 2; x++) {
  66234. for (var y = -1; y < 2; y++) {
  66235. downSampleOffsets[id] = x / lastLuminance.width;
  66236. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66237. id += 2;
  66238. }
  66239. }
  66240. effect.setArray2("dsOffsets", downSampleOffsets);
  66241. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66242. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66243. lastLuminance = _this.luminancePostProcess;
  66244. }
  66245. else {
  66246. lastLuminance = pp;
  66247. }
  66248. };
  66249. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66250. pp.onAfterRender = function (effect) {
  66251. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66252. 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);
  66253. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66254. };
  66255. }
  66256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66257. });
  66258. };
  66259. // Create HDR post-process
  66260. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66261. var _this = this;
  66262. 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);
  66263. var outputLiminance = 1;
  66264. var time = 0;
  66265. var lastTime = 0;
  66266. this.hdrPostProcess.onApply = function (effect) {
  66267. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66268. time += scene.getEngine().getDeltaTime();
  66269. if (outputLiminance < 0) {
  66270. outputLiminance = _this._hdrCurrentLuminance;
  66271. }
  66272. else {
  66273. var dt = (lastTime - time) / 1000.0;
  66274. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66275. outputLiminance += _this.hdrDecreaseRate * dt;
  66276. }
  66277. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66278. outputLiminance -= _this.hdrIncreaseRate * dt;
  66279. }
  66280. else {
  66281. outputLiminance = _this._hdrCurrentLuminance;
  66282. }
  66283. }
  66284. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66285. effect.setFloat("averageLuminance", outputLiminance);
  66286. lastTime = time;
  66287. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66288. };
  66289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66290. };
  66291. // Create lens flare post-process
  66292. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66293. var _this = this;
  66294. 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);
  66295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66296. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66297. 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);
  66298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66299. var resolution = new BABYLON.Vector2(0, 0);
  66300. // Lens flare
  66301. this.lensFlarePostProcess.onApply = function (effect) {
  66302. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66303. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66304. effect.setFloat("strength", _this.lensFlareStrength);
  66305. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66306. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66307. // Shift
  66308. resolution.x = _this.lensFlarePostProcess.width;
  66309. resolution.y = _this.lensFlarePostProcess.height;
  66310. effect.setVector2("resolution", resolution);
  66311. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66312. };
  66313. // Compose
  66314. 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);
  66315. 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);
  66316. this.lensFlareComposePostProcess.onApply = function (effect) {
  66317. if (!_this._scene.activeCamera) {
  66318. return;
  66319. }
  66320. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66321. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66322. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66323. // Lens start rotation matrix
  66324. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66325. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66326. 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));
  66327. camRot *= 4.0;
  66328. 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);
  66329. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66330. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66331. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66332. };
  66333. };
  66334. // Create depth-of-field post-process
  66335. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66336. var _this = this;
  66337. 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);
  66338. this.depthOfFieldPostProcess.onApply = function (effect) {
  66339. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66340. effect.setTexture("depthSampler", _this._getDepthTexture());
  66341. effect.setFloat("distance", _this.depthOfFieldDistance);
  66342. };
  66343. // Add to pipeline
  66344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66345. };
  66346. // Create motion blur post-process
  66347. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66348. var _this = this;
  66349. 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);
  66350. var motionScale = 0;
  66351. var prevViewProjection = BABYLON.Matrix.Identity();
  66352. var invViewProjection = BABYLON.Matrix.Identity();
  66353. var viewProjection = BABYLON.Matrix.Identity();
  66354. var screenSize = BABYLON.Vector2.Zero();
  66355. this.motionBlurPostProcess.onApply = function (effect) {
  66356. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66357. viewProjection.invertToRef(invViewProjection);
  66358. effect.setMatrix("inverseViewProjection", invViewProjection);
  66359. effect.setMatrix("prevViewProjection", prevViewProjection);
  66360. prevViewProjection = viewProjection;
  66361. screenSize.x = _this.motionBlurPostProcess.width;
  66362. screenSize.y = _this.motionBlurPostProcess.height;
  66363. effect.setVector2("screenSize", screenSize);
  66364. motionScale = scene.getEngine().getFps() / 60.0;
  66365. effect.setFloat("motionScale", motionScale);
  66366. effect.setFloat("motionStrength", _this.motionStrength);
  66367. effect.setTexture("depthSampler", _this._getDepthTexture());
  66368. };
  66369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66370. };
  66371. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66372. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66373. var renderer = this._scene.enableGeometryBufferRenderer();
  66374. return renderer.getGBuffer().textures[0];
  66375. }
  66376. return this._scene.enableDepthRenderer().getDepthMap();
  66377. };
  66378. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66379. for (var i = 0; i < this._cameras.length; i++) {
  66380. var camera = this._cameras[i];
  66381. if (this.originalPostProcess) {
  66382. this.originalPostProcess.dispose(camera);
  66383. }
  66384. if (this.downSampleX4PostProcess) {
  66385. this.downSampleX4PostProcess.dispose(camera);
  66386. }
  66387. if (this.brightPassPostProcess) {
  66388. this.brightPassPostProcess.dispose(camera);
  66389. }
  66390. if (this.textureAdderPostProcess) {
  66391. this.textureAdderPostProcess.dispose(camera);
  66392. }
  66393. if (this.textureAdderFinalPostProcess) {
  66394. this.textureAdderFinalPostProcess.dispose(camera);
  66395. }
  66396. if (this.volumetricLightPostProcess) {
  66397. this.volumetricLightPostProcess.dispose(camera);
  66398. }
  66399. if (this.volumetricLightSmoothXPostProcess) {
  66400. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66401. }
  66402. if (this.volumetricLightSmoothYPostProcess) {
  66403. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66404. }
  66405. if (this.volumetricLightMergePostProces) {
  66406. this.volumetricLightMergePostProces.dispose(camera);
  66407. }
  66408. if (this.volumetricLightFinalPostProcess) {
  66409. this.volumetricLightFinalPostProcess.dispose(camera);
  66410. }
  66411. if (this.lensFlarePostProcess) {
  66412. this.lensFlarePostProcess.dispose(camera);
  66413. }
  66414. if (this.lensFlareComposePostProcess) {
  66415. this.lensFlareComposePostProcess.dispose(camera);
  66416. }
  66417. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66418. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66419. }
  66420. if (this.luminancePostProcess) {
  66421. this.luminancePostProcess.dispose(camera);
  66422. }
  66423. if (this.hdrPostProcess) {
  66424. this.hdrPostProcess.dispose(camera);
  66425. }
  66426. if (this.hdrFinalPostProcess) {
  66427. this.hdrFinalPostProcess.dispose(camera);
  66428. }
  66429. if (this.depthOfFieldPostProcess) {
  66430. this.depthOfFieldPostProcess.dispose(camera);
  66431. }
  66432. if (this.motionBlurPostProcess) {
  66433. this.motionBlurPostProcess.dispose(camera);
  66434. }
  66435. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66436. this.blurHPostProcesses[j].dispose(camera);
  66437. }
  66438. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66439. this.blurVPostProcesses[j].dispose(camera);
  66440. }
  66441. }
  66442. this.originalPostProcess = null;
  66443. this.downSampleX4PostProcess = null;
  66444. this.brightPassPostProcess = null;
  66445. this.textureAdderPostProcess = null;
  66446. this.textureAdderFinalPostProcess = null;
  66447. this.volumetricLightPostProcess = null;
  66448. this.volumetricLightSmoothXPostProcess = null;
  66449. this.volumetricLightSmoothYPostProcess = null;
  66450. this.volumetricLightMergePostProces = null;
  66451. this.volumetricLightFinalPostProcess = null;
  66452. this.lensFlarePostProcess = null;
  66453. this.lensFlareComposePostProcess = null;
  66454. this.luminancePostProcess = null;
  66455. this.hdrPostProcess = null;
  66456. this.hdrFinalPostProcess = null;
  66457. this.depthOfFieldPostProcess = null;
  66458. this.motionBlurPostProcess = null;
  66459. this.luminanceDownSamplePostProcesses = [];
  66460. this.blurHPostProcesses = [];
  66461. this.blurVPostProcesses = [];
  66462. };
  66463. // Dispose
  66464. StandardRenderingPipeline.prototype.dispose = function () {
  66465. this._disposePostProcesses();
  66466. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66467. _super.prototype.dispose.call(this);
  66468. };
  66469. // Serialize rendering pipeline
  66470. StandardRenderingPipeline.prototype.serialize = function () {
  66471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66472. serializationObject.customType = "StandardRenderingPipeline";
  66473. return serializationObject;
  66474. };
  66475. /**
  66476. * Static members
  66477. */
  66478. // Parse serialized pipeline
  66479. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66480. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66481. };
  66482. // Luminance steps
  66483. StandardRenderingPipeline.LuminanceSteps = 6;
  66484. __decorate([
  66485. BABYLON.serialize()
  66486. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66487. __decorate([
  66488. BABYLON.serialize()
  66489. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66490. __decorate([
  66491. BABYLON.serialize()
  66492. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66493. __decorate([
  66494. BABYLON.serialize()
  66495. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66496. __decorate([
  66497. BABYLON.serializeAsTexture("lensTexture")
  66498. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66499. __decorate([
  66500. BABYLON.serialize()
  66501. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66502. __decorate([
  66503. BABYLON.serialize()
  66504. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66505. __decorate([
  66506. BABYLON.serialize()
  66507. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66508. __decorate([
  66509. BABYLON.serialize()
  66510. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66511. __decorate([
  66512. BABYLON.serialize()
  66513. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66514. __decorate([
  66515. BABYLON.serialize()
  66516. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66517. __decorate([
  66518. BABYLON.serializeAsTexture("lensColorTexture")
  66519. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66520. __decorate([
  66521. BABYLON.serialize()
  66522. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66523. __decorate([
  66524. BABYLON.serialize()
  66525. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66526. __decorate([
  66527. BABYLON.serialize()
  66528. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66529. __decorate([
  66530. BABYLON.serialize()
  66531. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66532. __decorate([
  66533. BABYLON.serializeAsTexture("lensStarTexture")
  66534. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66535. __decorate([
  66536. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66537. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66538. __decorate([
  66539. BABYLON.serialize()
  66540. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66541. __decorate([
  66542. BABYLON.serialize()
  66543. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66544. __decorate([
  66545. BABYLON.serialize()
  66546. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66547. __decorate([
  66548. BABYLON.serialize()
  66549. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66550. __decorate([
  66551. BABYLON.serialize()
  66552. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66553. __decorate([
  66554. BABYLON.serialize()
  66555. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66556. __decorate([
  66557. BABYLON.serialize()
  66558. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66559. __decorate([
  66560. BABYLON.serialize()
  66561. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66562. __decorate([
  66563. BABYLON.serialize()
  66564. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66565. __decorate([
  66566. BABYLON.serialize()
  66567. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66568. __decorate([
  66569. BABYLON.serialize()
  66570. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66571. __decorate([
  66572. BABYLON.serialize()
  66573. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66574. return StandardRenderingPipeline;
  66575. }(BABYLON.PostProcessRenderPipeline));
  66576. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66577. })(BABYLON || (BABYLON = {}));
  66578. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66579. var BABYLON;
  66580. (function (BABYLON) {
  66581. var FxaaPostProcess = /** @class */ (function (_super) {
  66582. __extends(FxaaPostProcess, _super);
  66583. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66584. if (camera === void 0) { camera = null; }
  66585. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66586. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66587. _this.onApplyObservable.add(function (effect) {
  66588. var texelSize = _this.texelSize;
  66589. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66590. });
  66591. return _this;
  66592. }
  66593. return FxaaPostProcess;
  66594. }(BABYLON.PostProcess));
  66595. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66596. })(BABYLON || (BABYLON = {}));
  66597. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66598. var BABYLON;
  66599. (function (BABYLON) {
  66600. /**
  66601. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66602. */
  66603. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66604. __extends(CircleOfConfusionPostProcess, _super);
  66605. /**
  66606. * Creates a new instance of @see CircleOfConfusionPostProcess
  66607. * @param name The name of the effect.
  66608. * @param scene The scene the effect belongs to.
  66609. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66610. * @param options The required width/height ratio to downsize to before computing the render pass.
  66611. * @param camera The camera to apply the render pass to.
  66612. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66613. * @param engine The engine which the post process will be applied. (default: current engine)
  66614. * @param reusable If the post process can be reused on the same frame. (default: false)
  66615. * @param textureType Type of textures used when performing the post process. (default: 0)
  66616. */
  66617. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66618. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66619. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66620. /**
  66621. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  66622. */
  66623. _this.lensSize = 50;
  66624. /**
  66625. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66626. */
  66627. _this.fStop = 1.4;
  66628. /**
  66629. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66630. */
  66631. _this.focusDistance = 2000;
  66632. /**
  66633. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66634. */
  66635. _this.focalLength = 50;
  66636. _this.onApplyObservable.add(function (effect) {
  66637. effect.setTexture("depthSampler", depthTexture);
  66638. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66639. var aperture = _this.lensSize / _this.fStop;
  66640. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66641. effect.setFloat('focusDistance', _this.focusDistance);
  66642. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66643. if (scene.activeCamera) {
  66644. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66645. }
  66646. });
  66647. return _this;
  66648. }
  66649. return CircleOfConfusionPostProcess;
  66650. }(BABYLON.PostProcess));
  66651. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66652. })(BABYLON || (BABYLON = {}));
  66653. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66654. var BABYLON;
  66655. (function (BABYLON) {
  66656. /**
  66657. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66658. */
  66659. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66660. __extends(DepthOfFieldMergePostProcess, _super);
  66661. /**
  66662. * Creates a new instance of @see CircleOfConfusionPostProcess
  66663. * @param name The name of the effect.
  66664. * @param original The non-blurred image to be modified
  66665. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66666. * @param blurSteps Incrimental bluring post processes.
  66667. * @param options The required width/height ratio to downsize to before computing the render pass.
  66668. * @param camera The camera to apply the render pass to.
  66669. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66670. * @param engine The engine which the post process will be applied. (default: current engine)
  66671. * @param reusable If the post process can be reused on the same frame. (default: false)
  66672. * @param textureType Type of textures used when performing the post process. (default: 0)
  66673. */
  66674. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66675. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66676. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66677. _this.onApplyObservable.add(function (effect) {
  66678. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66679. effect.setTextureFromPostProcess("originalSampler", original);
  66680. blurSteps.forEach(function (step, index) {
  66681. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66682. });
  66683. });
  66684. return _this;
  66685. }
  66686. return DepthOfFieldMergePostProcess;
  66687. }(BABYLON.PostProcess));
  66688. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66689. })(BABYLON || (BABYLON = {}));
  66690. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66691. var BABYLON;
  66692. (function (BABYLON) {
  66693. /**
  66694. * Specifies the level of max blur that should be applied when using the depth of field effect
  66695. */
  66696. var DepthOfFieldEffectBlurLevel;
  66697. (function (DepthOfFieldEffectBlurLevel) {
  66698. /**
  66699. * Subtle blur
  66700. */
  66701. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66702. /**
  66703. * Medium blur
  66704. */
  66705. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66706. /**
  66707. * Large blur
  66708. */
  66709. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66710. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66711. ;
  66712. /**
  66713. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66714. */
  66715. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66716. __extends(DepthOfFieldEffect, _super);
  66717. /**
  66718. * Creates a new instance of @see DepthOfFieldEffect
  66719. * @param scene The scene the effect belongs to.
  66720. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66721. */
  66722. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66723. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66724. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66725. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66726. // Enable and get current depth map
  66727. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66728. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66729. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66730. // Capture circle of confusion texture
  66731. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66732. _this._depthOfFieldPass.autoClear = false;
  66733. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  66734. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66735. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66736. _this._depthOfFieldBlurY = [];
  66737. _this._depthOfFieldBlurX = [];
  66738. var blurCount = 1;
  66739. var kernelSize = 15;
  66740. switch (blurLevel) {
  66741. case DepthOfFieldEffectBlurLevel.High: {
  66742. blurCount = 3;
  66743. kernelSize = 51;
  66744. break;
  66745. }
  66746. case DepthOfFieldEffectBlurLevel.Medium: {
  66747. blurCount = 2;
  66748. kernelSize = 31;
  66749. break;
  66750. }
  66751. default: {
  66752. kernelSize = 15;
  66753. blurCount = 1;
  66754. break;
  66755. }
  66756. }
  66757. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66758. for (var i = 0; i < blurCount; i++) {
  66759. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66760. blurY.autoClear = false;
  66761. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66762. blurX.autoClear = false;
  66763. _this._depthOfFieldBlurY.push(blurY);
  66764. _this._depthOfFieldBlurX.push(blurX);
  66765. }
  66766. // Merge blurred images with original image based on circleOfConfusion
  66767. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66768. _this._depthOfFieldMerge.autoClear = false;
  66769. // Set all post processes on the effect.
  66770. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66771. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66772. effects.push(_this._depthOfFieldBlurY[i]);
  66773. effects.push(_this._depthOfFieldBlurX[i]);
  66774. }
  66775. effects.push(_this._depthOfFieldMerge);
  66776. return effects;
  66777. }, true) || this;
  66778. return _this;
  66779. }
  66780. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66781. get: function () {
  66782. return this._circleOfConfusion.focalLength;
  66783. },
  66784. /**
  66785. * The focal the length of the camera used in the effect
  66786. */
  66787. set: function (value) {
  66788. this._circleOfConfusion.focalLength = value;
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66794. get: function () {
  66795. return this._circleOfConfusion.fStop;
  66796. },
  66797. /**
  66798. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66799. */
  66800. set: function (value) {
  66801. this._circleOfConfusion.fStop = value;
  66802. },
  66803. enumerable: true,
  66804. configurable: true
  66805. });
  66806. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66807. get: function () {
  66808. return this._circleOfConfusion.focusDistance;
  66809. },
  66810. /**
  66811. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66812. */
  66813. set: function (value) {
  66814. this._circleOfConfusion.focusDistance = value;
  66815. },
  66816. enumerable: true,
  66817. configurable: true
  66818. });
  66819. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66820. get: function () {
  66821. return this._circleOfConfusion.lensSize;
  66822. },
  66823. /**
  66824. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  66825. */
  66826. set: function (value) {
  66827. this._circleOfConfusion.lensSize = value;
  66828. },
  66829. enumerable: true,
  66830. configurable: true
  66831. });
  66832. /**
  66833. * Disposes each of the internal effects for a given camera.
  66834. * @param camera The camera to dispose the effect on.
  66835. */
  66836. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66837. this._depthOfFieldPass.dispose(camera);
  66838. this._circleOfConfusion.dispose(camera);
  66839. this._depthOfFieldBlurX.forEach(function (element) {
  66840. element.dispose(camera);
  66841. });
  66842. this._depthOfFieldBlurY.forEach(function (element) {
  66843. element.dispose(camera);
  66844. });
  66845. this._depthOfFieldMerge.dispose(camera);
  66846. };
  66847. return DepthOfFieldEffect;
  66848. }(BABYLON.PostProcessRenderEffect));
  66849. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66850. })(BABYLON || (BABYLON = {}));
  66851. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66852. var BABYLON;
  66853. (function (BABYLON) {
  66854. /**
  66855. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66856. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66857. */
  66858. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66859. __extends(DefaultRenderingPipeline, _super);
  66860. /**
  66861. * @constructor
  66862. * @param {string} name - The rendering pipeline name
  66863. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66864. * @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)
  66865. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66866. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66867. */
  66868. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66869. if (automaticBuild === void 0) { automaticBuild = true; }
  66870. var _this = _super.call(this, scene.getEngine(), name) || this;
  66871. /**
  66872. * ID of the pass post process used for bloom,
  66873. */
  66874. _this.PassPostProcessId = "PassPostProcessEffect";
  66875. /**
  66876. * ID of the highlight post process used for bloom,
  66877. */
  66878. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66879. /**
  66880. * ID of the blurX post process used for bloom,
  66881. */
  66882. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66883. /**
  66884. * ID of the blurY post process used for bloom,
  66885. */
  66886. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66887. /**
  66888. * ID of the copy back post process used for bloom,
  66889. */
  66890. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66891. /**
  66892. * ID of the image processing post process;
  66893. */
  66894. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66895. /**
  66896. * ID of the Fast Approximate Anti-Aliasing post process;
  66897. */
  66898. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66899. /**
  66900. * ID of the final merge post process;
  66901. */
  66902. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66903. /**
  66904. * Animations which can be used to tweak settings over a period of time
  66905. */
  66906. _this.animations = [];
  66907. // Values
  66908. _this._bloomEnabled = false;
  66909. _this._depthOfFieldEnabled = false;
  66910. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66911. _this._fxaaEnabled = false;
  66912. _this._imageProcessingEnabled = true;
  66913. _this._bloomScale = 0.6;
  66914. _this._buildAllowed = true;
  66915. /**
  66916. * Specifies the size of the bloom blur kernel, relative to the final output size
  66917. */
  66918. _this.bloomKernel = 64;
  66919. /**
  66920. * Specifies the weight of the bloom in the final rendering
  66921. */
  66922. _this._bloomWeight = 0.15;
  66923. _this._cameras = cameras || [];
  66924. _this._buildAllowed = automaticBuild;
  66925. // Initialize
  66926. _this._scene = scene;
  66927. var caps = _this._scene.getEngine().getCaps();
  66928. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66929. // Misc
  66930. if (_this._hdr) {
  66931. if (caps.textureHalfFloatRender) {
  66932. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66933. }
  66934. else if (caps.textureFloatRender) {
  66935. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66936. }
  66937. }
  66938. else {
  66939. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66940. }
  66941. // Attach
  66942. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66943. _this._buildPipeline();
  66944. return _this;
  66945. }
  66946. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66947. get: function () {
  66948. return this._bloomWeight;
  66949. },
  66950. /**
  66951. * The strength of the bloom.
  66952. */
  66953. set: function (value) {
  66954. if (this._bloomWeight === value) {
  66955. return;
  66956. }
  66957. this._bloomWeight = value;
  66958. if (this._hdr && this.copyBack) {
  66959. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66960. }
  66961. },
  66962. enumerable: true,
  66963. configurable: true
  66964. });
  66965. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66966. get: function () {
  66967. return this._bloomScale;
  66968. },
  66969. /**
  66970. * The scale of the bloom, lower value will provide better performance.
  66971. */
  66972. set: function (value) {
  66973. if (this._bloomScale === value) {
  66974. return;
  66975. }
  66976. this._bloomScale = value;
  66977. this._buildPipeline();
  66978. },
  66979. enumerable: true,
  66980. configurable: true
  66981. });
  66982. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66983. get: function () {
  66984. return this._bloomEnabled;
  66985. },
  66986. /**
  66987. * Enable or disable the bloom from the pipeline
  66988. */
  66989. set: function (enabled) {
  66990. if (this._bloomEnabled === enabled) {
  66991. return;
  66992. }
  66993. this._bloomEnabled = enabled;
  66994. this._buildPipeline();
  66995. },
  66996. enumerable: true,
  66997. configurable: true
  66998. });
  66999. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67000. /**
  67001. * If the depth of field is enabled.
  67002. */
  67003. get: function () {
  67004. return this._depthOfFieldEnabled;
  67005. },
  67006. set: function (enabled) {
  67007. if (this._depthOfFieldEnabled === enabled) {
  67008. return;
  67009. }
  67010. this._depthOfFieldEnabled = enabled;
  67011. this._buildPipeline();
  67012. },
  67013. enumerable: true,
  67014. configurable: true
  67015. });
  67016. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67017. /**
  67018. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67019. */
  67020. get: function () {
  67021. return this._depthOfFieldBlurLevel;
  67022. },
  67023. set: function (value) {
  67024. if (this._depthOfFieldBlurLevel === value) {
  67025. return;
  67026. }
  67027. this._depthOfFieldBlurLevel = value;
  67028. this._buildPipeline();
  67029. },
  67030. enumerable: true,
  67031. configurable: true
  67032. });
  67033. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67034. get: function () {
  67035. return this._fxaaEnabled;
  67036. },
  67037. /**
  67038. * If the anti aliasing is enabled.
  67039. */
  67040. set: function (enabled) {
  67041. if (this._fxaaEnabled === enabled) {
  67042. return;
  67043. }
  67044. this._fxaaEnabled = enabled;
  67045. this._buildPipeline();
  67046. },
  67047. enumerable: true,
  67048. configurable: true
  67049. });
  67050. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67051. get: function () {
  67052. return this._imageProcessingEnabled;
  67053. },
  67054. /**
  67055. * If image processing is enabled.
  67056. */
  67057. set: function (enabled) {
  67058. if (this._imageProcessingEnabled === enabled) {
  67059. return;
  67060. }
  67061. this._imageProcessingEnabled = enabled;
  67062. this._buildPipeline();
  67063. },
  67064. enumerable: true,
  67065. configurable: true
  67066. });
  67067. /**
  67068. * Force the compilation of the entire pipeline.
  67069. */
  67070. DefaultRenderingPipeline.prototype.prepare = function () {
  67071. var previousState = this._buildAllowed;
  67072. this._buildAllowed = true;
  67073. this._buildPipeline();
  67074. this._buildAllowed = previousState;
  67075. };
  67076. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67077. var _this = this;
  67078. if (!this._buildAllowed) {
  67079. return;
  67080. }
  67081. var engine = this._scene.getEngine();
  67082. this._disposePostProcesses();
  67083. this._reset();
  67084. if (this.depthOfFieldEnabled) {
  67085. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67086. this.addEffect(this.depthOfField);
  67087. }
  67088. if (this.bloomEnabled) {
  67089. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67090. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67091. if (!this._hdr) {
  67092. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67093. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67094. this.highlights.autoClear = false;
  67095. this.highlights.alwaysForcePOT = true;
  67096. }
  67097. 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);
  67098. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67099. this.blurX.alwaysForcePOT = true;
  67100. this.blurX.autoClear = false;
  67101. this.blurX.onActivateObservable.add(function () {
  67102. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67103. _this.blurX.kernel = _this.bloomKernel * dw;
  67104. });
  67105. 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);
  67106. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67107. this.blurY.alwaysForcePOT = true;
  67108. this.blurY.autoClear = false;
  67109. this.blurY.onActivateObservable.add(function () {
  67110. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67111. _this.blurY.kernel = _this.bloomKernel * dh;
  67112. });
  67113. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67114. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67115. this.copyBack.alwaysForcePOT = true;
  67116. if (this._hdr) {
  67117. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67118. var w = this.bloomWeight;
  67119. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67120. }
  67121. else {
  67122. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67123. }
  67124. this.copyBack.autoClear = false;
  67125. }
  67126. if (this._imageProcessingEnabled) {
  67127. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67128. if (this._hdr) {
  67129. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67130. }
  67131. else {
  67132. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67133. }
  67134. }
  67135. if (this.fxaaEnabled) {
  67136. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67137. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67138. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67139. }
  67140. else if (this._hdr && this.imageProcessing) {
  67141. this.finalMerge = this.imageProcessing;
  67142. }
  67143. else {
  67144. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67145. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67146. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67147. }
  67148. if (this.bloomEnabled) {
  67149. if (this._hdr) {
  67150. this.copyBack.shareOutputWith(this.blurX);
  67151. if (this.imageProcessing) {
  67152. this.imageProcessing.shareOutputWith(this.pass);
  67153. this.imageProcessing.autoClear = false;
  67154. }
  67155. else if (this.fxaa) {
  67156. this.fxaa.shareOutputWith(this.pass);
  67157. }
  67158. else {
  67159. this.finalMerge.shareOutputWith(this.pass);
  67160. }
  67161. }
  67162. else {
  67163. if (this.fxaa) {
  67164. this.fxaa.shareOutputWith(this.pass);
  67165. }
  67166. else {
  67167. this.finalMerge.shareOutputWith(this.pass);
  67168. }
  67169. }
  67170. }
  67171. if (this._cameras !== null) {
  67172. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67173. }
  67174. };
  67175. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67176. for (var i = 0; i < this._cameras.length; i++) {
  67177. var camera = this._cameras[i];
  67178. if (this.pass) {
  67179. this.pass.dispose(camera);
  67180. }
  67181. if (this.highlights) {
  67182. this.highlights.dispose(camera);
  67183. }
  67184. if (this.blurX) {
  67185. this.blurX.dispose(camera);
  67186. }
  67187. if (this.blurY) {
  67188. this.blurY.dispose(camera);
  67189. }
  67190. if (this.copyBack) {
  67191. this.copyBack.dispose(camera);
  67192. }
  67193. if (this.imageProcessing) {
  67194. this.imageProcessing.dispose(camera);
  67195. }
  67196. if (this.fxaa) {
  67197. this.fxaa.dispose(camera);
  67198. }
  67199. if (this.finalMerge) {
  67200. this.finalMerge.dispose(camera);
  67201. }
  67202. if (this.depthOfField) {
  67203. this.depthOfField.disposeEffects(camera);
  67204. }
  67205. }
  67206. this.pass = null;
  67207. this.highlights = null;
  67208. this.blurX = null;
  67209. this.blurY = null;
  67210. this.copyBack = null;
  67211. this.imageProcessing = null;
  67212. this.fxaa = null;
  67213. this.finalMerge = null;
  67214. this.depthOfField = null;
  67215. };
  67216. /**
  67217. * Dispose of the pipeline and stop all post processes
  67218. */
  67219. DefaultRenderingPipeline.prototype.dispose = function () {
  67220. this._disposePostProcesses();
  67221. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67222. _super.prototype.dispose.call(this);
  67223. };
  67224. /**
  67225. * Serialize the rendering pipeline (Used when exporting)
  67226. * @returns the serialized object
  67227. */
  67228. DefaultRenderingPipeline.prototype.serialize = function () {
  67229. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67230. serializationObject.customType = "DefaultRenderingPipeline";
  67231. return serializationObject;
  67232. };
  67233. /**
  67234. * Parse the serialized pipeline
  67235. * @param source Source pipeline.
  67236. * @param scene The scene to load the pipeline to.
  67237. * @param rootUrl The URL of the serialized pipeline.
  67238. * @returns An instantiated pipeline from the serialized object.
  67239. */
  67240. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67241. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67242. };
  67243. __decorate([
  67244. BABYLON.serialize()
  67245. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67246. __decorate([
  67247. BABYLON.serialize()
  67248. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67249. __decorate([
  67250. BABYLON.serialize()
  67251. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67252. __decorate([
  67253. BABYLON.serialize()
  67254. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67255. __decorate([
  67256. BABYLON.serialize()
  67257. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67258. __decorate([
  67259. BABYLON.serialize()
  67260. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67261. __decorate([
  67262. BABYLON.serialize()
  67263. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67264. __decorate([
  67265. BABYLON.serialize()
  67266. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67267. __decorate([
  67268. BABYLON.serialize()
  67269. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67270. __decorate([
  67271. BABYLON.serialize()
  67272. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67273. return DefaultRenderingPipeline;
  67274. }(BABYLON.PostProcessRenderPipeline));
  67275. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67276. })(BABYLON || (BABYLON = {}));
  67277. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67278. var BABYLON;
  67279. (function (BABYLON) {
  67280. /**
  67281. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67282. */
  67283. var GeometryBufferRenderer = /** @class */ (function () {
  67284. /**
  67285. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67286. * @param scene The scene the buffer belongs to
  67287. * @param ratio How big is the buffer related to the main canvas.
  67288. */
  67289. function GeometryBufferRenderer(scene, ratio) {
  67290. if (ratio === void 0) { ratio = 1; }
  67291. this._enablePosition = false;
  67292. this._scene = scene;
  67293. this._ratio = ratio;
  67294. // Render target
  67295. this._createRenderTargets();
  67296. }
  67297. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67298. /**
  67299. * Set the render list (meshes to be rendered) used in the G buffer.
  67300. */
  67301. set: function (meshes) {
  67302. this._multiRenderTarget.renderList = meshes;
  67303. },
  67304. enumerable: true,
  67305. configurable: true
  67306. });
  67307. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67308. /**
  67309. * Gets wether or not G buffer are supported by the running hardware.
  67310. * This requires draw buffer supports
  67311. */
  67312. get: function () {
  67313. return this._multiRenderTarget.isSupported;
  67314. },
  67315. enumerable: true,
  67316. configurable: true
  67317. });
  67318. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67319. /**
  67320. * Gets wether or not position are enabled for the G buffer.
  67321. */
  67322. get: function () {
  67323. return this._enablePosition;
  67324. },
  67325. /**
  67326. * Sets wether or not position are enabled for the G buffer.
  67327. */
  67328. set: function (enable) {
  67329. this._enablePosition = enable;
  67330. this.dispose();
  67331. this._createRenderTargets();
  67332. },
  67333. enumerable: true,
  67334. configurable: true
  67335. });
  67336. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67337. /**
  67338. * Gets the scene associated with the buffer.
  67339. */
  67340. get: function () {
  67341. return this._scene;
  67342. },
  67343. enumerable: true,
  67344. configurable: true
  67345. });
  67346. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67347. /**
  67348. * Gets the ratio used by the buffer during its creation.
  67349. * How big is the buffer related to the main canvas.
  67350. */
  67351. get: function () {
  67352. return this._ratio;
  67353. },
  67354. enumerable: true,
  67355. configurable: true
  67356. });
  67357. /**
  67358. * Checks wether everything is ready to render a submesh to the G buffer.
  67359. * @param subMesh the submesh to check readiness for
  67360. * @param useInstances is the mesh drawn using instance or not
  67361. * @returns true if ready otherwise false
  67362. */
  67363. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67364. var material = subMesh.getMaterial();
  67365. if (material && material.disableDepthWrite) {
  67366. return false;
  67367. }
  67368. var defines = [];
  67369. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67370. var mesh = subMesh.getMesh();
  67371. // Alpha test
  67372. if (material && material.needAlphaTesting()) {
  67373. defines.push("#define ALPHATEST");
  67374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67375. attribs.push(BABYLON.VertexBuffer.UVKind);
  67376. defines.push("#define UV1");
  67377. }
  67378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67380. defines.push("#define UV2");
  67381. }
  67382. }
  67383. // Buffers
  67384. if (this._enablePosition) {
  67385. defines.push("#define POSITION");
  67386. }
  67387. // Bones
  67388. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67389. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67390. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67391. if (mesh.numBoneInfluencers > 4) {
  67392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67394. }
  67395. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67396. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67397. }
  67398. else {
  67399. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67400. }
  67401. // Instances
  67402. if (useInstances) {
  67403. defines.push("#define INSTANCES");
  67404. attribs.push("world0");
  67405. attribs.push("world1");
  67406. attribs.push("world2");
  67407. attribs.push("world3");
  67408. }
  67409. // Get correct effect
  67410. var join = defines.join("\n");
  67411. if (this._cachedDefines !== join) {
  67412. this._cachedDefines = join;
  67413. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67414. }
  67415. return this._effect.isReady();
  67416. };
  67417. /**
  67418. * Gets the current underlying G Buffer.
  67419. * @returns the buffer
  67420. */
  67421. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67422. return this._multiRenderTarget;
  67423. };
  67424. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67425. /**
  67426. * Gets the number of samples used to render the buffer (anti aliasing).
  67427. */
  67428. get: function () {
  67429. return this._multiRenderTarget.samples;
  67430. },
  67431. /**
  67432. * Sets the number of samples used to render the buffer (anti aliasing).
  67433. */
  67434. set: function (value) {
  67435. this._multiRenderTarget.samples = value;
  67436. },
  67437. enumerable: true,
  67438. configurable: true
  67439. });
  67440. /**
  67441. * Disposes the renderer and frees up associated resources.
  67442. */
  67443. GeometryBufferRenderer.prototype.dispose = function () {
  67444. this.getGBuffer().dispose();
  67445. };
  67446. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67447. var _this = this;
  67448. var engine = this._scene.getEngine();
  67449. var count = this._enablePosition ? 3 : 2;
  67450. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  67451. if (!this.isSupported) {
  67452. return;
  67453. }
  67454. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67455. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67456. this._multiRenderTarget.refreshRate = 1;
  67457. this._multiRenderTarget.renderParticles = false;
  67458. this._multiRenderTarget.renderList = null;
  67459. // set default depth value to 1.0 (far away)
  67460. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67461. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67462. });
  67463. // Custom render function
  67464. var renderSubMesh = function (subMesh) {
  67465. var mesh = subMesh.getRenderingMesh();
  67466. var scene = _this._scene;
  67467. var engine = scene.getEngine();
  67468. var material = subMesh.getMaterial();
  67469. if (!material) {
  67470. return;
  67471. }
  67472. // Culling
  67473. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67474. // Managing instances
  67475. var batch = mesh._getInstancesRenderList(subMesh._id);
  67476. if (batch.mustReturn) {
  67477. return;
  67478. }
  67479. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67480. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67481. engine.enableEffect(_this._effect);
  67482. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67483. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67484. _this._effect.setMatrix("view", scene.getViewMatrix());
  67485. // Alpha test
  67486. if (material && material.needAlphaTesting()) {
  67487. var alphaTexture = material.getAlphaTestTexture();
  67488. if (alphaTexture) {
  67489. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67490. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67491. }
  67492. }
  67493. // Bones
  67494. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67495. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67496. }
  67497. // Draw
  67498. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67499. }
  67500. };
  67501. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67502. var index;
  67503. if (depthOnlySubMeshes.length) {
  67504. engine.setColorWrite(false);
  67505. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67506. renderSubMesh(depthOnlySubMeshes.data[index]);
  67507. }
  67508. engine.setColorWrite(true);
  67509. }
  67510. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67511. renderSubMesh(opaqueSubMeshes.data[index]);
  67512. }
  67513. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67514. renderSubMesh(alphaTestSubMeshes.data[index]);
  67515. }
  67516. };
  67517. };
  67518. return GeometryBufferRenderer;
  67519. }());
  67520. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67521. })(BABYLON || (BABYLON = {}));
  67522. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67523. var BABYLON;
  67524. (function (BABYLON) {
  67525. var RefractionPostProcess = /** @class */ (function (_super) {
  67526. __extends(RefractionPostProcess, _super);
  67527. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67528. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67529. _this.color = color;
  67530. _this.depth = depth;
  67531. _this.colorLevel = colorLevel;
  67532. _this._ownRefractionTexture = true;
  67533. _this.onActivateObservable.add(function (cam) {
  67534. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67535. });
  67536. _this.onApplyObservable.add(function (effect) {
  67537. effect.setColor3("baseColor", _this.color);
  67538. effect.setFloat("depth", _this.depth);
  67539. effect.setFloat("colorLevel", _this.colorLevel);
  67540. effect.setTexture("refractionSampler", _this._refTexture);
  67541. });
  67542. return _this;
  67543. }
  67544. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  67545. /**
  67546. * Gets or sets the refraction texture
  67547. * Please note that you are responsible for disposing the texture if you set it manually
  67548. */
  67549. get: function () {
  67550. return this._refTexture;
  67551. },
  67552. set: function (value) {
  67553. if (this._refTexture && this._ownRefractionTexture) {
  67554. this._refTexture.dispose();
  67555. }
  67556. this._refTexture = value;
  67557. this._ownRefractionTexture = false;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. // Methods
  67563. RefractionPostProcess.prototype.dispose = function (camera) {
  67564. if (this._refTexture && this._ownRefractionTexture) {
  67565. this._refTexture.dispose();
  67566. this._refTexture = null;
  67567. }
  67568. _super.prototype.dispose.call(this, camera);
  67569. };
  67570. return RefractionPostProcess;
  67571. }(BABYLON.PostProcess));
  67572. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67573. })(BABYLON || (BABYLON = {}));
  67574. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67575. var BABYLON;
  67576. (function (BABYLON) {
  67577. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67578. __extends(BlackAndWhitePostProcess, _super);
  67579. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67580. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67581. _this.degree = 1;
  67582. _this.onApplyObservable.add(function (effect) {
  67583. effect.setFloat("degree", _this.degree);
  67584. });
  67585. return _this;
  67586. }
  67587. return BlackAndWhitePostProcess;
  67588. }(BABYLON.PostProcess));
  67589. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67590. })(BABYLON || (BABYLON = {}));
  67591. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67592. var BABYLON;
  67593. (function (BABYLON) {
  67594. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67595. __extends(ConvolutionPostProcess, _super);
  67596. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67597. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67598. _this.kernel = kernel;
  67599. _this.onApply = function (effect) {
  67600. effect.setFloat2("screenSize", _this.width, _this.height);
  67601. effect.setArray("kernel", _this.kernel);
  67602. };
  67603. return _this;
  67604. }
  67605. // Statics
  67606. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67607. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67608. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67609. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67610. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67611. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67612. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67613. return ConvolutionPostProcess;
  67614. }(BABYLON.PostProcess));
  67615. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67616. })(BABYLON || (BABYLON = {}));
  67617. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67618. var BABYLON;
  67619. (function (BABYLON) {
  67620. var FilterPostProcess = /** @class */ (function (_super) {
  67621. __extends(FilterPostProcess, _super);
  67622. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67623. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67624. _this.kernelMatrix = kernelMatrix;
  67625. _this.onApply = function (effect) {
  67626. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67627. };
  67628. return _this;
  67629. }
  67630. return FilterPostProcess;
  67631. }(BABYLON.PostProcess));
  67632. BABYLON.FilterPostProcess = FilterPostProcess;
  67633. })(BABYLON || (BABYLON = {}));
  67634. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67635. var BABYLON;
  67636. (function (BABYLON) {
  67637. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67638. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67639. __extends(VolumetricLightScatteringPostProcess, _super);
  67640. /**
  67641. * @constructor
  67642. * @param {string} name - The post-process name
  67643. * @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)
  67644. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67645. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67646. * @param {number} samples - The post-process quality, default 100
  67647. * @param {number} samplingMode - The post-process filtering mode
  67648. * @param {BABYLON.Engine} engine - The babylon engine
  67649. * @param {boolean} reusable - If the post-process is reusable
  67650. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67651. */
  67652. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67653. if (samples === void 0) { samples = 100; }
  67654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67655. 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;
  67656. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67657. /**
  67658. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67659. * @type {Vector3}
  67660. */
  67661. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67662. /**
  67663. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67664. * @type {boolean}
  67665. */
  67666. _this.useCustomMeshPosition = false;
  67667. /**
  67668. * If the post-process should inverse the light scattering direction
  67669. * @type {boolean}
  67670. */
  67671. _this.invert = true;
  67672. /**
  67673. * Array containing the excluded meshes not rendered in the internal pass
  67674. */
  67675. _this.excludedMeshes = new Array();
  67676. /**
  67677. * Controls the overall intensity of the post-process
  67678. * @type {number}
  67679. */
  67680. _this.exposure = 0.3;
  67681. /**
  67682. * Dissipates each sample's contribution in range [0, 1]
  67683. * @type {number}
  67684. */
  67685. _this.decay = 0.96815;
  67686. /**
  67687. * Controls the overall intensity of each sample
  67688. * @type {number}
  67689. */
  67690. _this.weight = 0.58767;
  67691. /**
  67692. * Controls the density of each sample
  67693. * @type {number}
  67694. */
  67695. _this.density = 0.926;
  67696. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67697. engine = scene.getEngine();
  67698. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67699. // Configure mesh
  67700. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67701. // Configure
  67702. _this._createPass(scene, ratio.passRatio || ratio);
  67703. _this.onActivate = function (camera) {
  67704. if (!_this.isSupported) {
  67705. _this.dispose(camera);
  67706. }
  67707. _this.onActivate = null;
  67708. };
  67709. _this.onApplyObservable.add(function (effect) {
  67710. _this._updateMeshScreenCoordinates(scene);
  67711. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67712. effect.setFloat("exposure", _this.exposure);
  67713. effect.setFloat("decay", _this.decay);
  67714. effect.setFloat("weight", _this.weight);
  67715. effect.setFloat("density", _this.density);
  67716. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67717. });
  67718. return _this;
  67719. }
  67720. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67721. get: function () {
  67722. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67723. return false;
  67724. },
  67725. set: function (useDiffuseColor) {
  67726. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67727. },
  67728. enumerable: true,
  67729. configurable: true
  67730. });
  67731. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67732. return "VolumetricLightScatteringPostProcess";
  67733. };
  67734. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67735. var mesh = subMesh.getMesh();
  67736. // Render this.mesh as default
  67737. if (mesh === this.mesh && mesh.material) {
  67738. return mesh.material.isReady(mesh);
  67739. }
  67740. var defines = [];
  67741. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67742. var material = subMesh.getMaterial();
  67743. // Alpha test
  67744. if (material) {
  67745. if (material.needAlphaTesting()) {
  67746. defines.push("#define ALPHATEST");
  67747. }
  67748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67749. attribs.push(BABYLON.VertexBuffer.UVKind);
  67750. defines.push("#define UV1");
  67751. }
  67752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67753. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67754. defines.push("#define UV2");
  67755. }
  67756. }
  67757. // Bones
  67758. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67759. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67760. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67761. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67762. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67763. }
  67764. else {
  67765. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67766. }
  67767. // Instances
  67768. if (useInstances) {
  67769. defines.push("#define INSTANCES");
  67770. attribs.push("world0");
  67771. attribs.push("world1");
  67772. attribs.push("world2");
  67773. attribs.push("world3");
  67774. }
  67775. // Get correct effect
  67776. var join = defines.join("\n");
  67777. if (this._cachedDefines !== join) {
  67778. this._cachedDefines = join;
  67779. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67780. }
  67781. return this._volumetricLightScatteringPass.isReady();
  67782. };
  67783. /**
  67784. * Sets the new light position for light scattering effect
  67785. * @param {BABYLON.Vector3} The new custom light position
  67786. */
  67787. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67788. this.customMeshPosition = position;
  67789. };
  67790. /**
  67791. * Returns the light position for light scattering effect
  67792. * @return {BABYLON.Vector3} The custom light position
  67793. */
  67794. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67795. return this.customMeshPosition;
  67796. };
  67797. /**
  67798. * Disposes the internal assets and detaches the post-process from the camera
  67799. */
  67800. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67801. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67802. if (rttIndex !== -1) {
  67803. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67804. }
  67805. this._volumetricLightScatteringRTT.dispose();
  67806. _super.prototype.dispose.call(this, camera);
  67807. };
  67808. /**
  67809. * Returns the render target texture used by the post-process
  67810. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67811. */
  67812. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67813. return this._volumetricLightScatteringRTT;
  67814. };
  67815. // Private methods
  67816. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67817. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67818. return true;
  67819. }
  67820. return false;
  67821. };
  67822. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67823. var _this = this;
  67824. var engine = scene.getEngine();
  67825. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67826. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67827. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67828. this._volumetricLightScatteringRTT.renderList = null;
  67829. this._volumetricLightScatteringRTT.renderParticles = false;
  67830. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  67831. var camera = this.getCamera();
  67832. if (camera) {
  67833. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67834. }
  67835. else {
  67836. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67837. }
  67838. // Custom render function for submeshes
  67839. var renderSubMesh = function (subMesh) {
  67840. var mesh = subMesh.getRenderingMesh();
  67841. if (_this._meshExcluded(mesh)) {
  67842. return;
  67843. }
  67844. var material = subMesh.getMaterial();
  67845. if (!material) {
  67846. return;
  67847. }
  67848. var scene = mesh.getScene();
  67849. var engine = scene.getEngine();
  67850. // Culling
  67851. engine.setState(material.backFaceCulling);
  67852. // Managing instances
  67853. var batch = mesh._getInstancesRenderList(subMesh._id);
  67854. if (batch.mustReturn) {
  67855. return;
  67856. }
  67857. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67858. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67859. var effect = _this._volumetricLightScatteringPass;
  67860. if (mesh === _this.mesh) {
  67861. if (subMesh.effect) {
  67862. effect = subMesh.effect;
  67863. }
  67864. else {
  67865. effect = material.getEffect();
  67866. }
  67867. }
  67868. engine.enableEffect(effect);
  67869. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67870. if (mesh === _this.mesh) {
  67871. material.bind(mesh.getWorldMatrix(), mesh);
  67872. }
  67873. else {
  67874. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67875. // Alpha test
  67876. if (material && material.needAlphaTesting()) {
  67877. var alphaTexture = material.getAlphaTestTexture();
  67878. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67879. if (alphaTexture) {
  67880. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67881. }
  67882. }
  67883. // Bones
  67884. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67885. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67886. }
  67887. }
  67888. // Draw
  67889. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67890. }
  67891. };
  67892. // Render target texture callbacks
  67893. var savedSceneClearColor;
  67894. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67895. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67896. savedSceneClearColor = scene.clearColor;
  67897. scene.clearColor = sceneClearColor;
  67898. });
  67899. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67900. scene.clearColor = savedSceneClearColor;
  67901. });
  67902. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67903. var engine = scene.getEngine();
  67904. var index;
  67905. if (depthOnlySubMeshes.length) {
  67906. engine.setColorWrite(false);
  67907. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67908. renderSubMesh(depthOnlySubMeshes.data[index]);
  67909. }
  67910. engine.setColorWrite(true);
  67911. }
  67912. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67913. renderSubMesh(opaqueSubMeshes.data[index]);
  67914. }
  67915. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67916. renderSubMesh(alphaTestSubMeshes.data[index]);
  67917. }
  67918. if (transparentSubMeshes.length) {
  67919. // Sort sub meshes
  67920. for (index = 0; index < transparentSubMeshes.length; index++) {
  67921. var submesh = transparentSubMeshes.data[index];
  67922. var boundingInfo = submesh.getBoundingInfo();
  67923. if (boundingInfo && scene.activeCamera) {
  67924. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67925. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67926. }
  67927. }
  67928. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67929. sortedArray.sort(function (a, b) {
  67930. // Alpha index first
  67931. if (a._alphaIndex > b._alphaIndex) {
  67932. return 1;
  67933. }
  67934. if (a._alphaIndex < b._alphaIndex) {
  67935. return -1;
  67936. }
  67937. // Then distance to camera
  67938. if (a._distanceToCamera < b._distanceToCamera) {
  67939. return 1;
  67940. }
  67941. if (a._distanceToCamera > b._distanceToCamera) {
  67942. return -1;
  67943. }
  67944. return 0;
  67945. });
  67946. // Render sub meshes
  67947. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67948. for (index = 0; index < sortedArray.length; index++) {
  67949. renderSubMesh(sortedArray[index]);
  67950. }
  67951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67952. }
  67953. };
  67954. };
  67955. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67956. var transform = scene.getTransformMatrix();
  67957. var meshPosition;
  67958. if (this.useCustomMeshPosition) {
  67959. meshPosition = this.customMeshPosition;
  67960. }
  67961. else if (this.attachedNode) {
  67962. meshPosition = this.attachedNode.position;
  67963. }
  67964. else {
  67965. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67966. }
  67967. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67968. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67969. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67970. if (this.invert)
  67971. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67972. };
  67973. // Static methods
  67974. /**
  67975. * Creates a default mesh for the Volumeric Light Scattering post-process
  67976. * @param {string} The mesh name
  67977. * @param {BABYLON.Scene} The scene where to create the mesh
  67978. * @return {BABYLON.Mesh} the default mesh
  67979. */
  67980. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67981. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67982. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67983. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67984. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67985. mesh.material = material;
  67986. return mesh;
  67987. };
  67988. __decorate([
  67989. BABYLON.serializeAsVector3()
  67990. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67991. __decorate([
  67992. BABYLON.serialize()
  67993. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67994. __decorate([
  67995. BABYLON.serialize()
  67996. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67997. __decorate([
  67998. BABYLON.serializeAsMeshReference()
  67999. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68000. __decorate([
  68001. BABYLON.serialize()
  68002. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68003. __decorate([
  68004. BABYLON.serialize()
  68005. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68006. __decorate([
  68007. BABYLON.serialize()
  68008. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68009. __decorate([
  68010. BABYLON.serialize()
  68011. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68012. __decorate([
  68013. BABYLON.serialize()
  68014. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68015. return VolumetricLightScatteringPostProcess;
  68016. }(BABYLON.PostProcess));
  68017. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68018. })(BABYLON || (BABYLON = {}));
  68019. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68020. //
  68021. // This post-process allows the modification of rendered colors by using
  68022. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68023. //
  68024. // The object needs to be provided an url to a texture containing the color
  68025. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68026. // Use an image editing software to tweak the LUT to match your needs.
  68027. //
  68028. // For an example of a color LUT, see here:
  68029. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68030. // For explanations on color grading, see here:
  68031. // http://udn.epicgames.com/Three/ColorGrading.html
  68032. //
  68033. var BABYLON;
  68034. (function (BABYLON) {
  68035. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  68036. __extends(ColorCorrectionPostProcess, _super);
  68037. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  68038. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  68039. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68040. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  68041. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68042. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68043. _this.onApply = function (effect) {
  68044. effect.setTexture("colorTable", _this._colorTableTexture);
  68045. };
  68046. return _this;
  68047. }
  68048. return ColorCorrectionPostProcess;
  68049. }(BABYLON.PostProcess));
  68050. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  68051. })(BABYLON || (BABYLON = {}));
  68052. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  68053. var BABYLON;
  68054. (function (BABYLON) {
  68055. var TonemappingOperator;
  68056. (function (TonemappingOperator) {
  68057. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  68058. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  68059. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  68060. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  68061. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  68062. ;
  68063. var TonemapPostProcess = /** @class */ (function (_super) {
  68064. __extends(TonemapPostProcess, _super);
  68065. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  68066. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68067. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68068. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  68069. _this._operator = _operator;
  68070. _this.exposureAdjustment = exposureAdjustment;
  68071. var defines = "#define ";
  68072. if (_this._operator === TonemappingOperator.Hable)
  68073. defines += "HABLE_TONEMAPPING";
  68074. else if (_this._operator === TonemappingOperator.Reinhard)
  68075. defines += "REINHARD_TONEMAPPING";
  68076. else if (_this._operator === TonemappingOperator.HejiDawson)
  68077. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  68078. else if (_this._operator === TonemappingOperator.Photographic)
  68079. defines += "PHOTOGRAPHIC_TONEMAPPING";
  68080. //sadly a second call to create the effect.
  68081. _this.updateEffect(defines);
  68082. _this.onApply = function (effect) {
  68083. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  68084. };
  68085. return _this;
  68086. }
  68087. return TonemapPostProcess;
  68088. }(BABYLON.PostProcess));
  68089. BABYLON.TonemapPostProcess = TonemapPostProcess;
  68090. })(BABYLON || (BABYLON = {}));
  68091. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  68092. var BABYLON;
  68093. (function (BABYLON) {
  68094. var DisplayPassPostProcess = /** @class */ (function (_super) {
  68095. __extends(DisplayPassPostProcess, _super);
  68096. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  68097. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  68098. }
  68099. return DisplayPassPostProcess;
  68100. }(BABYLON.PostProcess));
  68101. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  68102. })(BABYLON || (BABYLON = {}));
  68103. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  68104. var BABYLON;
  68105. (function (BABYLON) {
  68106. var HighlightsPostProcess = /** @class */ (function (_super) {
  68107. __extends(HighlightsPostProcess, _super);
  68108. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68109. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68110. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68111. }
  68112. return HighlightsPostProcess;
  68113. }(BABYLON.PostProcess));
  68114. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  68115. })(BABYLON || (BABYLON = {}));
  68116. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  68117. var BABYLON;
  68118. (function (BABYLON) {
  68119. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  68120. __extends(ImageProcessingPostProcess, _super);
  68121. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  68122. if (camera === void 0) { camera = null; }
  68123. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68124. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  68125. _this._fromLinearSpace = true;
  68126. /**
  68127. * Defines cache preventing GC.
  68128. */
  68129. _this._defines = {
  68130. IMAGEPROCESSING: false,
  68131. VIGNETTE: false,
  68132. VIGNETTEBLENDMODEMULTIPLY: false,
  68133. VIGNETTEBLENDMODEOPAQUE: false,
  68134. TONEMAPPING: false,
  68135. CONTRAST: false,
  68136. COLORCURVES: false,
  68137. COLORGRADING: false,
  68138. COLORGRADING3D: false,
  68139. FROMLINEARSPACE: false,
  68140. SAMPLER3DGREENDEPTH: false,
  68141. SAMPLER3DBGRMAP: false,
  68142. IMAGEPROCESSINGPOSTPROCESS: false,
  68143. EXPOSURE: false,
  68144. };
  68145. // Setup the configuration as forced by the constructor. This would then not force the
  68146. // scene materials output in linear space and let untouched the default forward pass.
  68147. if (imageProcessingConfiguration) {
  68148. imageProcessingConfiguration.applyByPostProcess = true;
  68149. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68150. // This will cause the shader to be compiled
  68151. _this.fromLinearSpace = false;
  68152. }
  68153. else {
  68154. _this._attachImageProcessingConfiguration(null, true);
  68155. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68156. }
  68157. _this.onApply = function (effect) {
  68158. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68159. };
  68160. return _this;
  68161. }
  68162. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68163. /**
  68164. * Gets the image processing configuration used either in this material.
  68165. */
  68166. get: function () {
  68167. return this._imageProcessingConfiguration;
  68168. },
  68169. /**
  68170. * Sets the Default image processing configuration used either in the this material.
  68171. *
  68172. * If sets to null, the scene one is in use.
  68173. */
  68174. set: function (value) {
  68175. this._attachImageProcessingConfiguration(value);
  68176. },
  68177. enumerable: true,
  68178. configurable: true
  68179. });
  68180. /**
  68181. * Attaches a new image processing configuration to the PBR Material.
  68182. * @param configuration
  68183. */
  68184. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68185. var _this = this;
  68186. if (doNotBuild === void 0) { doNotBuild = false; }
  68187. if (configuration === this._imageProcessingConfiguration) {
  68188. return;
  68189. }
  68190. // Detaches observer.
  68191. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68192. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68193. }
  68194. // Pick the scene configuration if needed.
  68195. if (!configuration) {
  68196. var scene = null;
  68197. var engine = this.getEngine();
  68198. var camera = this.getCamera();
  68199. if (camera) {
  68200. scene = camera.getScene();
  68201. }
  68202. else if (engine && engine.scenes) {
  68203. var scenes = engine.scenes;
  68204. scene = scenes[scenes.length - 1];
  68205. }
  68206. else {
  68207. scene = BABYLON.Engine.LastCreatedScene;
  68208. }
  68209. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68210. }
  68211. else {
  68212. this._imageProcessingConfiguration = configuration;
  68213. }
  68214. // Attaches observer.
  68215. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68216. _this._updateParameters();
  68217. });
  68218. // Ensure the effect will be rebuilt.
  68219. if (!doNotBuild) {
  68220. this._updateParameters();
  68221. }
  68222. };
  68223. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68224. /**
  68225. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68226. */
  68227. get: function () {
  68228. return this.imageProcessingConfiguration.colorCurves;
  68229. },
  68230. /**
  68231. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68232. */
  68233. set: function (value) {
  68234. this.imageProcessingConfiguration.colorCurves = value;
  68235. },
  68236. enumerable: true,
  68237. configurable: true
  68238. });
  68239. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68240. /**
  68241. * Gets wether the color curves effect is enabled.
  68242. */
  68243. get: function () {
  68244. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68245. },
  68246. /**
  68247. * Sets wether the color curves effect is enabled.
  68248. */
  68249. set: function (value) {
  68250. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68251. },
  68252. enumerable: true,
  68253. configurable: true
  68254. });
  68255. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68256. /**
  68257. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68258. */
  68259. get: function () {
  68260. return this.imageProcessingConfiguration.colorGradingTexture;
  68261. },
  68262. /**
  68263. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68264. */
  68265. set: function (value) {
  68266. this.imageProcessingConfiguration.colorGradingTexture = value;
  68267. },
  68268. enumerable: true,
  68269. configurable: true
  68270. });
  68271. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68272. /**
  68273. * Gets wether the color grading effect is enabled.
  68274. */
  68275. get: function () {
  68276. return this.imageProcessingConfiguration.colorGradingEnabled;
  68277. },
  68278. /**
  68279. * Gets wether the color grading effect is enabled.
  68280. */
  68281. set: function (value) {
  68282. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68283. },
  68284. enumerable: true,
  68285. configurable: true
  68286. });
  68287. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68288. /**
  68289. * Gets exposure used in the effect.
  68290. */
  68291. get: function () {
  68292. return this.imageProcessingConfiguration.exposure;
  68293. },
  68294. /**
  68295. * Sets exposure used in the effect.
  68296. */
  68297. set: function (value) {
  68298. this.imageProcessingConfiguration.exposure = value;
  68299. },
  68300. enumerable: true,
  68301. configurable: true
  68302. });
  68303. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68304. /**
  68305. * Gets wether tonemapping is enabled or not.
  68306. */
  68307. get: function () {
  68308. return this._imageProcessingConfiguration.toneMappingEnabled;
  68309. },
  68310. /**
  68311. * Sets wether tonemapping is enabled or not
  68312. */
  68313. set: function (value) {
  68314. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68315. },
  68316. enumerable: true,
  68317. configurable: true
  68318. });
  68319. ;
  68320. ;
  68321. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68322. /**
  68323. * Gets contrast used in the effect.
  68324. */
  68325. get: function () {
  68326. return this.imageProcessingConfiguration.contrast;
  68327. },
  68328. /**
  68329. * Sets contrast used in the effect.
  68330. */
  68331. set: function (value) {
  68332. this.imageProcessingConfiguration.contrast = value;
  68333. },
  68334. enumerable: true,
  68335. configurable: true
  68336. });
  68337. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68338. /**
  68339. * Gets Vignette stretch size.
  68340. */
  68341. get: function () {
  68342. return this.imageProcessingConfiguration.vignetteStretch;
  68343. },
  68344. /**
  68345. * Sets Vignette stretch size.
  68346. */
  68347. set: function (value) {
  68348. this.imageProcessingConfiguration.vignetteStretch = value;
  68349. },
  68350. enumerable: true,
  68351. configurable: true
  68352. });
  68353. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68354. /**
  68355. * Gets Vignette centre X Offset.
  68356. */
  68357. get: function () {
  68358. return this.imageProcessingConfiguration.vignetteCentreX;
  68359. },
  68360. /**
  68361. * Sets Vignette centre X Offset.
  68362. */
  68363. set: function (value) {
  68364. this.imageProcessingConfiguration.vignetteCentreX = value;
  68365. },
  68366. enumerable: true,
  68367. configurable: true
  68368. });
  68369. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68370. /**
  68371. * Gets Vignette centre Y Offset.
  68372. */
  68373. get: function () {
  68374. return this.imageProcessingConfiguration.vignetteCentreY;
  68375. },
  68376. /**
  68377. * Sets Vignette centre Y Offset.
  68378. */
  68379. set: function (value) {
  68380. this.imageProcessingConfiguration.vignetteCentreY = value;
  68381. },
  68382. enumerable: true,
  68383. configurable: true
  68384. });
  68385. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68386. /**
  68387. * Gets Vignette weight or intensity of the vignette effect.
  68388. */
  68389. get: function () {
  68390. return this.imageProcessingConfiguration.vignetteWeight;
  68391. },
  68392. /**
  68393. * Sets Vignette weight or intensity of the vignette effect.
  68394. */
  68395. set: function (value) {
  68396. this.imageProcessingConfiguration.vignetteWeight = value;
  68397. },
  68398. enumerable: true,
  68399. configurable: true
  68400. });
  68401. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68402. /**
  68403. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68404. * if vignetteEnabled is set to true.
  68405. */
  68406. get: function () {
  68407. return this.imageProcessingConfiguration.vignetteColor;
  68408. },
  68409. /**
  68410. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68411. * if vignetteEnabled is set to true.
  68412. */
  68413. set: function (value) {
  68414. this.imageProcessingConfiguration.vignetteColor = value;
  68415. },
  68416. enumerable: true,
  68417. configurable: true
  68418. });
  68419. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68420. /**
  68421. * Gets Camera field of view used by the Vignette effect.
  68422. */
  68423. get: function () {
  68424. return this.imageProcessingConfiguration.vignetteCameraFov;
  68425. },
  68426. /**
  68427. * Sets Camera field of view used by the Vignette effect.
  68428. */
  68429. set: function (value) {
  68430. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68431. },
  68432. enumerable: true,
  68433. configurable: true
  68434. });
  68435. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68436. /**
  68437. * Gets the vignette blend mode allowing different kind of effect.
  68438. */
  68439. get: function () {
  68440. return this.imageProcessingConfiguration.vignetteBlendMode;
  68441. },
  68442. /**
  68443. * Sets the vignette blend mode allowing different kind of effect.
  68444. */
  68445. set: function (value) {
  68446. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68447. },
  68448. enumerable: true,
  68449. configurable: true
  68450. });
  68451. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68452. /**
  68453. * Gets wether the vignette effect is enabled.
  68454. */
  68455. get: function () {
  68456. return this.imageProcessingConfiguration.vignetteEnabled;
  68457. },
  68458. /**
  68459. * Sets wether the vignette effect is enabled.
  68460. */
  68461. set: function (value) {
  68462. this.imageProcessingConfiguration.vignetteEnabled = value;
  68463. },
  68464. enumerable: true,
  68465. configurable: true
  68466. });
  68467. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68468. /**
  68469. * Gets wether the input of the processing is in Gamma or Linear Space.
  68470. */
  68471. get: function () {
  68472. return this._fromLinearSpace;
  68473. },
  68474. /**
  68475. * Sets wether the input of the processing is in Gamma or Linear Space.
  68476. */
  68477. set: function (value) {
  68478. if (this._fromLinearSpace === value) {
  68479. return;
  68480. }
  68481. this._fromLinearSpace = value;
  68482. this._updateParameters();
  68483. },
  68484. enumerable: true,
  68485. configurable: true
  68486. });
  68487. ImageProcessingPostProcess.prototype.getClassName = function () {
  68488. return "ImageProcessingPostProcess";
  68489. };
  68490. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68491. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68492. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68493. var defines = "";
  68494. for (var define in this._defines) {
  68495. if (this._defines[define]) {
  68496. defines += "#define " + define + ";\r\n";
  68497. }
  68498. }
  68499. var samplers = ["textureSampler"];
  68500. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68501. var uniforms = ["scale"];
  68502. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68503. this.updateEffect(defines, uniforms, samplers);
  68504. };
  68505. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68506. _super.prototype.dispose.call(this, camera);
  68507. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68508. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68509. }
  68510. this.imageProcessingConfiguration.applyByPostProcess = false;
  68511. };
  68512. __decorate([
  68513. BABYLON.serialize()
  68514. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68515. return ImageProcessingPostProcess;
  68516. }(BABYLON.PostProcess));
  68517. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68518. })(BABYLON || (BABYLON = {}));
  68519. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68520. var BABYLON;
  68521. (function (BABYLON) {
  68522. /**
  68523. * The Blur Post Process which blurs an image based on a kernel and direction.
  68524. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68525. */
  68526. var BlurPostProcess = /** @class */ (function (_super) {
  68527. __extends(BlurPostProcess, _super);
  68528. /**
  68529. * Creates a new instance of @see BlurPostProcess
  68530. * @param name The name of the effect.
  68531. * @param direction The direction in which to blur the image.
  68532. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  68533. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68534. * @param camera The camera to apply the render pass to.
  68535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68536. * @param engine The engine which the post process will be applied. (default: current engine)
  68537. * @param reusable If the post process can be reused on the same frame. (default: false)
  68538. * @param textureType Type of textures used when performing the post process. (default: 0)
  68539. */
  68540. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68542. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68543. if (defines === void 0) { defines = ""; }
  68544. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68545. _this.direction = direction;
  68546. _this._packedFloat = false;
  68547. _this._staticDefines = "";
  68548. _this._staticDefines = defines;
  68549. _this.onApplyObservable.add(function (effect) {
  68550. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68551. });
  68552. _this.kernel = kernel;
  68553. return _this;
  68554. }
  68555. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68556. /**
  68557. * Gets the length in pixels of the blur sample region
  68558. */
  68559. get: function () {
  68560. return this._idealKernel;
  68561. },
  68562. /**
  68563. * Sets the length in pixels of the blur sample region
  68564. */
  68565. set: function (v) {
  68566. if (this._idealKernel === v) {
  68567. return;
  68568. }
  68569. v = Math.max(v, 1);
  68570. this._idealKernel = v;
  68571. this._kernel = this._nearestBestKernel(v);
  68572. this._updateParameters();
  68573. },
  68574. enumerable: true,
  68575. configurable: true
  68576. });
  68577. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68578. /**
  68579. * Gets wether or not the blur is unpacking/repacking floats
  68580. */
  68581. get: function () {
  68582. return this._packedFloat;
  68583. },
  68584. /**
  68585. * Sets wether or not the blur needs to unpack/repack floats
  68586. */
  68587. set: function (v) {
  68588. if (this._packedFloat === v) {
  68589. return;
  68590. }
  68591. this._packedFloat = v;
  68592. this._updateParameters();
  68593. },
  68594. enumerable: true,
  68595. configurable: true
  68596. });
  68597. BlurPostProcess.prototype._updateParameters = function () {
  68598. // Generate sampling offsets and weights
  68599. var N = this._kernel;
  68600. var centerIndex = (N - 1) / 2;
  68601. // Generate Gaussian sampling weights over kernel
  68602. var offsets = [];
  68603. var weights = [];
  68604. var totalWeight = 0;
  68605. for (var i = 0; i < N; i++) {
  68606. var u = i / (N - 1);
  68607. var w = this._gaussianWeight(u * 2.0 - 1);
  68608. offsets[i] = (i - centerIndex);
  68609. weights[i] = w;
  68610. totalWeight += w;
  68611. }
  68612. // Normalize weights
  68613. for (var i = 0; i < weights.length; i++) {
  68614. weights[i] /= totalWeight;
  68615. }
  68616. // Optimize: combine samples to take advantage of hardware linear sampling
  68617. // Walk from left to center, combining pairs (symmetrically)
  68618. var linearSamplingWeights = [];
  68619. var linearSamplingOffsets = [];
  68620. var linearSamplingMap = [];
  68621. for (var i = 0; i <= centerIndex; i += 2) {
  68622. var j = Math.min(i + 1, Math.floor(centerIndex));
  68623. var singleCenterSample = i === j;
  68624. if (singleCenterSample) {
  68625. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68626. }
  68627. else {
  68628. var sharedCell = j === centerIndex;
  68629. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68630. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68631. if (offsetLinear === 0) {
  68632. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68633. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68634. }
  68635. else {
  68636. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68637. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68638. }
  68639. }
  68640. }
  68641. for (var i = 0; i < linearSamplingMap.length; i++) {
  68642. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68643. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68644. }
  68645. // Replace with optimized
  68646. offsets = linearSamplingOffsets;
  68647. weights = linearSamplingWeights;
  68648. // Generate shaders
  68649. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68650. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68651. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68652. var defines = "";
  68653. defines += this._staticDefines;
  68654. for (var i = 0; i < varyingCount; i++) {
  68655. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68656. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68657. }
  68658. var depCount = 0;
  68659. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68660. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68661. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68662. depCount++;
  68663. }
  68664. if (this.packedFloat) {
  68665. defines += "#define PACKEDFLOAT 1";
  68666. }
  68667. this.updateEffect(defines, null, null, {
  68668. varyingCount: varyingCount,
  68669. depCount: depCount
  68670. });
  68671. };
  68672. /**
  68673. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68674. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68675. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68676. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68677. * The gaps between physical kernels are compensated for in the weighting of the samples
  68678. * @param idealKernel Ideal blur kernel.
  68679. * @return Nearest best kernel.
  68680. */
  68681. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68682. var v = Math.round(idealKernel);
  68683. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68684. var k = _a[_i];
  68685. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68686. return Math.max(k, 3);
  68687. }
  68688. }
  68689. return Math.max(v, 3);
  68690. };
  68691. /**
  68692. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68693. * @param x The point on the Gaussian distribution to sample.
  68694. * @return the value of the Gaussian function at x.
  68695. */
  68696. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68697. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68698. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68699. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68700. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68701. // truncated at around 1.3% of peak strength.
  68702. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68703. var sigma = (1 / 3);
  68704. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68705. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68706. var weight = (1.0 / denominator) * Math.exp(exponent);
  68707. return weight;
  68708. };
  68709. /**
  68710. * Generates a string that can be used as a floating point number in GLSL.
  68711. * @param x Value to print.
  68712. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68713. * @return GLSL float string.
  68714. */
  68715. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68716. if (decimalFigures === void 0) { decimalFigures = 8; }
  68717. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68718. };
  68719. return BlurPostProcess;
  68720. }(BABYLON.PostProcess));
  68721. BABYLON.BlurPostProcess = BlurPostProcess;
  68722. })(BABYLON || (BABYLON = {}));
  68723. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68724. var BABYLON;
  68725. (function (BABYLON) {
  68726. var Bone = /** @class */ (function (_super) {
  68727. __extends(Bone, _super);
  68728. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68729. if (parentBone === void 0) { parentBone = null; }
  68730. if (localMatrix === void 0) { localMatrix = null; }
  68731. if (restPose === void 0) { restPose = null; }
  68732. if (baseMatrix === void 0) { baseMatrix = null; }
  68733. if (index === void 0) { index = null; }
  68734. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68735. _this.name = name;
  68736. _this.children = new Array();
  68737. _this.animations = new Array();
  68738. // Set this value to map this bone to a different index in the transform matrices.
  68739. // Set this value to -1 to exclude the bone from the transform matrices.
  68740. _this._index = null;
  68741. _this._worldTransform = new BABYLON.Matrix();
  68742. _this._absoluteTransform = new BABYLON.Matrix();
  68743. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68744. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68745. _this._scaleVector = BABYLON.Vector3.One();
  68746. _this._negateScaleChildren = BABYLON.Vector3.One();
  68747. _this._scalingDeterminant = 1;
  68748. _this._skeleton = skeleton;
  68749. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68750. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68751. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68752. _this._index = index;
  68753. skeleton.bones.push(_this);
  68754. _this.setParent(parentBone, false);
  68755. _this._updateDifferenceMatrix();
  68756. return _this;
  68757. }
  68758. Object.defineProperty(Bone.prototype, "_matrix", {
  68759. get: function () {
  68760. return this._localMatrix;
  68761. },
  68762. set: function (val) {
  68763. if (this._localMatrix) {
  68764. this._localMatrix.copyFrom(val);
  68765. }
  68766. else {
  68767. this._localMatrix = val;
  68768. }
  68769. },
  68770. enumerable: true,
  68771. configurable: true
  68772. });
  68773. // Members
  68774. Bone.prototype.getSkeleton = function () {
  68775. return this._skeleton;
  68776. };
  68777. Bone.prototype.getParent = function () {
  68778. return this._parent;
  68779. };
  68780. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68781. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68782. if (this._parent === parent) {
  68783. return;
  68784. }
  68785. if (this._parent) {
  68786. var index = this._parent.children.indexOf(this);
  68787. if (index !== -1) {
  68788. this._parent.children.splice(index, 1);
  68789. }
  68790. }
  68791. this._parent = parent;
  68792. if (this._parent) {
  68793. this._parent.children.push(this);
  68794. }
  68795. if (updateDifferenceMatrix) {
  68796. this._updateDifferenceMatrix();
  68797. }
  68798. };
  68799. Bone.prototype.getLocalMatrix = function () {
  68800. return this._localMatrix;
  68801. };
  68802. Bone.prototype.getBaseMatrix = function () {
  68803. return this._baseMatrix;
  68804. };
  68805. Bone.prototype.getRestPose = function () {
  68806. return this._restPose;
  68807. };
  68808. Bone.prototype.returnToRest = function () {
  68809. this.updateMatrix(this._restPose.clone());
  68810. };
  68811. Bone.prototype.getWorldMatrix = function () {
  68812. return this._worldTransform;
  68813. };
  68814. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68815. return this._invertedAbsoluteTransform;
  68816. };
  68817. Bone.prototype.getAbsoluteTransform = function () {
  68818. return this._absoluteTransform;
  68819. };
  68820. Object.defineProperty(Bone.prototype, "position", {
  68821. // Properties (matches AbstractMesh properties)
  68822. get: function () {
  68823. return this.getPosition();
  68824. },
  68825. set: function (newPosition) {
  68826. this.setPosition(newPosition);
  68827. },
  68828. enumerable: true,
  68829. configurable: true
  68830. });
  68831. Object.defineProperty(Bone.prototype, "rotation", {
  68832. get: function () {
  68833. return this.getRotation();
  68834. },
  68835. set: function (newRotation) {
  68836. this.setRotation(newRotation);
  68837. },
  68838. enumerable: true,
  68839. configurable: true
  68840. });
  68841. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68842. get: function () {
  68843. return this.getRotationQuaternion();
  68844. },
  68845. set: function (newRotation) {
  68846. this.setRotationQuaternion(newRotation);
  68847. },
  68848. enumerable: true,
  68849. configurable: true
  68850. });
  68851. Object.defineProperty(Bone.prototype, "scaling", {
  68852. get: function () {
  68853. return this.getScale();
  68854. },
  68855. set: function (newScaling) {
  68856. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68857. },
  68858. enumerable: true,
  68859. configurable: true
  68860. });
  68861. // Methods
  68862. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68863. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68864. this._baseMatrix = matrix.clone();
  68865. this._localMatrix = matrix.clone();
  68866. this._skeleton._markAsDirty();
  68867. if (updateDifferenceMatrix) {
  68868. this._updateDifferenceMatrix();
  68869. }
  68870. };
  68871. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68872. if (!rootMatrix) {
  68873. rootMatrix = this._baseMatrix;
  68874. }
  68875. if (this._parent) {
  68876. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68877. }
  68878. else {
  68879. this._absoluteTransform.copyFrom(rootMatrix);
  68880. }
  68881. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68882. for (var index = 0; index < this.children.length; index++) {
  68883. this.children[index]._updateDifferenceMatrix();
  68884. }
  68885. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68886. };
  68887. Bone.prototype.markAsDirty = function () {
  68888. this._currentRenderId++;
  68889. this._skeleton._markAsDirty();
  68890. };
  68891. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68892. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68893. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68894. // all animation may be coming from a library skeleton, so may need to create animation
  68895. if (this.animations.length === 0) {
  68896. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68897. this.animations[0].setKeys([]);
  68898. }
  68899. // get animation info / verify there is such a range from the source bone
  68900. var sourceRange = source.animations[0].getRange(rangeName);
  68901. if (!sourceRange) {
  68902. return false;
  68903. }
  68904. var from = sourceRange.from;
  68905. var to = sourceRange.to;
  68906. var sourceKeys = source.animations[0].getKeys();
  68907. // rescaling prep
  68908. var sourceBoneLength = source.length;
  68909. var sourceParent = source.getParent();
  68910. var parent = this.getParent();
  68911. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68912. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68913. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68914. var destKeys = this.animations[0].getKeys();
  68915. // loop vars declaration
  68916. var orig;
  68917. var origTranslation;
  68918. var mat;
  68919. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68920. orig = sourceKeys[key];
  68921. if (orig.frame >= from && orig.frame <= to) {
  68922. if (rescaleAsRequired) {
  68923. mat = orig.value.clone();
  68924. // scale based on parent ratio, when bone has parent
  68925. if (parentScalingReqd) {
  68926. origTranslation = mat.getTranslation();
  68927. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68928. // scale based on skeleton dimension ratio when root bone, and value is passed
  68929. }
  68930. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68931. origTranslation = mat.getTranslation();
  68932. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68933. // use original when root bone, and no data for skelDimensionsRatio
  68934. }
  68935. else {
  68936. mat = orig.value;
  68937. }
  68938. }
  68939. else {
  68940. mat = orig.value;
  68941. }
  68942. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68943. }
  68944. }
  68945. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68946. return true;
  68947. };
  68948. /**
  68949. * Translate the bone in local or world space.
  68950. * @param vec The amount to translate the bone.
  68951. * @param space The space that the translation is in.
  68952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68953. */
  68954. Bone.prototype.translate = function (vec, space, mesh) {
  68955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68956. var lm = this.getLocalMatrix();
  68957. if (space == BABYLON.Space.LOCAL) {
  68958. lm.m[12] += vec.x;
  68959. lm.m[13] += vec.y;
  68960. lm.m[14] += vec.z;
  68961. }
  68962. else {
  68963. var wm = null;
  68964. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68965. if (mesh) {
  68966. wm = mesh.getWorldMatrix();
  68967. }
  68968. this._skeleton.computeAbsoluteTransforms();
  68969. var tmat = Bone._tmpMats[0];
  68970. var tvec = Bone._tmpVecs[0];
  68971. if (this._parent) {
  68972. if (mesh && wm) {
  68973. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68974. tmat.multiplyToRef(wm, tmat);
  68975. }
  68976. else {
  68977. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68978. }
  68979. }
  68980. tmat.m[12] = 0;
  68981. tmat.m[13] = 0;
  68982. tmat.m[14] = 0;
  68983. tmat.invert();
  68984. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68985. lm.m[12] += tvec.x;
  68986. lm.m[13] += tvec.y;
  68987. lm.m[14] += tvec.z;
  68988. }
  68989. this.markAsDirty();
  68990. };
  68991. /**
  68992. * Set the postion of the bone in local or world space.
  68993. * @param position The position to set the bone.
  68994. * @param space The space that the position is in.
  68995. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68996. */
  68997. Bone.prototype.setPosition = function (position, space, mesh) {
  68998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68999. var lm = this.getLocalMatrix();
  69000. if (space == BABYLON.Space.LOCAL) {
  69001. lm.m[12] = position.x;
  69002. lm.m[13] = position.y;
  69003. lm.m[14] = position.z;
  69004. }
  69005. else {
  69006. var wm = null;
  69007. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69008. if (mesh) {
  69009. wm = mesh.getWorldMatrix();
  69010. }
  69011. this._skeleton.computeAbsoluteTransforms();
  69012. var tmat = Bone._tmpMats[0];
  69013. var vec = Bone._tmpVecs[0];
  69014. if (this._parent) {
  69015. if (mesh && wm) {
  69016. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69017. tmat.multiplyToRef(wm, tmat);
  69018. }
  69019. else {
  69020. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69021. }
  69022. }
  69023. tmat.invert();
  69024. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  69025. lm.m[12] = vec.x;
  69026. lm.m[13] = vec.y;
  69027. lm.m[14] = vec.z;
  69028. }
  69029. this.markAsDirty();
  69030. };
  69031. /**
  69032. * Set the absolute postion of the bone (world space).
  69033. * @param position The position to set the bone.
  69034. * @param mesh The mesh that this bone is attached to.
  69035. */
  69036. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  69037. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  69038. };
  69039. /**
  69040. * Set the scale of the bone on the x, y and z axes.
  69041. * @param x The scale of the bone on the x axis.
  69042. * @param x The scale of the bone on the y axis.
  69043. * @param z The scale of the bone on the z axis.
  69044. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69045. */
  69046. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  69047. if (scaleChildren === void 0) { scaleChildren = false; }
  69048. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  69049. if (!scaleChildren) {
  69050. this._negateScaleChildren.x = 1 / x;
  69051. this._negateScaleChildren.y = 1 / y;
  69052. this._negateScaleChildren.z = 1 / z;
  69053. }
  69054. this._syncScaleVector();
  69055. }
  69056. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  69057. };
  69058. /**
  69059. * Scale the bone on the x, y and z axes.
  69060. * @param x The amount to scale the bone on the x axis.
  69061. * @param x The amount to scale the bone on the y axis.
  69062. * @param z The amount to scale the bone on the z axis.
  69063. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69064. */
  69065. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  69066. if (scaleChildren === void 0) { scaleChildren = false; }
  69067. var locMat = this.getLocalMatrix();
  69068. var origLocMat = Bone._tmpMats[0];
  69069. origLocMat.copyFrom(locMat);
  69070. var origLocMatInv = Bone._tmpMats[1];
  69071. origLocMatInv.copyFrom(origLocMat);
  69072. origLocMatInv.invert();
  69073. var scaleMat = Bone._tmpMats[2];
  69074. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  69075. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  69076. this._scaleVector.x *= x;
  69077. this._scaleVector.y *= y;
  69078. this._scaleVector.z *= z;
  69079. locMat.multiplyToRef(origLocMatInv, locMat);
  69080. locMat.multiplyToRef(scaleMat, locMat);
  69081. locMat.multiplyToRef(origLocMat, locMat);
  69082. var parent = this.getParent();
  69083. if (parent) {
  69084. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  69085. }
  69086. else {
  69087. this.getAbsoluteTransform().copyFrom(locMat);
  69088. }
  69089. var len = this.children.length;
  69090. scaleMat.invert();
  69091. for (var i = 0; i < len; i++) {
  69092. var child = this.children[i];
  69093. var cm = child.getLocalMatrix();
  69094. cm.multiplyToRef(scaleMat, cm);
  69095. var lm = child.getLocalMatrix();
  69096. lm.m[12] *= x;
  69097. lm.m[13] *= y;
  69098. lm.m[14] *= z;
  69099. }
  69100. this.computeAbsoluteTransforms();
  69101. if (scaleChildren) {
  69102. for (var i = 0; i < len; i++) {
  69103. this.children[i].scale(x, y, z, scaleChildren);
  69104. }
  69105. }
  69106. this.markAsDirty();
  69107. };
  69108. /**
  69109. * Set the yaw, pitch, and roll of the bone in local or world space.
  69110. * @param yaw The rotation of the bone on the y axis.
  69111. * @param pitch The rotation of the bone on the x axis.
  69112. * @param roll The rotation of the bone on the z axis.
  69113. * @param space The space that the axes of rotation are in.
  69114. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69115. */
  69116. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69118. var rotMat = Bone._tmpMats[0];
  69119. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69120. var rotMatInv = Bone._tmpMats[1];
  69121. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69122. rotMatInv.multiplyToRef(rotMat, rotMat);
  69123. this._rotateWithMatrix(rotMat, space, mesh);
  69124. };
  69125. /**
  69126. * Rotate the bone on an axis in local or world space.
  69127. * @param axis The axis to rotate the bone on.
  69128. * @param amount The amount to rotate the bone.
  69129. * @param space The space that the axis is in.
  69130. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69131. */
  69132. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69134. var rmat = Bone._tmpMats[0];
  69135. rmat.m[12] = 0;
  69136. rmat.m[13] = 0;
  69137. rmat.m[14] = 0;
  69138. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69139. this._rotateWithMatrix(rmat, space, mesh);
  69140. };
  69141. /**
  69142. * Set the rotation of the bone to a particular axis angle in local or world space.
  69143. * @param axis The axis to rotate the bone on.
  69144. * @param angle The angle that the bone should be rotated to.
  69145. * @param space The space that the axis is in.
  69146. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69147. */
  69148. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69150. var rotMat = Bone._tmpMats[0];
  69151. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69152. var rotMatInv = Bone._tmpMats[1];
  69153. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69154. rotMatInv.multiplyToRef(rotMat, rotMat);
  69155. this._rotateWithMatrix(rotMat, space, mesh);
  69156. };
  69157. /**
  69158. * Set the euler rotation of the bone in local of world space.
  69159. * @param rotation The euler rotation that the bone should be set to.
  69160. * @param space The space that the rotation is in.
  69161. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69162. */
  69163. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69164. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69165. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69166. };
  69167. /**
  69168. * Set the quaternion rotation of the bone in local of world space.
  69169. * @param quat The quaternion rotation that the bone should be set to.
  69170. * @param space The space that the rotation is in.
  69171. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69172. */
  69173. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69175. var rotMatInv = Bone._tmpMats[0];
  69176. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69177. var rotMat = Bone._tmpMats[1];
  69178. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69179. rotMatInv.multiplyToRef(rotMat, rotMat);
  69180. this._rotateWithMatrix(rotMat, space, mesh);
  69181. };
  69182. /**
  69183. * Set the rotation matrix of the bone in local of world space.
  69184. * @param rotMat The rotation matrix that the bone should be set to.
  69185. * @param space The space that the rotation is in.
  69186. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69187. */
  69188. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69190. var rotMatInv = Bone._tmpMats[0];
  69191. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69192. var rotMat2 = Bone._tmpMats[1];
  69193. rotMat2.copyFrom(rotMat);
  69194. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69195. this._rotateWithMatrix(rotMat2, space, mesh);
  69196. };
  69197. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69198. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69199. var lmat = this.getLocalMatrix();
  69200. var lx = lmat.m[12];
  69201. var ly = lmat.m[13];
  69202. var lz = lmat.m[14];
  69203. var parent = this.getParent();
  69204. var parentScale = Bone._tmpMats[3];
  69205. var parentScaleInv = Bone._tmpMats[4];
  69206. if (parent) {
  69207. if (space == BABYLON.Space.WORLD) {
  69208. if (mesh) {
  69209. parentScale.copyFrom(mesh.getWorldMatrix());
  69210. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69211. }
  69212. else {
  69213. parentScale.copyFrom(parent.getAbsoluteTransform());
  69214. }
  69215. }
  69216. else {
  69217. parentScale = parent._scaleMatrix;
  69218. }
  69219. parentScaleInv.copyFrom(parentScale);
  69220. parentScaleInv.invert();
  69221. lmat.multiplyToRef(parentScale, lmat);
  69222. lmat.multiplyToRef(rmat, lmat);
  69223. lmat.multiplyToRef(parentScaleInv, lmat);
  69224. }
  69225. else {
  69226. if (space == BABYLON.Space.WORLD && mesh) {
  69227. parentScale.copyFrom(mesh.getWorldMatrix());
  69228. parentScaleInv.copyFrom(parentScale);
  69229. parentScaleInv.invert();
  69230. lmat.multiplyToRef(parentScale, lmat);
  69231. lmat.multiplyToRef(rmat, lmat);
  69232. lmat.multiplyToRef(parentScaleInv, lmat);
  69233. }
  69234. else {
  69235. lmat.multiplyToRef(rmat, lmat);
  69236. }
  69237. }
  69238. lmat.m[12] = lx;
  69239. lmat.m[13] = ly;
  69240. lmat.m[14] = lz;
  69241. this.computeAbsoluteTransforms();
  69242. this.markAsDirty();
  69243. };
  69244. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69246. if (space == BABYLON.Space.WORLD) {
  69247. var scaleMatrix = Bone._tmpMats[2];
  69248. scaleMatrix.copyFrom(this._scaleMatrix);
  69249. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69250. if (mesh) {
  69251. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69252. var meshScale = Bone._tmpMats[3];
  69253. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69254. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69255. }
  69256. rotMatInv.invert();
  69257. scaleMatrix.m[0] *= this._scalingDeterminant;
  69258. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69259. }
  69260. else {
  69261. rotMatInv.copyFrom(this.getLocalMatrix());
  69262. rotMatInv.invert();
  69263. var scaleMatrix = Bone._tmpMats[2];
  69264. scaleMatrix.copyFrom(this._scaleMatrix);
  69265. if (this._parent) {
  69266. var pscaleMatrix = Bone._tmpMats[3];
  69267. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69268. pscaleMatrix.invert();
  69269. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69270. }
  69271. else {
  69272. scaleMatrix.m[0] *= this._scalingDeterminant;
  69273. }
  69274. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69275. }
  69276. };
  69277. /**
  69278. * Get the scale of the bone
  69279. * @returns the scale of the bone
  69280. */
  69281. Bone.prototype.getScale = function () {
  69282. return this._scaleVector.clone();
  69283. };
  69284. /**
  69285. * Copy the scale of the bone to a vector3.
  69286. * @param result The vector3 to copy the scale to
  69287. */
  69288. Bone.prototype.getScaleToRef = function (result) {
  69289. result.copyFrom(this._scaleVector);
  69290. };
  69291. /**
  69292. * Get the position of the bone in local or world space.
  69293. * @param space The space that the returned position is in.
  69294. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69295. * @returns The position of the bone
  69296. */
  69297. Bone.prototype.getPosition = function (space, mesh) {
  69298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69299. if (mesh === void 0) { mesh = null; }
  69300. var pos = BABYLON.Vector3.Zero();
  69301. this.getPositionToRef(space, mesh, pos);
  69302. return pos;
  69303. };
  69304. /**
  69305. * Copy the position of the bone to a vector3 in local or world space.
  69306. * @param space The space that the returned position is in.
  69307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69308. * @param result The vector3 to copy the position to.
  69309. */
  69310. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69312. if (space == BABYLON.Space.LOCAL) {
  69313. var lm = this.getLocalMatrix();
  69314. result.x = lm.m[12];
  69315. result.y = lm.m[13];
  69316. result.z = lm.m[14];
  69317. }
  69318. else {
  69319. var wm = null;
  69320. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69321. if (mesh) {
  69322. wm = mesh.getWorldMatrix();
  69323. }
  69324. this._skeleton.computeAbsoluteTransforms();
  69325. var tmat = Bone._tmpMats[0];
  69326. if (mesh && wm) {
  69327. tmat.copyFrom(this.getAbsoluteTransform());
  69328. tmat.multiplyToRef(wm, tmat);
  69329. }
  69330. else {
  69331. tmat = this.getAbsoluteTransform();
  69332. }
  69333. result.x = tmat.m[12];
  69334. result.y = tmat.m[13];
  69335. result.z = tmat.m[14];
  69336. }
  69337. };
  69338. /**
  69339. * Get the absolute position of the bone (world space).
  69340. * @param mesh The mesh that this bone is attached to.
  69341. * @returns The absolute position of the bone
  69342. */
  69343. Bone.prototype.getAbsolutePosition = function (mesh) {
  69344. if (mesh === void 0) { mesh = null; }
  69345. var pos = BABYLON.Vector3.Zero();
  69346. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69347. return pos;
  69348. };
  69349. /**
  69350. * Copy the absolute position of the bone (world space) to the result param.
  69351. * @param mesh The mesh that this bone is attached to.
  69352. * @param result The vector3 to copy the absolute position to.
  69353. */
  69354. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69355. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69356. };
  69357. /**
  69358. * Compute the absolute transforms of this bone and its children.
  69359. */
  69360. Bone.prototype.computeAbsoluteTransforms = function () {
  69361. if (this._parent) {
  69362. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69363. }
  69364. else {
  69365. this._absoluteTransform.copyFrom(this._localMatrix);
  69366. var poseMatrix = this._skeleton.getPoseMatrix();
  69367. if (poseMatrix) {
  69368. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69369. }
  69370. }
  69371. var children = this.children;
  69372. var len = children.length;
  69373. for (var i = 0; i < len; i++) {
  69374. children[i].computeAbsoluteTransforms();
  69375. }
  69376. };
  69377. Bone.prototype._syncScaleVector = function () {
  69378. var lm = this.getLocalMatrix();
  69379. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69380. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69381. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69382. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69383. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69384. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69385. this._scaleVector.x = xs * Math.sqrt(xsq);
  69386. this._scaleVector.y = ys * Math.sqrt(ysq);
  69387. this._scaleVector.z = zs * Math.sqrt(zsq);
  69388. if (this._parent) {
  69389. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69390. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69391. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69392. }
  69393. 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);
  69394. };
  69395. /**
  69396. * Get the world direction from an axis that is in the local space of the bone.
  69397. * @param localAxis The local direction that is used to compute the world direction.
  69398. * @param mesh The mesh that this bone is attached to.
  69399. * @returns The world direction
  69400. */
  69401. Bone.prototype.getDirection = function (localAxis, mesh) {
  69402. if (mesh === void 0) { mesh = null; }
  69403. var result = BABYLON.Vector3.Zero();
  69404. this.getDirectionToRef(localAxis, mesh, result);
  69405. return result;
  69406. };
  69407. /**
  69408. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69409. * @param localAxis The local direction that is used to compute the world direction.
  69410. * @param mesh The mesh that this bone is attached to.
  69411. * @param result The vector3 that the world direction will be copied to.
  69412. */
  69413. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69414. if (mesh === void 0) { mesh = null; }
  69415. var wm = null;
  69416. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69417. if (mesh) {
  69418. wm = mesh.getWorldMatrix();
  69419. }
  69420. this._skeleton.computeAbsoluteTransforms();
  69421. var mat = Bone._tmpMats[0];
  69422. mat.copyFrom(this.getAbsoluteTransform());
  69423. if (mesh && wm) {
  69424. mat.multiplyToRef(wm, mat);
  69425. }
  69426. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69427. result.normalize();
  69428. };
  69429. /**
  69430. * Get the euler rotation of the bone in local or world space.
  69431. * @param space The space that the rotation should be in.
  69432. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69433. * @returns The euler rotation
  69434. */
  69435. Bone.prototype.getRotation = function (space, mesh) {
  69436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69437. if (mesh === void 0) { mesh = null; }
  69438. var result = BABYLON.Vector3.Zero();
  69439. this.getRotationToRef(space, mesh, result);
  69440. return result;
  69441. };
  69442. /**
  69443. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69444. * @param space The space that the rotation should be in.
  69445. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69446. * @param result The vector3 that the rotation should be copied to.
  69447. */
  69448. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69449. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69450. if (mesh === void 0) { mesh = null; }
  69451. var quat = Bone._tmpQuat;
  69452. this.getRotationQuaternionToRef(space, mesh, quat);
  69453. quat.toEulerAnglesToRef(result);
  69454. };
  69455. /**
  69456. * Get the quaternion rotation of the bone in either local or world space.
  69457. * @param space The space that the rotation should be in.
  69458. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69459. * @returns The quaternion rotation
  69460. */
  69461. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69462. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69463. if (mesh === void 0) { mesh = null; }
  69464. var result = BABYLON.Quaternion.Identity();
  69465. this.getRotationQuaternionToRef(space, mesh, result);
  69466. return result;
  69467. };
  69468. /**
  69469. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69470. * @param space The space that the rotation should be in.
  69471. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69472. * @param result The quaternion that the rotation should be copied to.
  69473. */
  69474. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69476. if (mesh === void 0) { mesh = null; }
  69477. if (space == BABYLON.Space.LOCAL) {
  69478. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69479. }
  69480. else {
  69481. var mat = Bone._tmpMats[0];
  69482. var amat = this.getAbsoluteTransform();
  69483. if (mesh) {
  69484. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69485. }
  69486. else {
  69487. mat.copyFrom(amat);
  69488. }
  69489. mat.m[0] *= this._scalingDeterminant;
  69490. mat.m[1] *= this._scalingDeterminant;
  69491. mat.m[2] *= this._scalingDeterminant;
  69492. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69493. }
  69494. };
  69495. /**
  69496. * Get the rotation matrix of the bone in local or world space.
  69497. * @param space The space that the rotation should be in.
  69498. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69499. * @returns The rotation matrix
  69500. */
  69501. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69503. var result = BABYLON.Matrix.Identity();
  69504. this.getRotationMatrixToRef(space, mesh, result);
  69505. return result;
  69506. };
  69507. /**
  69508. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69509. * @param space The space that the rotation should be in.
  69510. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69511. * @param result The quaternion that the rotation should be copied to.
  69512. */
  69513. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69514. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69515. if (space == BABYLON.Space.LOCAL) {
  69516. this.getLocalMatrix().getRotationMatrixToRef(result);
  69517. }
  69518. else {
  69519. var mat = Bone._tmpMats[0];
  69520. var amat = this.getAbsoluteTransform();
  69521. if (mesh) {
  69522. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69523. }
  69524. else {
  69525. mat.copyFrom(amat);
  69526. }
  69527. mat.m[0] *= this._scalingDeterminant;
  69528. mat.m[1] *= this._scalingDeterminant;
  69529. mat.m[2] *= this._scalingDeterminant;
  69530. mat.getRotationMatrixToRef(result);
  69531. }
  69532. };
  69533. /**
  69534. * Get the world position of a point that is in the local space of the bone.
  69535. * @param position The local position
  69536. * @param mesh The mesh that this bone is attached to.
  69537. * @returns The world position
  69538. */
  69539. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69540. if (mesh === void 0) { mesh = null; }
  69541. var result = BABYLON.Vector3.Zero();
  69542. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69543. return result;
  69544. };
  69545. /**
  69546. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69547. * @param position The local position
  69548. * @param mesh The mesh that this bone is attached to.
  69549. * @param result The vector3 that the world position should be copied to.
  69550. */
  69551. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69552. if (mesh === void 0) { mesh = null; }
  69553. var wm = null;
  69554. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69555. if (mesh) {
  69556. wm = mesh.getWorldMatrix();
  69557. }
  69558. this._skeleton.computeAbsoluteTransforms();
  69559. var tmat = Bone._tmpMats[0];
  69560. if (mesh && wm) {
  69561. tmat.copyFrom(this.getAbsoluteTransform());
  69562. tmat.multiplyToRef(wm, tmat);
  69563. }
  69564. else {
  69565. tmat = this.getAbsoluteTransform();
  69566. }
  69567. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69568. };
  69569. /**
  69570. * Get the local position of a point that is in world space.
  69571. * @param position The world position
  69572. * @param mesh The mesh that this bone is attached to.
  69573. * @returns The local position
  69574. */
  69575. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69576. if (mesh === void 0) { mesh = null; }
  69577. var result = BABYLON.Vector3.Zero();
  69578. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69579. return result;
  69580. };
  69581. /**
  69582. * Get the local position of a point that is in world space and copy it to the result param.
  69583. * @param position The world position
  69584. * @param mesh The mesh that this bone is attached to.
  69585. * @param result The vector3 that the local position should be copied to.
  69586. */
  69587. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69588. if (mesh === void 0) { mesh = null; }
  69589. var wm = null;
  69590. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69591. if (mesh) {
  69592. wm = mesh.getWorldMatrix();
  69593. }
  69594. this._skeleton.computeAbsoluteTransforms();
  69595. var tmat = Bone._tmpMats[0];
  69596. tmat.copyFrom(this.getAbsoluteTransform());
  69597. if (mesh && wm) {
  69598. tmat.multiplyToRef(wm, tmat);
  69599. }
  69600. tmat.invert();
  69601. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69602. };
  69603. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69604. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69605. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69606. return Bone;
  69607. }(BABYLON.Node));
  69608. BABYLON.Bone = Bone;
  69609. })(BABYLON || (BABYLON = {}));
  69610. //# sourceMappingURL=babylon.bone.js.map
  69611. var BABYLON;
  69612. (function (BABYLON) {
  69613. var BoneIKController = /** @class */ (function () {
  69614. function BoneIKController(mesh, bone, options) {
  69615. this.targetPosition = BABYLON.Vector3.Zero();
  69616. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69617. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69618. this.poleAngle = 0;
  69619. this.slerpAmount = 1;
  69620. this._bone1Quat = BABYLON.Quaternion.Identity();
  69621. this._bone1Mat = BABYLON.Matrix.Identity();
  69622. this._bone2Ang = Math.PI;
  69623. this._maxAngle = Math.PI;
  69624. this._rightHandedSystem = false;
  69625. this._bendAxis = BABYLON.Vector3.Right();
  69626. this._slerping = false;
  69627. this._adjustRoll = 0;
  69628. this._bone2 = bone;
  69629. this._bone1 = bone.getParent();
  69630. if (!this._bone1) {
  69631. return;
  69632. }
  69633. this.mesh = mesh;
  69634. var bonePos = bone.getPosition();
  69635. if (bone.getAbsoluteTransform().determinant() > 0) {
  69636. this._rightHandedSystem = true;
  69637. this._bendAxis.x = 0;
  69638. this._bendAxis.y = 0;
  69639. this._bendAxis.z = -1;
  69640. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69641. this._adjustRoll = Math.PI * .5;
  69642. this._bendAxis.z = 1;
  69643. }
  69644. }
  69645. if (this._bone1.length) {
  69646. var boneScale1 = this._bone1.getScale();
  69647. var boneScale2 = this._bone2.getScale();
  69648. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69649. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69650. }
  69651. else if (this._bone1.children[0]) {
  69652. mesh.computeWorldMatrix(true);
  69653. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69654. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69655. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69656. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69657. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69658. }
  69659. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69660. this.maxAngle = Math.PI;
  69661. if (options) {
  69662. if (options.targetMesh) {
  69663. this.targetMesh = options.targetMesh;
  69664. this.targetMesh.computeWorldMatrix(true);
  69665. }
  69666. if (options.poleTargetMesh) {
  69667. this.poleTargetMesh = options.poleTargetMesh;
  69668. this.poleTargetMesh.computeWorldMatrix(true);
  69669. }
  69670. else if (options.poleTargetBone) {
  69671. this.poleTargetBone = options.poleTargetBone;
  69672. }
  69673. else if (this._bone1.getParent()) {
  69674. this.poleTargetBone = this._bone1.getParent();
  69675. }
  69676. if (options.poleTargetLocalOffset) {
  69677. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69678. }
  69679. if (options.poleAngle) {
  69680. this.poleAngle = options.poleAngle;
  69681. }
  69682. if (options.bendAxis) {
  69683. this._bendAxis.copyFrom(options.bendAxis);
  69684. }
  69685. if (options.maxAngle) {
  69686. this.maxAngle = options.maxAngle;
  69687. }
  69688. if (options.slerpAmount) {
  69689. this.slerpAmount = options.slerpAmount;
  69690. }
  69691. }
  69692. }
  69693. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69694. get: function () {
  69695. return this._maxAngle;
  69696. },
  69697. set: function (value) {
  69698. this._setMaxAngle(value);
  69699. },
  69700. enumerable: true,
  69701. configurable: true
  69702. });
  69703. BoneIKController.prototype._setMaxAngle = function (ang) {
  69704. if (ang < 0) {
  69705. ang = 0;
  69706. }
  69707. if (ang > Math.PI || ang == undefined) {
  69708. ang = Math.PI;
  69709. }
  69710. this._maxAngle = ang;
  69711. var a = this._bone1Length;
  69712. var b = this._bone2Length;
  69713. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69714. };
  69715. BoneIKController.prototype.update = function () {
  69716. var bone1 = this._bone1;
  69717. if (!bone1) {
  69718. return;
  69719. }
  69720. var target = this.targetPosition;
  69721. var poleTarget = this.poleTargetPosition;
  69722. var mat1 = BoneIKController._tmpMats[0];
  69723. var mat2 = BoneIKController._tmpMats[1];
  69724. if (this.targetMesh) {
  69725. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69726. }
  69727. if (this.poleTargetBone) {
  69728. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69729. }
  69730. else if (this.poleTargetMesh) {
  69731. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69732. }
  69733. var bonePos = BoneIKController._tmpVecs[0];
  69734. var zaxis = BoneIKController._tmpVecs[1];
  69735. var xaxis = BoneIKController._tmpVecs[2];
  69736. var yaxis = BoneIKController._tmpVecs[3];
  69737. var upAxis = BoneIKController._tmpVecs[4];
  69738. var _tmpQuat = BoneIKController._tmpQuat;
  69739. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69740. poleTarget.subtractToRef(bonePos, upAxis);
  69741. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69742. upAxis.y = 1;
  69743. }
  69744. else {
  69745. upAxis.normalize();
  69746. }
  69747. target.subtractToRef(bonePos, yaxis);
  69748. yaxis.normalize();
  69749. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69750. zaxis.normalize();
  69751. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69752. xaxis.normalize();
  69753. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69754. var a = this._bone1Length;
  69755. var b = this._bone2Length;
  69756. var c = BABYLON.Vector3.Distance(bonePos, target);
  69757. if (this._maxReach > 0) {
  69758. c = Math.min(this._maxReach, c);
  69759. }
  69760. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69761. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69762. if (acosa > 1) {
  69763. acosa = 1;
  69764. }
  69765. if (acosb > 1) {
  69766. acosb = 1;
  69767. }
  69768. if (acosa < -1) {
  69769. acosa = -1;
  69770. }
  69771. if (acosb < -1) {
  69772. acosb = -1;
  69773. }
  69774. var angA = Math.acos(acosa);
  69775. var angB = Math.acos(acosb);
  69776. var angC = -angA - angB;
  69777. if (this._rightHandedSystem) {
  69778. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69779. mat2.multiplyToRef(mat1, mat1);
  69780. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69781. mat2.multiplyToRef(mat1, mat1);
  69782. }
  69783. else {
  69784. var _tmpVec = BoneIKController._tmpVecs[5];
  69785. _tmpVec.copyFrom(this._bendAxis);
  69786. _tmpVec.x *= -1;
  69787. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69788. mat2.multiplyToRef(mat1, mat1);
  69789. }
  69790. if (this.poleAngle) {
  69791. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69792. mat1.multiplyToRef(mat2, mat1);
  69793. }
  69794. if (this._bone1) {
  69795. if (this.slerpAmount < 1) {
  69796. if (!this._slerping) {
  69797. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69798. }
  69799. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69800. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69801. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69802. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69803. this._slerping = true;
  69804. }
  69805. else {
  69806. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69807. this._bone1Mat.copyFrom(mat1);
  69808. this._slerping = false;
  69809. }
  69810. }
  69811. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69812. this._bone2Ang = angC;
  69813. };
  69814. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69815. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69816. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69817. return BoneIKController;
  69818. }());
  69819. BABYLON.BoneIKController = BoneIKController;
  69820. })(BABYLON || (BABYLON = {}));
  69821. //# sourceMappingURL=babylon.boneIKController.js.map
  69822. var BABYLON;
  69823. (function (BABYLON) {
  69824. var BoneLookController = /** @class */ (function () {
  69825. /**
  69826. * Create a BoneLookController
  69827. * @param mesh the mesh that the bone belongs to
  69828. * @param bone the bone that will be looking to the target
  69829. * @param target the target Vector3 to look at
  69830. * @param settings optional settings:
  69831. * - maxYaw: the maximum angle the bone will yaw to
  69832. * - minYaw: the minimum angle the bone will yaw to
  69833. * - maxPitch: the maximum angle the bone will pitch to
  69834. * - minPitch: the minimum angle the bone will yaw to
  69835. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69836. * - upAxis: the up axis of the coordinate system
  69837. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69838. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69839. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69840. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69841. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69842. * - adjustRoll: used to make an adjustment to the roll of the bone
  69843. **/
  69844. function BoneLookController(mesh, bone, target, options) {
  69845. /**
  69846. * The up axis of the coordinate system that is used when the bone is rotated.
  69847. */
  69848. this.upAxis = BABYLON.Vector3.Up();
  69849. /**
  69850. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69851. */
  69852. this.upAxisSpace = BABYLON.Space.LOCAL;
  69853. /**
  69854. * Used to make an adjustment to the yaw of the bone.
  69855. */
  69856. this.adjustYaw = 0;
  69857. /**
  69858. * Used to make an adjustment to the pitch of the bone.
  69859. */
  69860. this.adjustPitch = 0;
  69861. /**
  69862. * Used to make an adjustment to the roll of the bone.
  69863. */
  69864. this.adjustRoll = 0;
  69865. /**
  69866. * 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).
  69867. */
  69868. this.slerpAmount = 1;
  69869. this._boneQuat = BABYLON.Quaternion.Identity();
  69870. this._slerping = false;
  69871. this._firstFrameSkipped = false;
  69872. this._fowardAxis = BABYLON.Vector3.Forward();
  69873. this.mesh = mesh;
  69874. this.bone = bone;
  69875. this.target = target;
  69876. if (options) {
  69877. if (options.adjustYaw) {
  69878. this.adjustYaw = options.adjustYaw;
  69879. }
  69880. if (options.adjustPitch) {
  69881. this.adjustPitch = options.adjustPitch;
  69882. }
  69883. if (options.adjustRoll) {
  69884. this.adjustRoll = options.adjustRoll;
  69885. }
  69886. if (options.maxYaw != null) {
  69887. this.maxYaw = options.maxYaw;
  69888. }
  69889. else {
  69890. this.maxYaw = Math.PI;
  69891. }
  69892. if (options.minYaw != null) {
  69893. this.minYaw = options.minYaw;
  69894. }
  69895. else {
  69896. this.minYaw = -Math.PI;
  69897. }
  69898. if (options.maxPitch != null) {
  69899. this.maxPitch = options.maxPitch;
  69900. }
  69901. else {
  69902. this.maxPitch = Math.PI;
  69903. }
  69904. if (options.minPitch != null) {
  69905. this.minPitch = options.minPitch;
  69906. }
  69907. else {
  69908. this.minPitch = -Math.PI;
  69909. }
  69910. if (options.slerpAmount != null) {
  69911. this.slerpAmount = options.slerpAmount;
  69912. }
  69913. if (options.upAxis != null) {
  69914. this.upAxis = options.upAxis;
  69915. }
  69916. if (options.upAxisSpace != null) {
  69917. this.upAxisSpace = options.upAxisSpace;
  69918. }
  69919. if (options.yawAxis != null || options.pitchAxis != null) {
  69920. var newYawAxis = BABYLON.Axis.Y;
  69921. var newPitchAxis = BABYLON.Axis.X;
  69922. if (options.yawAxis != null) {
  69923. newYawAxis = options.yawAxis.clone();
  69924. newYawAxis.normalize();
  69925. }
  69926. if (options.pitchAxis != null) {
  69927. newPitchAxis = options.pitchAxis.clone();
  69928. newPitchAxis.normalize();
  69929. }
  69930. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69931. this._transformYawPitch = BABYLON.Matrix.Identity();
  69932. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69933. this._transformYawPitchInv = this._transformYawPitch.clone();
  69934. this._transformYawPitch.invert();
  69935. }
  69936. }
  69937. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69938. this.upAxisSpace = BABYLON.Space.LOCAL;
  69939. }
  69940. }
  69941. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69942. /**
  69943. * Get/set the minimum yaw angle that the bone can look to.
  69944. */
  69945. get: function () {
  69946. return this._minYaw;
  69947. },
  69948. set: function (value) {
  69949. this._minYaw = value;
  69950. this._minYawSin = Math.sin(value);
  69951. this._minYawCos = Math.cos(value);
  69952. if (this._maxYaw != null) {
  69953. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69954. this._yawRange = this._maxYaw - this._minYaw;
  69955. }
  69956. },
  69957. enumerable: true,
  69958. configurable: true
  69959. });
  69960. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69961. /**
  69962. * Get/set the maximum yaw angle that the bone can look to.
  69963. */
  69964. get: function () {
  69965. return this._maxYaw;
  69966. },
  69967. set: function (value) {
  69968. this._maxYaw = value;
  69969. this._maxYawSin = Math.sin(value);
  69970. this._maxYawCos = Math.cos(value);
  69971. if (this._minYaw != null) {
  69972. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69973. this._yawRange = this._maxYaw - this._minYaw;
  69974. }
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69980. /**
  69981. * Get/set the minimum pitch angle that the bone can look to.
  69982. */
  69983. get: function () {
  69984. return this._minPitch;
  69985. },
  69986. set: function (value) {
  69987. this._minPitch = value;
  69988. this._minPitchTan = Math.tan(value);
  69989. },
  69990. enumerable: true,
  69991. configurable: true
  69992. });
  69993. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69994. /**
  69995. * Get/set the maximum pitch angle that the bone can look to.
  69996. */
  69997. get: function () {
  69998. return this._maxPitch;
  69999. },
  70000. set: function (value) {
  70001. this._maxPitch = value;
  70002. this._maxPitchTan = Math.tan(value);
  70003. },
  70004. enumerable: true,
  70005. configurable: true
  70006. });
  70007. /**
  70008. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  70009. */
  70010. BoneLookController.prototype.update = function () {
  70011. //skip the first frame when slerping so that the mesh rotation is correct
  70012. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  70013. this._firstFrameSkipped = true;
  70014. return;
  70015. }
  70016. var bone = this.bone;
  70017. var bonePos = BoneLookController._tmpVecs[0];
  70018. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  70019. var target = this.target;
  70020. var _tmpMat1 = BoneLookController._tmpMats[0];
  70021. var _tmpMat2 = BoneLookController._tmpMats[1];
  70022. var mesh = this.mesh;
  70023. var parentBone = bone.getParent();
  70024. var upAxis = BoneLookController._tmpVecs[1];
  70025. upAxis.copyFrom(this.upAxis);
  70026. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  70027. if (this._transformYawPitch) {
  70028. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  70029. }
  70030. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  70031. }
  70032. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  70033. mesh.getDirectionToRef(upAxis, upAxis);
  70034. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  70035. upAxis.normalize();
  70036. }
  70037. }
  70038. var checkYaw = false;
  70039. var checkPitch = false;
  70040. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  70041. checkYaw = true;
  70042. }
  70043. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  70044. checkPitch = true;
  70045. }
  70046. if (checkYaw || checkPitch) {
  70047. var spaceMat = BoneLookController._tmpMats[2];
  70048. var spaceMatInv = BoneLookController._tmpMats[3];
  70049. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  70050. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  70051. }
  70052. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  70053. spaceMat.copyFrom(mesh.getWorldMatrix());
  70054. }
  70055. else {
  70056. var forwardAxis = BoneLookController._tmpVecs[2];
  70057. forwardAxis.copyFrom(this._fowardAxis);
  70058. if (this._transformYawPitch) {
  70059. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  70060. }
  70061. if (parentBone) {
  70062. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  70063. }
  70064. else {
  70065. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  70066. }
  70067. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  70068. rightAxis.normalize();
  70069. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  70070. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  70071. }
  70072. spaceMat.invertToRef(spaceMatInv);
  70073. var xzlen = null;
  70074. if (checkPitch) {
  70075. var localTarget = BoneLookController._tmpVecs[3];
  70076. target.subtractToRef(bonePos, localTarget);
  70077. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70078. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70079. var pitch = Math.atan2(localTarget.y, xzlen);
  70080. var newPitch = pitch;
  70081. if (pitch > this._maxPitch) {
  70082. localTarget.y = this._maxPitchTan * xzlen;
  70083. newPitch = this._maxPitch;
  70084. }
  70085. else if (pitch < this._minPitch) {
  70086. localTarget.y = this._minPitchTan * xzlen;
  70087. newPitch = this._minPitch;
  70088. }
  70089. if (pitch != newPitch) {
  70090. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70091. localTarget.addInPlace(bonePos);
  70092. target = localTarget;
  70093. }
  70094. }
  70095. if (checkYaw) {
  70096. var localTarget = BoneLookController._tmpVecs[4];
  70097. target.subtractToRef(bonePos, localTarget);
  70098. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70099. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70100. var newYaw = yaw;
  70101. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70102. if (xzlen == null) {
  70103. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70104. }
  70105. if (this._yawRange > Math.PI) {
  70106. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70107. localTarget.z = this._maxYawCos * xzlen;
  70108. localTarget.x = this._maxYawSin * xzlen;
  70109. newYaw = this._maxYaw;
  70110. }
  70111. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70112. localTarget.z = this._minYawCos * xzlen;
  70113. localTarget.x = this._minYawSin * xzlen;
  70114. newYaw = this._minYaw;
  70115. }
  70116. }
  70117. else {
  70118. if (yaw > this._maxYaw) {
  70119. localTarget.z = this._maxYawCos * xzlen;
  70120. localTarget.x = this._maxYawSin * xzlen;
  70121. newYaw = this._maxYaw;
  70122. }
  70123. else if (yaw < this._minYaw) {
  70124. localTarget.z = this._minYawCos * xzlen;
  70125. localTarget.x = this._minYawSin * xzlen;
  70126. newYaw = this._minYaw;
  70127. }
  70128. }
  70129. }
  70130. if (this._slerping && this._yawRange > Math.PI) {
  70131. //are we going to be crossing into the min/max region?
  70132. var boneFwd = BoneLookController._tmpVecs[8];
  70133. boneFwd.copyFrom(BABYLON.Axis.Z);
  70134. if (this._transformYawPitch) {
  70135. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70136. }
  70137. var boneRotMat = BoneLookController._tmpMats[4];
  70138. this._boneQuat.toRotationMatrix(boneRotMat);
  70139. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70140. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70141. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70142. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70143. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70144. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70145. if (angBtwTar > angBtwMidYaw) {
  70146. if (xzlen == null) {
  70147. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70148. }
  70149. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70150. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70151. if (angBtwMin < angBtwMax) {
  70152. newYaw = boneYaw + Math.PI * .75;
  70153. localTarget.z = Math.cos(newYaw) * xzlen;
  70154. localTarget.x = Math.sin(newYaw) * xzlen;
  70155. }
  70156. else {
  70157. newYaw = boneYaw - Math.PI * .75;
  70158. localTarget.z = Math.cos(newYaw) * xzlen;
  70159. localTarget.x = Math.sin(newYaw) * xzlen;
  70160. }
  70161. }
  70162. }
  70163. if (yaw != newYaw) {
  70164. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70165. localTarget.addInPlace(bonePos);
  70166. target = localTarget;
  70167. }
  70168. }
  70169. }
  70170. var zaxis = BoneLookController._tmpVecs[5];
  70171. var xaxis = BoneLookController._tmpVecs[6];
  70172. var yaxis = BoneLookController._tmpVecs[7];
  70173. var _tmpQuat = BoneLookController._tmpQuat;
  70174. target.subtractToRef(bonePos, zaxis);
  70175. zaxis.normalize();
  70176. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70177. xaxis.normalize();
  70178. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70179. yaxis.normalize();
  70180. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70181. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70182. return;
  70183. }
  70184. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70185. return;
  70186. }
  70187. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70188. return;
  70189. }
  70190. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70191. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70192. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70193. }
  70194. if (this.slerpAmount < 1) {
  70195. if (!this._slerping) {
  70196. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70197. }
  70198. if (this._transformYawPitch) {
  70199. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70200. }
  70201. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70202. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70203. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70204. this._slerping = true;
  70205. }
  70206. else {
  70207. if (this._transformYawPitch) {
  70208. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70209. }
  70210. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70211. this._slerping = false;
  70212. }
  70213. };
  70214. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70215. var angDiff = ang2 - ang1;
  70216. angDiff %= Math.PI * 2;
  70217. if (angDiff > Math.PI) {
  70218. angDiff -= Math.PI * 2;
  70219. }
  70220. else if (angDiff < -Math.PI) {
  70221. angDiff += Math.PI * 2;
  70222. }
  70223. return angDiff;
  70224. };
  70225. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70226. ang1 %= (2 * Math.PI);
  70227. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70228. ang2 %= (2 * Math.PI);
  70229. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70230. var ab = 0;
  70231. if (ang1 < ang2) {
  70232. ab = ang2 - ang1;
  70233. }
  70234. else {
  70235. ab = ang1 - ang2;
  70236. }
  70237. if (ab > Math.PI) {
  70238. ab = Math.PI * 2 - ab;
  70239. }
  70240. return ab;
  70241. };
  70242. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70243. ang %= (2 * Math.PI);
  70244. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70245. ang1 %= (2 * Math.PI);
  70246. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70247. ang2 %= (2 * Math.PI);
  70248. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70249. if (ang1 < ang2) {
  70250. if (ang > ang1 && ang < ang2) {
  70251. return true;
  70252. }
  70253. }
  70254. else {
  70255. if (ang > ang2 && ang < ang1) {
  70256. return true;
  70257. }
  70258. }
  70259. return false;
  70260. };
  70261. 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()];
  70262. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70263. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70264. return BoneLookController;
  70265. }());
  70266. BABYLON.BoneLookController = BoneLookController;
  70267. })(BABYLON || (BABYLON = {}));
  70268. //# sourceMappingURL=babylon.boneLookController.js.map
  70269. var BABYLON;
  70270. (function (BABYLON) {
  70271. var Skeleton = /** @class */ (function () {
  70272. function Skeleton(name, id, scene) {
  70273. this.name = name;
  70274. this.id = id;
  70275. this.bones = new Array();
  70276. this.needInitialSkinMatrix = false;
  70277. this._isDirty = true;
  70278. this._meshesWithPoseMatrix = new Array();
  70279. this._identity = BABYLON.Matrix.Identity();
  70280. this._ranges = {};
  70281. this._lastAbsoluteTransformsUpdateId = -1;
  70282. /**
  70283. * Specifies if the skeleton should be serialized.
  70284. */
  70285. this.doNotSerialize = false;
  70286. // Events
  70287. /**
  70288. * An event triggered before computing the skeleton's matrices
  70289. * @type {BABYLON.Observable}
  70290. */
  70291. this.onBeforeComputeObservable = new BABYLON.Observable();
  70292. this.bones = [];
  70293. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70294. scene.skeletons.push(this);
  70295. //make sure it will recalculate the matrix next time prepare is called.
  70296. this._isDirty = true;
  70297. }
  70298. // Members
  70299. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70300. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70301. return mesh._bonesTransformMatrices;
  70302. }
  70303. if (!this._transformMatrices) {
  70304. this.prepare();
  70305. }
  70306. return this._transformMatrices;
  70307. };
  70308. Skeleton.prototype.getScene = function () {
  70309. return this._scene;
  70310. };
  70311. // Methods
  70312. /**
  70313. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70314. */
  70315. Skeleton.prototype.toString = function (fullDetails) {
  70316. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70317. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70318. if (fullDetails) {
  70319. ret += ", Ranges: {";
  70320. var first = true;
  70321. for (var name_1 in this._ranges) {
  70322. if (first) {
  70323. ret += ", ";
  70324. first = false;
  70325. }
  70326. ret += name_1;
  70327. }
  70328. ret += "}";
  70329. }
  70330. return ret;
  70331. };
  70332. /**
  70333. * Get bone's index searching by name
  70334. * @param {string} name is bone's name to search for
  70335. * @return {number} Indice of the bone. Returns -1 if not found
  70336. */
  70337. Skeleton.prototype.getBoneIndexByName = function (name) {
  70338. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70339. if (this.bones[boneIndex].name === name) {
  70340. return boneIndex;
  70341. }
  70342. }
  70343. return -1;
  70344. };
  70345. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70346. // check name not already in use
  70347. if (!this._ranges[name]) {
  70348. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70349. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70350. if (this.bones[i].animations[0]) {
  70351. this.bones[i].animations[0].createRange(name, from, to);
  70352. }
  70353. }
  70354. }
  70355. };
  70356. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70357. if (deleteFrames === void 0) { deleteFrames = true; }
  70358. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70359. if (this.bones[i].animations[0]) {
  70360. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70361. }
  70362. }
  70363. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70364. };
  70365. Skeleton.prototype.getAnimationRange = function (name) {
  70366. return this._ranges[name];
  70367. };
  70368. /**
  70369. * Returns as an Array, all AnimationRanges defined on this skeleton
  70370. */
  70371. Skeleton.prototype.getAnimationRanges = function () {
  70372. var animationRanges = [];
  70373. var name;
  70374. var i = 0;
  70375. for (name in this._ranges) {
  70376. animationRanges[i] = this._ranges[name];
  70377. i++;
  70378. }
  70379. return animationRanges;
  70380. };
  70381. /**
  70382. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70383. */
  70384. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70385. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70386. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70387. return false;
  70388. }
  70389. var ret = true;
  70390. var frameOffset = this._getHighestAnimationFrame() + 1;
  70391. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70392. var boneDict = {};
  70393. var sourceBones = source.bones;
  70394. var nBones;
  70395. var i;
  70396. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70397. boneDict[sourceBones[i].name] = sourceBones[i];
  70398. }
  70399. if (this.bones.length !== sourceBones.length) {
  70400. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70401. ret = false;
  70402. }
  70403. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70404. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70405. var boneName = this.bones[i].name;
  70406. var sourceBone = boneDict[boneName];
  70407. if (sourceBone) {
  70408. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70409. }
  70410. else {
  70411. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70412. ret = false;
  70413. }
  70414. }
  70415. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70416. var range = source.getAnimationRange(name);
  70417. if (range) {
  70418. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70419. }
  70420. return ret;
  70421. };
  70422. Skeleton.prototype.returnToRest = function () {
  70423. for (var index = 0; index < this.bones.length; index++) {
  70424. this.bones[index].returnToRest();
  70425. }
  70426. };
  70427. Skeleton.prototype._getHighestAnimationFrame = function () {
  70428. var ret = 0;
  70429. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70430. if (this.bones[i].animations[0]) {
  70431. var highest = this.bones[i].animations[0].getHighestFrame();
  70432. if (ret < highest) {
  70433. ret = highest;
  70434. }
  70435. }
  70436. }
  70437. return ret;
  70438. };
  70439. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70440. var range = this.getAnimationRange(name);
  70441. if (!range) {
  70442. return null;
  70443. }
  70444. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70445. };
  70446. Skeleton.prototype._markAsDirty = function () {
  70447. this._isDirty = true;
  70448. };
  70449. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70450. this._meshesWithPoseMatrix.push(mesh);
  70451. };
  70452. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70453. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70454. if (index > -1) {
  70455. this._meshesWithPoseMatrix.splice(index, 1);
  70456. }
  70457. };
  70458. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70459. this.onBeforeComputeObservable.notifyObservers(this);
  70460. for (var index = 0; index < this.bones.length; index++) {
  70461. var bone = this.bones[index];
  70462. var parentBone = bone.getParent();
  70463. if (parentBone) {
  70464. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70465. }
  70466. else {
  70467. if (initialSkinMatrix) {
  70468. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70469. }
  70470. else {
  70471. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70472. }
  70473. }
  70474. if (bone._index !== -1) {
  70475. var mappedIndex = bone._index === null ? index : bone._index;
  70476. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70477. }
  70478. }
  70479. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70480. };
  70481. Skeleton.prototype.prepare = function () {
  70482. if (!this._isDirty) {
  70483. return;
  70484. }
  70485. if (this.needInitialSkinMatrix) {
  70486. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70487. var mesh = this._meshesWithPoseMatrix[index];
  70488. var poseMatrix = mesh.getPoseMatrix();
  70489. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70490. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70491. }
  70492. if (this._synchronizedWithMesh !== mesh) {
  70493. this._synchronizedWithMesh = mesh;
  70494. // Prepare bones
  70495. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70496. var bone = this.bones[boneIndex];
  70497. if (!bone.getParent()) {
  70498. var matrix = bone.getBaseMatrix();
  70499. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70500. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70501. }
  70502. }
  70503. }
  70504. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70505. }
  70506. }
  70507. else {
  70508. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70509. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70510. }
  70511. this._computeTransformMatrices(this._transformMatrices, null);
  70512. }
  70513. this._isDirty = false;
  70514. this._scene._activeBones.addCount(this.bones.length, false);
  70515. };
  70516. Skeleton.prototype.getAnimatables = function () {
  70517. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70518. this._animatables = [];
  70519. for (var index = 0; index < this.bones.length; index++) {
  70520. this._animatables.push(this.bones[index]);
  70521. }
  70522. }
  70523. return this._animatables;
  70524. };
  70525. Skeleton.prototype.clone = function (name, id) {
  70526. var result = new Skeleton(name, id || name, this._scene);
  70527. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70528. for (var index = 0; index < this.bones.length; index++) {
  70529. var source = this.bones[index];
  70530. var parentBone = null;
  70531. var parent_1 = source.getParent();
  70532. if (parent_1) {
  70533. var parentIndex = this.bones.indexOf(parent_1);
  70534. parentBone = result.bones[parentIndex];
  70535. }
  70536. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70537. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70538. }
  70539. if (this._ranges) {
  70540. result._ranges = {};
  70541. for (var rangeName in this._ranges) {
  70542. var range = this._ranges[rangeName];
  70543. if (range) {
  70544. result._ranges[rangeName] = range.clone();
  70545. }
  70546. }
  70547. }
  70548. this._isDirty = true;
  70549. return result;
  70550. };
  70551. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70552. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70553. this.bones.forEach(function (bone) {
  70554. bone.animations.forEach(function (animation) {
  70555. animation.enableBlending = true;
  70556. animation.blendingSpeed = blendingSpeed;
  70557. });
  70558. });
  70559. };
  70560. Skeleton.prototype.dispose = function () {
  70561. this._meshesWithPoseMatrix = [];
  70562. // Animations
  70563. this.getScene().stopAnimation(this);
  70564. // Remove from scene
  70565. this.getScene().removeSkeleton(this);
  70566. };
  70567. Skeleton.prototype.serialize = function () {
  70568. var serializationObject = {};
  70569. serializationObject.name = this.name;
  70570. serializationObject.id = this.id;
  70571. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70572. serializationObject.bones = [];
  70573. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70574. for (var index = 0; index < this.bones.length; index++) {
  70575. var bone = this.bones[index];
  70576. var parent_2 = bone.getParent();
  70577. var serializedBone = {
  70578. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70579. name: bone.name,
  70580. matrix: bone.getBaseMatrix().toArray(),
  70581. rest: bone.getRestPose().toArray()
  70582. };
  70583. serializationObject.bones.push(serializedBone);
  70584. if (bone.length) {
  70585. serializedBone.length = bone.length;
  70586. }
  70587. if (bone.animations && bone.animations.length > 0) {
  70588. serializedBone.animation = bone.animations[0].serialize();
  70589. }
  70590. serializationObject.ranges = [];
  70591. for (var name in this._ranges) {
  70592. var source = this._ranges[name];
  70593. if (!source) {
  70594. continue;
  70595. }
  70596. var range = {};
  70597. range.name = name;
  70598. range.from = source.from;
  70599. range.to = source.to;
  70600. serializationObject.ranges.push(range);
  70601. }
  70602. }
  70603. return serializationObject;
  70604. };
  70605. Skeleton.Parse = function (parsedSkeleton, scene) {
  70606. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70607. if (parsedSkeleton.dimensionsAtRest) {
  70608. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70609. }
  70610. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70611. var index;
  70612. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70613. var parsedBone = parsedSkeleton.bones[index];
  70614. var parentBone = null;
  70615. if (parsedBone.parentBoneIndex > -1) {
  70616. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70617. }
  70618. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70619. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70620. if (parsedBone.length) {
  70621. bone.length = parsedBone.length;
  70622. }
  70623. if (parsedBone.animation) {
  70624. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70625. }
  70626. }
  70627. // placed after bones, so createAnimationRange can cascade down
  70628. if (parsedSkeleton.ranges) {
  70629. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70630. var data = parsedSkeleton.ranges[index];
  70631. skeleton.createAnimationRange(data.name, data.from, data.to);
  70632. }
  70633. }
  70634. return skeleton;
  70635. };
  70636. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70637. if (forceUpdate === void 0) { forceUpdate = false; }
  70638. var renderId = this._scene.getRenderId();
  70639. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70640. this.bones[0].computeAbsoluteTransforms();
  70641. this._lastAbsoluteTransformsUpdateId = renderId;
  70642. }
  70643. };
  70644. Skeleton.prototype.getPoseMatrix = function () {
  70645. var poseMatrix = null;
  70646. if (this._meshesWithPoseMatrix.length > 0) {
  70647. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70648. }
  70649. return poseMatrix;
  70650. };
  70651. Skeleton.prototype.sortBones = function () {
  70652. var bones = new Array();
  70653. var visited = new Array(this.bones.length);
  70654. for (var index = 0; index < this.bones.length; index++) {
  70655. this._sortBones(index, bones, visited);
  70656. }
  70657. this.bones = bones;
  70658. };
  70659. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70660. if (visited[index]) {
  70661. return;
  70662. }
  70663. visited[index] = true;
  70664. var bone = this.bones[index];
  70665. if (bone._index === undefined) {
  70666. bone._index = index;
  70667. }
  70668. var parentBone = bone.getParent();
  70669. if (parentBone) {
  70670. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70671. }
  70672. bones.push(bone);
  70673. };
  70674. return Skeleton;
  70675. }());
  70676. BABYLON.Skeleton = Skeleton;
  70677. })(BABYLON || (BABYLON = {}));
  70678. //# sourceMappingURL=babylon.skeleton.js.map
  70679. var BABYLON;
  70680. (function (BABYLON) {
  70681. var SphericalPolynomial = /** @class */ (function () {
  70682. function SphericalPolynomial() {
  70683. this.x = BABYLON.Vector3.Zero();
  70684. this.y = BABYLON.Vector3.Zero();
  70685. this.z = BABYLON.Vector3.Zero();
  70686. this.xx = BABYLON.Vector3.Zero();
  70687. this.yy = BABYLON.Vector3.Zero();
  70688. this.zz = BABYLON.Vector3.Zero();
  70689. this.xy = BABYLON.Vector3.Zero();
  70690. this.yz = BABYLON.Vector3.Zero();
  70691. this.zx = BABYLON.Vector3.Zero();
  70692. }
  70693. SphericalPolynomial.prototype.addAmbient = function (color) {
  70694. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70695. this.xx = this.xx.add(colorVector);
  70696. this.yy = this.yy.add(colorVector);
  70697. this.zz = this.zz.add(colorVector);
  70698. };
  70699. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70700. var result = new SphericalPolynomial();
  70701. result.x = harmonics.L11.scale(1.02333);
  70702. result.y = harmonics.L1_1.scale(1.02333);
  70703. result.z = harmonics.L10.scale(1.02333);
  70704. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70705. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70706. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70707. result.yz = harmonics.L2_1.scale(0.858086);
  70708. result.zx = harmonics.L21.scale(0.858086);
  70709. result.xy = harmonics.L2_2.scale(0.858086);
  70710. result.scale(1.0 / Math.PI);
  70711. return result;
  70712. };
  70713. SphericalPolynomial.prototype.scale = function (scale) {
  70714. this.x = this.x.scale(scale);
  70715. this.y = this.y.scale(scale);
  70716. this.z = this.z.scale(scale);
  70717. this.xx = this.xx.scale(scale);
  70718. this.yy = this.yy.scale(scale);
  70719. this.zz = this.zz.scale(scale);
  70720. this.yz = this.yz.scale(scale);
  70721. this.zx = this.zx.scale(scale);
  70722. this.xy = this.xy.scale(scale);
  70723. };
  70724. return SphericalPolynomial;
  70725. }());
  70726. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70727. var SphericalHarmonics = /** @class */ (function () {
  70728. function SphericalHarmonics() {
  70729. this.L00 = BABYLON.Vector3.Zero();
  70730. this.L1_1 = BABYLON.Vector3.Zero();
  70731. this.L10 = BABYLON.Vector3.Zero();
  70732. this.L11 = BABYLON.Vector3.Zero();
  70733. this.L2_2 = BABYLON.Vector3.Zero();
  70734. this.L2_1 = BABYLON.Vector3.Zero();
  70735. this.L20 = BABYLON.Vector3.Zero();
  70736. this.L21 = BABYLON.Vector3.Zero();
  70737. this.L22 = BABYLON.Vector3.Zero();
  70738. }
  70739. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70740. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70741. var c = colorVector.scale(deltaSolidAngle);
  70742. this.L00 = this.L00.add(c.scale(0.282095));
  70743. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70744. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70745. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70746. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70747. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70748. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70749. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70750. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70751. };
  70752. SphericalHarmonics.prototype.scale = function (scale) {
  70753. this.L00 = this.L00.scale(scale);
  70754. this.L1_1 = this.L1_1.scale(scale);
  70755. this.L10 = this.L10.scale(scale);
  70756. this.L11 = this.L11.scale(scale);
  70757. this.L2_2 = this.L2_2.scale(scale);
  70758. this.L2_1 = this.L2_1.scale(scale);
  70759. this.L20 = this.L20.scale(scale);
  70760. this.L21 = this.L21.scale(scale);
  70761. this.L22 = this.L22.scale(scale);
  70762. };
  70763. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70764. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70765. //
  70766. // E_lm = A_l * L_lm
  70767. //
  70768. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70769. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70770. // the scaling factors are given in equation 9.
  70771. // Constant (Band 0)
  70772. this.L00 = this.L00.scale(3.141593);
  70773. // Linear (Band 1)
  70774. this.L1_1 = this.L1_1.scale(2.094395);
  70775. this.L10 = this.L10.scale(2.094395);
  70776. this.L11 = this.L11.scale(2.094395);
  70777. // Quadratic (Band 2)
  70778. this.L2_2 = this.L2_2.scale(0.785398);
  70779. this.L2_1 = this.L2_1.scale(0.785398);
  70780. this.L20 = this.L20.scale(0.785398);
  70781. this.L21 = this.L21.scale(0.785398);
  70782. this.L22 = this.L22.scale(0.785398);
  70783. };
  70784. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70785. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70786. // L = (1/pi) * E * rho
  70787. //
  70788. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70789. this.scale(1.0 / Math.PI);
  70790. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70791. // (The pixel shader must apply albedo after texture fetches, etc).
  70792. };
  70793. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70794. var result = new SphericalHarmonics();
  70795. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70796. result.L1_1 = polynomial.y.scale(0.977204);
  70797. result.L10 = polynomial.z.scale(0.977204);
  70798. result.L11 = polynomial.x.scale(0.977204);
  70799. result.L2_2 = polynomial.xy.scale(1.16538);
  70800. result.L2_1 = polynomial.yz.scale(1.16538);
  70801. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70802. result.L21 = polynomial.zx.scale(1.16538);
  70803. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70804. result.scale(Math.PI);
  70805. return result;
  70806. };
  70807. return SphericalHarmonics;
  70808. }());
  70809. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70810. })(BABYLON || (BABYLON = {}));
  70811. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70812. var BABYLON;
  70813. (function (BABYLON) {
  70814. var FileFaceOrientation = /** @class */ (function () {
  70815. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70816. this.name = name;
  70817. this.worldAxisForNormal = worldAxisForNormal;
  70818. this.worldAxisForFileX = worldAxisForFileX;
  70819. this.worldAxisForFileY = worldAxisForFileY;
  70820. }
  70821. return FileFaceOrientation;
  70822. }());
  70823. ;
  70824. /**
  70825. * Helper class dealing with the extraction of spherical polynomial dataArray
  70826. * from a cube map.
  70827. */
  70828. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70829. function CubeMapToSphericalPolynomialTools() {
  70830. }
  70831. /**
  70832. * Converts a texture to the according Spherical Polynomial data.
  70833. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70834. *
  70835. * @param texture The texture to extract the information from.
  70836. * @return The Spherical Polynomial data.
  70837. */
  70838. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70839. if (!texture.isCube) {
  70840. // Only supports cube Textures currently.
  70841. return null;
  70842. }
  70843. var size = texture.getSize().width;
  70844. var right = texture.readPixels(0);
  70845. var left = texture.readPixels(1);
  70846. var up;
  70847. var down;
  70848. if (texture.isRenderTarget) {
  70849. up = texture.readPixels(3);
  70850. down = texture.readPixels(2);
  70851. }
  70852. else {
  70853. up = texture.readPixels(2);
  70854. down = texture.readPixels(3);
  70855. }
  70856. var front = texture.readPixels(4);
  70857. var back = texture.readPixels(5);
  70858. var gammaSpace = texture.gammaSpace;
  70859. // Always read as RGBA.
  70860. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70861. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70862. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70863. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70864. }
  70865. var cubeInfo = {
  70866. size: size,
  70867. right: right,
  70868. left: left,
  70869. up: up,
  70870. down: down,
  70871. front: front,
  70872. back: back,
  70873. format: format,
  70874. type: type,
  70875. gammaSpace: gammaSpace,
  70876. };
  70877. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70878. };
  70879. /**
  70880. * Converts a cubemap to the according Spherical Polynomial data.
  70881. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70882. *
  70883. * @param cubeInfo The Cube map to extract the information from.
  70884. * @return The Spherical Polynomial data.
  70885. */
  70886. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70887. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70888. var totalSolidAngle = 0.0;
  70889. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70890. var du = 2.0 / cubeInfo.size;
  70891. var dv = du;
  70892. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70893. var minUV = du * 0.5 - 1.0;
  70894. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70895. var fileFace = this.FileFaces[faceIndex];
  70896. var dataArray = cubeInfo[fileFace.name];
  70897. var v = minUV;
  70898. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70899. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70900. // Because SP is still linear, so summation is fine in that basis.
  70901. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70902. for (var y = 0; y < cubeInfo.size; y++) {
  70903. var u = minUV;
  70904. for (var x = 0; x < cubeInfo.size; x++) {
  70905. // World direction (not normalised)
  70906. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70907. worldDirection.normalize();
  70908. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70909. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70910. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70911. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70912. // Handle Integer types.
  70913. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70914. r /= 255;
  70915. g /= 255;
  70916. b /= 255;
  70917. }
  70918. // Handle Gamma space textures.
  70919. if (cubeInfo.gammaSpace) {
  70920. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70921. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70922. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70923. }
  70924. var color = new BABYLON.Color3(r, g, b);
  70925. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70926. totalSolidAngle += deltaSolidAngle;
  70927. u += du;
  70928. }
  70929. v += dv;
  70930. }
  70931. }
  70932. // Solid angle for entire sphere is 4*pi
  70933. var sphereSolidAngle = 4.0 * Math.PI;
  70934. // Adjust the solid angle to allow for how many faces we processed.
  70935. var facesProcessed = 6.0;
  70936. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70937. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70938. // This is needed because the numerical integration over the cube uses a
  70939. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70940. // and also to compensate for accumulative error due to float precision in the summation.
  70941. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70942. sphericalHarmonics.scale(correctionFactor);
  70943. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70944. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70945. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70946. };
  70947. CubeMapToSphericalPolynomialTools.FileFaces = [
  70948. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70949. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70950. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70951. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70952. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70953. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70954. ];
  70955. return CubeMapToSphericalPolynomialTools;
  70956. }());
  70957. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70958. })(BABYLON || (BABYLON = {}));
  70959. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70960. var BABYLON;
  70961. (function (BABYLON) {
  70962. /**
  70963. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70964. */
  70965. var PanoramaToCubeMapTools = /** @class */ (function () {
  70966. function PanoramaToCubeMapTools() {
  70967. }
  70968. /**
  70969. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70970. *
  70971. * @param float32Array The source data.
  70972. * @param inputWidth The width of the input panorama.
  70973. * @param inputhHeight The height of the input panorama.
  70974. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70975. * @return The cubemap data
  70976. */
  70977. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70978. if (!float32Array) {
  70979. throw "ConvertPanoramaToCubemap: input cannot be null";
  70980. }
  70981. if (float32Array.length != inputWidth * inputHeight * 3) {
  70982. throw "ConvertPanoramaToCubemap: input size is wrong";
  70983. }
  70984. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70985. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70986. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70987. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70988. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70989. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70990. return {
  70991. front: textureFront,
  70992. back: textureBack,
  70993. left: textureLeft,
  70994. right: textureRight,
  70995. up: textureUp,
  70996. down: textureDown,
  70997. size: size,
  70998. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70999. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  71000. gammaSpace: false,
  71001. };
  71002. };
  71003. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  71004. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  71005. var textureArray = new Float32Array(buffer);
  71006. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  71007. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  71008. var dy = 1 / texSize;
  71009. var fy = 0;
  71010. for (var y = 0; y < texSize; y++) {
  71011. var xv1 = faceData[0];
  71012. var xv2 = faceData[2];
  71013. for (var x = 0; x < texSize; x++) {
  71014. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  71015. v.normalize();
  71016. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  71017. // 3 channels per pixels
  71018. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  71019. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  71020. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  71021. xv1 = xv1.add(rotDX1);
  71022. xv2 = xv2.add(rotDX2);
  71023. }
  71024. fy += dy;
  71025. }
  71026. return textureArray;
  71027. };
  71028. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  71029. var theta = Math.atan2(vDir.z, vDir.x);
  71030. var phi = Math.acos(vDir.y);
  71031. while (theta < -Math.PI)
  71032. theta += 2 * Math.PI;
  71033. while (theta > Math.PI)
  71034. theta -= 2 * Math.PI;
  71035. var dx = theta / Math.PI;
  71036. var dy = phi / Math.PI;
  71037. // recenter.
  71038. dx = dx * 0.5 + 0.5;
  71039. var px = Math.round(dx * inputWidth);
  71040. if (px < 0)
  71041. px = 0;
  71042. else if (px >= inputWidth)
  71043. px = inputWidth - 1;
  71044. var py = Math.round(dy * inputHeight);
  71045. if (py < 0)
  71046. py = 0;
  71047. else if (py >= inputHeight)
  71048. py = inputHeight - 1;
  71049. var inputY = (inputHeight - py - 1);
  71050. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  71051. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  71052. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  71053. return {
  71054. r: r,
  71055. g: g,
  71056. b: b
  71057. };
  71058. };
  71059. PanoramaToCubeMapTools.FACE_FRONT = [
  71060. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71061. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71062. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71063. new BABYLON.Vector3(1.0, 1.0, -1.0)
  71064. ];
  71065. PanoramaToCubeMapTools.FACE_BACK = [
  71066. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71067. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71068. new BABYLON.Vector3(1.0, 1.0, 1.0),
  71069. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  71070. ];
  71071. PanoramaToCubeMapTools.FACE_RIGHT = [
  71072. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71073. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71074. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71075. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71076. ];
  71077. PanoramaToCubeMapTools.FACE_LEFT = [
  71078. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71079. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71080. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71081. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  71082. ];
  71083. PanoramaToCubeMapTools.FACE_DOWN = [
  71084. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71085. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71086. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71087. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71088. ];
  71089. PanoramaToCubeMapTools.FACE_UP = [
  71090. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71091. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71092. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71093. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71094. ];
  71095. return PanoramaToCubeMapTools;
  71096. }());
  71097. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71098. })(BABYLON || (BABYLON = {}));
  71099. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71100. var BABYLON;
  71101. (function (BABYLON) {
  71102. ;
  71103. /**
  71104. * This groups tools to convert HDR texture to native colors array.
  71105. */
  71106. var HDRTools = /** @class */ (function () {
  71107. function HDRTools() {
  71108. }
  71109. HDRTools.Ldexp = function (mantissa, exponent) {
  71110. if (exponent > 1023) {
  71111. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71112. }
  71113. if (exponent < -1074) {
  71114. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71115. }
  71116. return mantissa * Math.pow(2, exponent);
  71117. };
  71118. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71119. if (exponent > 0) {
  71120. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71121. float32array[index + 0] = red * exponent;
  71122. float32array[index + 1] = green * exponent;
  71123. float32array[index + 2] = blue * exponent;
  71124. }
  71125. else {
  71126. float32array[index + 0] = 0;
  71127. float32array[index + 1] = 0;
  71128. float32array[index + 2] = 0;
  71129. }
  71130. };
  71131. HDRTools.readStringLine = function (uint8array, startIndex) {
  71132. var line = "";
  71133. var character = "";
  71134. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71135. character = String.fromCharCode(uint8array[i]);
  71136. if (character == "\n") {
  71137. break;
  71138. }
  71139. line += character;
  71140. }
  71141. return line;
  71142. };
  71143. /**
  71144. * Reads header information from an RGBE texture stored in a native array.
  71145. * More information on this format are available here:
  71146. * https://en.wikipedia.org/wiki/RGBE_image_format
  71147. *
  71148. * @param uint8array The binary file stored in native array.
  71149. * @return The header information.
  71150. */
  71151. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71152. var height = 0;
  71153. var width = 0;
  71154. var line = this.readStringLine(uint8array, 0);
  71155. if (line[0] != '#' || line[1] != '?') {
  71156. throw "Bad HDR Format.";
  71157. }
  71158. var endOfHeader = false;
  71159. var findFormat = false;
  71160. var lineIndex = 0;
  71161. do {
  71162. lineIndex += (line.length + 1);
  71163. line = this.readStringLine(uint8array, lineIndex);
  71164. if (line == "FORMAT=32-bit_rle_rgbe") {
  71165. findFormat = true;
  71166. }
  71167. else if (line.length == 0) {
  71168. endOfHeader = true;
  71169. }
  71170. } while (!endOfHeader);
  71171. if (!findFormat) {
  71172. throw "HDR Bad header format, unsupported FORMAT";
  71173. }
  71174. lineIndex += (line.length + 1);
  71175. line = this.readStringLine(uint8array, lineIndex);
  71176. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71177. var match = sizeRegexp.exec(line);
  71178. // TODO. Support +Y and -X if needed.
  71179. if (!match || match.length < 3) {
  71180. throw "HDR Bad header format, no size";
  71181. }
  71182. width = parseInt(match[2]);
  71183. height = parseInt(match[1]);
  71184. if (width < 8 || width > 0x7fff) {
  71185. throw "HDR Bad header format, unsupported size";
  71186. }
  71187. lineIndex += (line.length + 1);
  71188. return {
  71189. height: height,
  71190. width: width,
  71191. dataPosition: lineIndex
  71192. };
  71193. };
  71194. /**
  71195. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71196. * This RGBE texture needs to store the information as a panorama.
  71197. *
  71198. * More information on this format are available here:
  71199. * https://en.wikipedia.org/wiki/RGBE_image_format
  71200. *
  71201. * @param buffer The binary file stored in an array buffer.
  71202. * @param size The expected size of the extracted cubemap.
  71203. * @return The Cube Map information.
  71204. */
  71205. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71206. var uint8array = new Uint8Array(buffer);
  71207. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71208. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71209. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71210. return cubeMapData;
  71211. };
  71212. /**
  71213. * Returns the pixels data extracted from an RGBE texture.
  71214. * This pixels will be stored left to right up to down in the R G B order in one array.
  71215. *
  71216. * More information on this format are available here:
  71217. * https://en.wikipedia.org/wiki/RGBE_image_format
  71218. *
  71219. * @param uint8array The binary file stored in an array buffer.
  71220. * @param hdrInfo The header information of the file.
  71221. * @return The pixels data in RGB right to left up to down order.
  71222. */
  71223. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71224. // Keep for multi format supports.
  71225. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71226. };
  71227. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71228. var num_scanlines = hdrInfo.height;
  71229. var scanline_width = hdrInfo.width;
  71230. var a, b, c, d, count;
  71231. var dataIndex = hdrInfo.dataPosition;
  71232. var index = 0, endIndex = 0, i = 0;
  71233. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71234. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71235. // 3 channels of 4 bytes per pixel in float.
  71236. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71237. var resultArray = new Float32Array(resultBuffer);
  71238. // read in each successive scanline
  71239. while (num_scanlines > 0) {
  71240. a = uint8array[dataIndex++];
  71241. b = uint8array[dataIndex++];
  71242. c = uint8array[dataIndex++];
  71243. d = uint8array[dataIndex++];
  71244. if (a != 2 || b != 2 || (c & 0x80)) {
  71245. // this file is not run length encoded
  71246. throw "HDR Bad header format, not RLE";
  71247. }
  71248. if (((c << 8) | d) != scanline_width) {
  71249. throw "HDR Bad header format, wrong scan line width";
  71250. }
  71251. index = 0;
  71252. // read each of the four channels for the scanline into the buffer
  71253. for (i = 0; i < 4; i++) {
  71254. endIndex = (i + 1) * scanline_width;
  71255. while (index < endIndex) {
  71256. a = uint8array[dataIndex++];
  71257. b = uint8array[dataIndex++];
  71258. if (a > 128) {
  71259. // a run of the same value
  71260. count = a - 128;
  71261. if ((count == 0) || (count > endIndex - index)) {
  71262. throw "HDR Bad Format, bad scanline data (run)";
  71263. }
  71264. while (count-- > 0) {
  71265. scanLineArray[index++] = b;
  71266. }
  71267. }
  71268. else {
  71269. // a non-run
  71270. count = a;
  71271. if ((count == 0) || (count > endIndex - index)) {
  71272. throw "HDR Bad Format, bad scanline data (non-run)";
  71273. }
  71274. scanLineArray[index++] = b;
  71275. if (--count > 0) {
  71276. for (var j = 0; j < count; j++) {
  71277. scanLineArray[index++] = uint8array[dataIndex++];
  71278. }
  71279. }
  71280. }
  71281. }
  71282. }
  71283. // now convert data from buffer into floats
  71284. for (i = 0; i < scanline_width; i++) {
  71285. a = scanLineArray[i];
  71286. b = scanLineArray[i + scanline_width];
  71287. c = scanLineArray[i + 2 * scanline_width];
  71288. d = scanLineArray[i + 3 * scanline_width];
  71289. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71290. }
  71291. num_scanlines--;
  71292. }
  71293. return resultArray;
  71294. };
  71295. return HDRTools;
  71296. }());
  71297. BABYLON.HDRTools = HDRTools;
  71298. })(BABYLON || (BABYLON = {}));
  71299. //# sourceMappingURL=babylon.hdr.js.map
  71300. var BABYLON;
  71301. (function (BABYLON) {
  71302. /**
  71303. * This represents a texture coming from an HDR input.
  71304. *
  71305. * The only supported format is currently panorama picture stored in RGBE format.
  71306. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71307. */
  71308. var HDRCubeTexture = /** @class */ (function (_super) {
  71309. __extends(HDRCubeTexture, _super);
  71310. /**
  71311. * Instantiates an HDRTexture from the following parameters.
  71312. *
  71313. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71314. * @param scene The scene the texture will be used in
  71315. * @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.
  71316. * @param noMipmap Forces to not generate the mipmap if true
  71317. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71318. * @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)
  71319. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71320. */
  71321. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71322. if (noMipmap === void 0) { noMipmap = false; }
  71323. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71324. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71325. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71326. if (onLoad === void 0) { onLoad = null; }
  71327. if (onError === void 0) { onError = null; }
  71328. var _this = _super.call(this, scene) || this;
  71329. _this._useInGammaSpace = false;
  71330. _this._generateHarmonics = true;
  71331. _this._isBABYLONPreprocessed = false;
  71332. _this._onLoad = null;
  71333. _this._onError = null;
  71334. /**
  71335. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71336. */
  71337. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71338. /**
  71339. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71340. * This is usefull at run time to apply the good shader.
  71341. */
  71342. _this.isPMREM = false;
  71343. _this._isBlocking = true;
  71344. if (!url) {
  71345. return _this;
  71346. }
  71347. _this.name = url;
  71348. _this.url = url;
  71349. _this.hasAlpha = false;
  71350. _this.isCube = true;
  71351. _this._textureMatrix = BABYLON.Matrix.Identity();
  71352. _this._onLoad = onLoad;
  71353. _this._onError = onError;
  71354. _this.gammaSpace = false;
  71355. var caps = scene.getEngine().getCaps();
  71356. if (size) {
  71357. _this._isBABYLONPreprocessed = false;
  71358. _this._noMipmap = noMipmap;
  71359. _this._size = size;
  71360. _this._useInGammaSpace = useInGammaSpace;
  71361. _this._usePMREMGenerator = usePMREMGenerator &&
  71362. caps.textureLOD &&
  71363. caps.textureFloat &&
  71364. !_this._useInGammaSpace;
  71365. }
  71366. else {
  71367. _this._isBABYLONPreprocessed = true;
  71368. _this._noMipmap = false;
  71369. _this._useInGammaSpace = false;
  71370. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71371. !_this._useInGammaSpace;
  71372. }
  71373. _this.isPMREM = _this._usePMREMGenerator;
  71374. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71375. if (!_this._texture) {
  71376. if (!scene.useDelayedTextureLoading) {
  71377. _this.loadTexture();
  71378. }
  71379. else {
  71380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71381. }
  71382. }
  71383. return _this;
  71384. }
  71385. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71386. /**
  71387. * Gets wether or not the texture is blocking during loading.
  71388. */
  71389. get: function () {
  71390. return this._isBlocking;
  71391. },
  71392. /**
  71393. * Sets wether or not the texture is blocking during loading.
  71394. */
  71395. set: function (value) {
  71396. this._isBlocking = value;
  71397. },
  71398. enumerable: true,
  71399. configurable: true
  71400. });
  71401. /**
  71402. * Occurs when the file is a preprocessed .babylon.hdr file.
  71403. */
  71404. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71405. var _this = this;
  71406. var mipLevels = 0;
  71407. var floatArrayView = null;
  71408. var scene = this.getScene();
  71409. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71410. var mips = new Array();
  71411. if (!floatArrayView) {
  71412. return mips;
  71413. }
  71414. var startIndex = 30;
  71415. for (var level = 0; level < mipLevels; level++) {
  71416. mips.push([]);
  71417. // Fill each pixel of the mip level.
  71418. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71419. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71420. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71421. mips[level].push(faceData);
  71422. startIndex += faceSize;
  71423. }
  71424. }
  71425. return mips;
  71426. } : null;
  71427. var callback = function (buffer) {
  71428. var scene = _this.getScene();
  71429. if (!scene) {
  71430. return null;
  71431. }
  71432. // Create Native Array Views
  71433. var intArrayView = new Int32Array(buffer);
  71434. floatArrayView = new Float32Array(buffer);
  71435. // Fill header.
  71436. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71437. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71438. // Update Texture Information.
  71439. if (!_this._texture) {
  71440. return null;
  71441. }
  71442. _this._texture.updateSize(_this._size, _this._size);
  71443. // Fill polynomial information.
  71444. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71445. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71446. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71447. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71448. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71449. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71450. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71451. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71452. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71453. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71454. _this.sphericalPolynomial = sphericalPolynomial;
  71455. // Fill pixel data.
  71456. mipLevels = intArrayView[29]; // Number of mip levels.
  71457. var startIndex = 30;
  71458. var data = [];
  71459. var faceSize = Math.pow(_this._size, 2) * 3;
  71460. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71461. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71462. startIndex += faceSize;
  71463. }
  71464. var results = [];
  71465. var byteArray = null;
  71466. // Push each faces.
  71467. for (var k = 0; k < 6; k++) {
  71468. var dataFace = null;
  71469. // To be deprecated.
  71470. if (version === 1) {
  71471. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71472. dataFace = data[j];
  71473. }
  71474. // If special cases.
  71475. if (!mipmapGenerator && dataFace) {
  71476. if (!scene.getEngine().getCaps().textureFloat) {
  71477. // 3 channels of 1 bytes per pixel in bytes.
  71478. var byteBuffer = new ArrayBuffer(faceSize);
  71479. byteArray = new Uint8Array(byteBuffer);
  71480. }
  71481. for (var i = 0; i < _this._size * _this._size; i++) {
  71482. // Put in gamma space if requested.
  71483. if (_this._useInGammaSpace) {
  71484. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71485. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71486. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71487. }
  71488. // Convert to int texture for fallback.
  71489. if (byteArray) {
  71490. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71491. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71492. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71493. // May use luminance instead if the result is not accurate.
  71494. var max = Math.max(Math.max(r, g), b);
  71495. if (max > 255) {
  71496. var scale = 255 / max;
  71497. r *= scale;
  71498. g *= scale;
  71499. b *= scale;
  71500. }
  71501. byteArray[(i * 3) + 0] = r;
  71502. byteArray[(i * 3) + 1] = g;
  71503. byteArray[(i * 3) + 2] = b;
  71504. }
  71505. }
  71506. }
  71507. // Fill the array accordingly.
  71508. if (byteArray) {
  71509. results.push(byteArray);
  71510. }
  71511. else {
  71512. results.push(dataFace);
  71513. }
  71514. }
  71515. return results;
  71516. };
  71517. if (scene) {
  71518. 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);
  71519. }
  71520. };
  71521. /**
  71522. * Occurs when the file is raw .hdr file.
  71523. */
  71524. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71525. var _this = this;
  71526. var callback = function (buffer) {
  71527. var scene = _this.getScene();
  71528. if (!scene) {
  71529. return null;
  71530. }
  71531. // Extract the raw linear data.
  71532. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71533. // Generate harmonics if needed.
  71534. if (_this._generateHarmonics) {
  71535. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71536. _this.sphericalPolynomial = sphericalPolynomial;
  71537. }
  71538. var results = [];
  71539. var byteArray = null;
  71540. // Push each faces.
  71541. for (var j = 0; j < 6; j++) {
  71542. // Create uintarray fallback.
  71543. if (!scene.getEngine().getCaps().textureFloat) {
  71544. // 3 channels of 1 bytes per pixel in bytes.
  71545. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71546. byteArray = new Uint8Array(byteBuffer);
  71547. }
  71548. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71549. // If special cases.
  71550. if (_this._useInGammaSpace || byteArray) {
  71551. for (var i = 0; i < _this._size * _this._size; i++) {
  71552. // Put in gamma space if requested.
  71553. if (_this._useInGammaSpace) {
  71554. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71555. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71556. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71557. }
  71558. // Convert to int texture for fallback.
  71559. if (byteArray) {
  71560. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71561. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71562. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71563. // May use luminance instead if the result is not accurate.
  71564. var max = Math.max(Math.max(r, g), b);
  71565. if (max > 255) {
  71566. var scale = 255 / max;
  71567. r *= scale;
  71568. g *= scale;
  71569. b *= scale;
  71570. }
  71571. byteArray[(i * 3) + 0] = r;
  71572. byteArray[(i * 3) + 1] = g;
  71573. byteArray[(i * 3) + 2] = b;
  71574. }
  71575. }
  71576. }
  71577. if (byteArray) {
  71578. results.push(byteArray);
  71579. }
  71580. else {
  71581. results.push(dataFace);
  71582. }
  71583. }
  71584. return results;
  71585. };
  71586. var mipmapGenerator = null;
  71587. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71588. // if (!this._noMipmap &&
  71589. // this._usePMREMGenerator) {
  71590. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71591. // // Custom setup of the generator matching with the PBR shader values.
  71592. // var generator = new BABYLON.PMREMGenerator(data,
  71593. // this._size,
  71594. // this._size,
  71595. // 0,
  71596. // 3,
  71597. // this.getScene().getEngine().getCaps().textureFloat,
  71598. // 2048,
  71599. // 0.25,
  71600. // false,
  71601. // true);
  71602. // return generator.filterCubeMap();
  71603. // };
  71604. // }
  71605. var scene = this.getScene();
  71606. if (scene) {
  71607. 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);
  71608. }
  71609. };
  71610. /**
  71611. * Starts the loading process of the texture.
  71612. */
  71613. HDRCubeTexture.prototype.loadTexture = function () {
  71614. if (this._isBABYLONPreprocessed) {
  71615. this.loadBabylonTexture();
  71616. }
  71617. else {
  71618. this.loadHDRTexture();
  71619. }
  71620. };
  71621. HDRCubeTexture.prototype.clone = function () {
  71622. var scene = this.getScene();
  71623. if (!scene) {
  71624. return this;
  71625. }
  71626. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71627. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71628. // Base texture
  71629. newTexture.level = this.level;
  71630. newTexture.wrapU = this.wrapU;
  71631. newTexture.wrapV = this.wrapV;
  71632. newTexture.coordinatesIndex = this.coordinatesIndex;
  71633. newTexture.coordinatesMode = this.coordinatesMode;
  71634. return newTexture;
  71635. };
  71636. // Methods
  71637. HDRCubeTexture.prototype.delayLoad = function () {
  71638. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71639. return;
  71640. }
  71641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71642. this._texture = this._getFromCache(this.url, this._noMipmap);
  71643. if (!this._texture) {
  71644. this.loadTexture();
  71645. }
  71646. };
  71647. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71648. return this._textureMatrix;
  71649. };
  71650. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71651. this._textureMatrix = value;
  71652. };
  71653. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71654. var texture = null;
  71655. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71656. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71657. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71658. texture.name = parsedTexture.name;
  71659. texture.hasAlpha = parsedTexture.hasAlpha;
  71660. texture.level = parsedTexture.level;
  71661. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71662. texture.isBlocking = parsedTexture.isBlocking;
  71663. }
  71664. return texture;
  71665. };
  71666. HDRCubeTexture.prototype.serialize = function () {
  71667. if (!this.name) {
  71668. return null;
  71669. }
  71670. var serializationObject = {};
  71671. serializationObject.name = this.name;
  71672. serializationObject.hasAlpha = this.hasAlpha;
  71673. serializationObject.isCube = true;
  71674. serializationObject.level = this.level;
  71675. serializationObject.size = this._size;
  71676. serializationObject.coordinatesMode = this.coordinatesMode;
  71677. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71678. serializationObject.generateHarmonics = this._generateHarmonics;
  71679. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71680. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71681. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71682. serializationObject.noMipmap = this._noMipmap;
  71683. serializationObject.isBlocking = this._isBlocking;
  71684. return serializationObject;
  71685. };
  71686. /**
  71687. * Saves as a file the data contained in the texture in a binary format.
  71688. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71689. * as the spherical used in the lighting.
  71690. * @param url The HDR file url.
  71691. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71692. * @param onError Method called if any error happens during download.
  71693. * @return The packed binary data.
  71694. */
  71695. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71696. if (onError === void 0) { onError = null; }
  71697. var callback = function (buffer) {
  71698. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71699. // Returns a URL you can use as a href.
  71700. var objUrl = window.URL.createObjectURL(data);
  71701. // Simulates a link to it and click to dowload.
  71702. var a = document.createElement("a");
  71703. document.body.appendChild(a);
  71704. a.style.display = "none";
  71705. a.href = objUrl;
  71706. a.download = "envmap.babylon.hdr";
  71707. a.click();
  71708. };
  71709. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71710. };
  71711. /**
  71712. * Serializes the data contained in the texture in a binary format.
  71713. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71714. * as the spherical used in the lighting.
  71715. * @param url The HDR file url.
  71716. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71717. * @param onError Method called if any error happens during download.
  71718. * @return The packed binary data.
  71719. */
  71720. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71721. if (onError === void 0) { onError = null; }
  71722. // Needs the url tho create the texture.
  71723. if (!url) {
  71724. return;
  71725. }
  71726. // Check Power of two size.
  71727. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71728. return;
  71729. }
  71730. // Coming Back in 3.x.
  71731. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71732. };
  71733. HDRCubeTexture._facesMapping = [
  71734. "right",
  71735. "left",
  71736. "up",
  71737. "down",
  71738. "front",
  71739. "back"
  71740. ];
  71741. return HDRCubeTexture;
  71742. }(BABYLON.BaseTexture));
  71743. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71744. })(BABYLON || (BABYLON = {}));
  71745. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71746. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71747. // Huge respect for a such great lib.
  71748. // Earcut license:
  71749. // Copyright (c) 2016, Mapbox
  71750. //
  71751. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71752. // with or without fee is hereby granted, provided that the above copyright notice
  71753. // and this permission notice appear in all copies.
  71754. //
  71755. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71756. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71757. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71758. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71759. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71760. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71761. // THIS SOFTWARE.
  71762. var Earcut;
  71763. (function (Earcut) {
  71764. /**
  71765. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71766. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71767. * @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).
  71768. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71769. */
  71770. function earcut(data, holeIndices, dim) {
  71771. dim = dim || 2;
  71772. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71773. if (!outerNode)
  71774. return triangles;
  71775. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71776. if (hasHoles)
  71777. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71778. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71779. if (data.length > 80 * dim) {
  71780. minX = maxX = data[0];
  71781. minY = maxY = data[1];
  71782. for (var i = dim; i < outerLen; i += dim) {
  71783. x = data[i];
  71784. y = data[i + 1];
  71785. if (x < minX)
  71786. minX = x;
  71787. if (y < minY)
  71788. minY = y;
  71789. if (x > maxX)
  71790. maxX = x;
  71791. if (y > maxY)
  71792. maxY = y;
  71793. }
  71794. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71795. size = Math.max(maxX - minX, maxY - minY);
  71796. }
  71797. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71798. return triangles;
  71799. }
  71800. Earcut.earcut = earcut;
  71801. var Node = /** @class */ (function () {
  71802. function Node(i, x, y) {
  71803. this.i = i;
  71804. this.x = x;
  71805. this.y = y;
  71806. this.prev = null;
  71807. this.next = null;
  71808. this.z = null;
  71809. this.prevZ = null;
  71810. this.nextZ = null;
  71811. this.steiner = false;
  71812. }
  71813. return Node;
  71814. }());
  71815. // create a circular doubly linked list from polygon points in the specified winding order
  71816. function linkedList(data, start, end, dim, clockwise) {
  71817. var i, last = null;
  71818. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71819. for (i = start; i < end; i += dim)
  71820. last = insertNode(i, data[i], data[i + 1], last);
  71821. }
  71822. else {
  71823. for (i = end - dim; i >= start; i -= dim)
  71824. last = insertNode(i, data[i], data[i + 1], last);
  71825. }
  71826. if (last && equals(last, last.next)) {
  71827. removeNode(last);
  71828. last = last.next;
  71829. }
  71830. return last;
  71831. }
  71832. // eliminate colinear or duplicate points
  71833. function filterPoints(start, end) {
  71834. if (!start)
  71835. return start;
  71836. if (!end)
  71837. end = start;
  71838. var p = start, again;
  71839. do {
  71840. again = false;
  71841. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71842. removeNode(p);
  71843. p = end = p.prev;
  71844. if (p === p.next)
  71845. return undefined;
  71846. again = true;
  71847. }
  71848. else {
  71849. p = p.next;
  71850. }
  71851. } while (again || p !== end);
  71852. return end;
  71853. }
  71854. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71855. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71856. if (!ear)
  71857. return;
  71858. // interlink polygon nodes in z-order
  71859. if (!pass && size)
  71860. indexCurve(ear, minX, minY, size);
  71861. var stop = ear, prev, next;
  71862. // iterate through ears, slicing them one by one
  71863. while (ear.prev !== ear.next) {
  71864. prev = ear.prev;
  71865. next = ear.next;
  71866. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71867. // cut off the triangle
  71868. triangles.push(prev.i / dim);
  71869. triangles.push(ear.i / dim);
  71870. triangles.push(next.i / dim);
  71871. removeNode(ear);
  71872. // skipping the next vertice leads to less sliver triangles
  71873. ear = next.next;
  71874. stop = next.next;
  71875. continue;
  71876. }
  71877. ear = next;
  71878. // if we looped through the whole remaining polygon and can't find any more ears
  71879. if (ear === stop) {
  71880. // try filtering points and slicing again
  71881. if (!pass) {
  71882. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71883. // if this didn't work, try curing all small self-intersections locally
  71884. }
  71885. else if (pass === 1) {
  71886. ear = cureLocalIntersections(ear, triangles, dim);
  71887. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71888. // as a last resort, try splitting the remaining polygon into two
  71889. }
  71890. else if (pass === 2) {
  71891. splitEarcut(ear, triangles, dim, minX, minY, size);
  71892. }
  71893. break;
  71894. }
  71895. }
  71896. }
  71897. // check whether a polygon node forms a valid ear with adjacent nodes
  71898. function isEar(ear) {
  71899. var a = ear.prev, b = ear, c = ear.next;
  71900. if (area(a, b, c) >= 0)
  71901. return false; // reflex, can't be an ear
  71902. // now make sure we don't have other points inside the potential ear
  71903. var p = ear.next.next;
  71904. while (p !== ear.prev) {
  71905. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71906. area(p.prev, p, p.next) >= 0)
  71907. return false;
  71908. p = p.next;
  71909. }
  71910. return true;
  71911. }
  71912. function isEarHashed(ear, minX, minY, size) {
  71913. var a = ear.prev, b = ear, c = ear.next;
  71914. if (area(a, b, c) >= 0)
  71915. return false; // reflex, can't be an ear
  71916. // triangle bbox; min & max are calculated like this for speed
  71917. 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);
  71918. // z-order range for the current triangle bbox;
  71919. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71920. // first look for points inside the triangle in increasing z-order
  71921. var p = ear.nextZ;
  71922. while (p && p.z <= maxZ) {
  71923. if (p !== ear.prev &&
  71924. p !== ear.next &&
  71925. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71926. area(p.prev, p, p.next) >= 0)
  71927. return false;
  71928. p = p.nextZ;
  71929. }
  71930. // then look for points in decreasing z-order
  71931. p = ear.prevZ;
  71932. while (p && p.z >= minZ) {
  71933. if (p !== ear.prev &&
  71934. p !== ear.next &&
  71935. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71936. area(p.prev, p, p.next) >= 0)
  71937. return false;
  71938. p = p.prevZ;
  71939. }
  71940. return true;
  71941. }
  71942. // go through all polygon nodes and cure small local self-intersections
  71943. function cureLocalIntersections(start, triangles, dim) {
  71944. var p = start;
  71945. do {
  71946. var a = p.prev, b = p.next.next;
  71947. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71948. triangles.push(a.i / dim);
  71949. triangles.push(p.i / dim);
  71950. triangles.push(b.i / dim);
  71951. // remove two nodes involved
  71952. removeNode(p);
  71953. removeNode(p.next);
  71954. p = start = b;
  71955. }
  71956. p = p.next;
  71957. } while (p !== start);
  71958. return p;
  71959. }
  71960. // try splitting polygon into two and triangulate them independently
  71961. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71962. // look for a valid diagonal that divides the polygon into two
  71963. var a = start;
  71964. do {
  71965. var b = a.next.next;
  71966. while (b !== a.prev) {
  71967. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71968. // split the polygon in two by the diagonal
  71969. var c = splitPolygon(a, b);
  71970. // filter colinear points around the cuts
  71971. a = filterPoints(a, a.next);
  71972. c = filterPoints(c, c.next);
  71973. // run earcut on each half
  71974. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71975. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71976. return;
  71977. }
  71978. b = b.next;
  71979. }
  71980. a = a.next;
  71981. } while (a !== start);
  71982. }
  71983. // link every hole into the outer loop, producing a single-ring polygon without holes
  71984. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71985. var queue = [], i, len, start, end, list;
  71986. for (i = 0, len = holeIndices.length; i < len; i++) {
  71987. start = holeIndices[i] * dim;
  71988. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71989. list = linkedList(data, start, end, dim, false);
  71990. if (list === list.next)
  71991. list.steiner = true;
  71992. queue.push(getLeftmost(list));
  71993. }
  71994. queue.sort(compareX);
  71995. // process holes from left to right
  71996. for (i = 0; i < queue.length; i++) {
  71997. eliminateHole(queue[i], outerNode);
  71998. outerNode = filterPoints(outerNode, outerNode.next);
  71999. }
  72000. return outerNode;
  72001. }
  72002. function compareX(a, b) {
  72003. return a.x - b.x;
  72004. }
  72005. // find a bridge between vertices that connects hole with an outer ring and and link it
  72006. function eliminateHole(hole, outerNode) {
  72007. outerNode = findHoleBridge(hole, outerNode);
  72008. if (outerNode) {
  72009. var b = splitPolygon(outerNode, hole);
  72010. filterPoints(b, b.next);
  72011. }
  72012. }
  72013. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  72014. function findHoleBridge(hole, outerNode) {
  72015. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  72016. // find a segment intersected by a ray from the hole's leftmost point to the left;
  72017. // segment's endpoint with lesser x will be potential connection point
  72018. do {
  72019. if (hy <= p.y && hy >= p.next.y) {
  72020. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  72021. if (x <= hx && x > qx) {
  72022. qx = x;
  72023. if (x === hx) {
  72024. if (hy === p.y)
  72025. return p;
  72026. if (hy === p.next.y)
  72027. return p.next;
  72028. }
  72029. m = p.x < p.next.x ? p : p.next;
  72030. }
  72031. }
  72032. p = p.next;
  72033. } while (p !== outerNode);
  72034. if (!m)
  72035. return null;
  72036. if (hx === qx)
  72037. return m.prev; // hole touches outer segment; pick lower endpoint
  72038. // look for points inside the triangle of hole point, segment intersection and endpoint;
  72039. // if there are no points found, we have a valid connection;
  72040. // otherwise choose the point of the minimum angle with the ray as connection point
  72041. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  72042. p = m.next;
  72043. while (p !== stop) {
  72044. if (hx >= p.x &&
  72045. p.x >= mx &&
  72046. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  72047. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  72048. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  72049. m = p;
  72050. tanMin = tan;
  72051. }
  72052. }
  72053. p = p.next;
  72054. }
  72055. return m;
  72056. }
  72057. // interlink polygon nodes in z-order
  72058. function indexCurve(start, minX, minY, size) {
  72059. var p = start;
  72060. do {
  72061. if (p.z === null)
  72062. p.z = zOrder(p.x, p.y, minX, minY, size);
  72063. p.prevZ = p.prev;
  72064. p.nextZ = p.next;
  72065. p = p.next;
  72066. } while (p !== start);
  72067. p.prevZ.nextZ = null;
  72068. p.prevZ = null;
  72069. sortLinked(p);
  72070. }
  72071. // Simon Tatham's linked list merge sort algorithm
  72072. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  72073. function sortLinked(list) {
  72074. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  72075. do {
  72076. p = list;
  72077. list = null;
  72078. tail = null;
  72079. numMerges = 0;
  72080. while (p) {
  72081. numMerges++;
  72082. q = p;
  72083. pSize = 0;
  72084. for (i = 0; i < inSize; i++) {
  72085. pSize++;
  72086. q = q.nextZ;
  72087. if (!q)
  72088. break;
  72089. }
  72090. qSize = inSize;
  72091. while (pSize > 0 || (qSize > 0 && q)) {
  72092. if (pSize === 0) {
  72093. e = q;
  72094. q = q.nextZ;
  72095. qSize--;
  72096. }
  72097. else if (qSize === 0 || !q) {
  72098. e = p;
  72099. p = p.nextZ;
  72100. pSize--;
  72101. }
  72102. else if (p.z <= q.z) {
  72103. e = p;
  72104. p = p.nextZ;
  72105. pSize--;
  72106. }
  72107. else {
  72108. e = q;
  72109. q = q.nextZ;
  72110. qSize--;
  72111. }
  72112. if (tail)
  72113. tail.nextZ = e;
  72114. else
  72115. list = e;
  72116. e.prevZ = tail;
  72117. tail = e;
  72118. }
  72119. p = q;
  72120. }
  72121. tail.nextZ = null;
  72122. inSize *= 2;
  72123. } while (numMerges > 1);
  72124. return list;
  72125. }
  72126. // z-order of a point given coords and size of the data bounding box
  72127. function zOrder(x, y, minX, minY, size) {
  72128. // coords are transformed into non-negative 15-bit integer range
  72129. x = 32767 * (x - minX) / size;
  72130. y = 32767 * (y - minY) / size;
  72131. x = (x | (x << 8)) & 0x00FF00FF;
  72132. x = (x | (x << 4)) & 0x0F0F0F0F;
  72133. x = (x | (x << 2)) & 0x33333333;
  72134. x = (x | (x << 1)) & 0x55555555;
  72135. y = (y | (y << 8)) & 0x00FF00FF;
  72136. y = (y | (y << 4)) & 0x0F0F0F0F;
  72137. y = (y | (y << 2)) & 0x33333333;
  72138. y = (y | (y << 1)) & 0x55555555;
  72139. return x | (y << 1);
  72140. }
  72141. // find the leftmost node of a polygon ring
  72142. function getLeftmost(start) {
  72143. var p = start, leftmost = start;
  72144. do {
  72145. if (p.x < leftmost.x)
  72146. leftmost = p;
  72147. p = p.next;
  72148. } while (p !== start);
  72149. return leftmost;
  72150. }
  72151. // check if a point lies within a convex triangle
  72152. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72153. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72154. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72155. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72156. }
  72157. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72158. function isValidDiagonal(a, b) {
  72159. return a.next.i !== b.i &&
  72160. a.prev.i !== b.i &&
  72161. !intersectsPolygon(a, b) &&
  72162. locallyInside(a, b) &&
  72163. locallyInside(b, a) &&
  72164. middleInside(a, b);
  72165. }
  72166. // signed area of a triangle
  72167. function area(p, q, r) {
  72168. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72169. }
  72170. // check if two points are equal
  72171. function equals(p1, p2) {
  72172. return p1.x === p2.x && p1.y === p2.y;
  72173. }
  72174. // check if two segments intersect
  72175. function intersects(p1, q1, p2, q2) {
  72176. if ((equals(p1, q1) && equals(p2, q2)) ||
  72177. (equals(p1, q2) && equals(p2, q1)))
  72178. return true;
  72179. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72180. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72181. }
  72182. // check if a polygon diagonal intersects any polygon segments
  72183. function intersectsPolygon(a, b) {
  72184. var p = a;
  72185. do {
  72186. if (p.i !== a.i &&
  72187. p.next.i !== a.i &&
  72188. p.i !== b.i &&
  72189. p.next.i !== b.i &&
  72190. intersects(p, p.next, a, b))
  72191. return true;
  72192. p = p.next;
  72193. } while (p !== a);
  72194. return false;
  72195. }
  72196. // check if a polygon diagonal is locally inside the polygon
  72197. function locallyInside(a, b) {
  72198. return area(a.prev, a, a.next) < 0
  72199. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72200. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72201. }
  72202. // check if the middle point of a polygon diagonal is inside the polygon
  72203. function middleInside(a, b) {
  72204. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72205. do {
  72206. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72207. inside = !inside;
  72208. p = p.next;
  72209. } while (p !== a);
  72210. return inside;
  72211. }
  72212. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72213. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72214. function splitPolygon(a, b) {
  72215. 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;
  72216. a.next = b;
  72217. b.prev = a;
  72218. a2.next = an;
  72219. an.prev = a2;
  72220. b2.next = a2;
  72221. a2.prev = b2;
  72222. bp.next = b2;
  72223. b2.prev = bp;
  72224. return b2;
  72225. }
  72226. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72227. function insertNode(i, x, y, last) {
  72228. var p = new Node(i, x, y);
  72229. if (!last) {
  72230. p.prev = p;
  72231. p.next = p;
  72232. }
  72233. else {
  72234. p.next = last.next;
  72235. p.prev = last;
  72236. last.next.prev = p;
  72237. last.next = p;
  72238. }
  72239. return p;
  72240. }
  72241. function removeNode(p) {
  72242. p.next.prev = p.prev;
  72243. p.prev.next = p.next;
  72244. if (p.prevZ)
  72245. p.prevZ.nextZ = p.nextZ;
  72246. if (p.nextZ)
  72247. p.nextZ.prevZ = p.prevZ;
  72248. }
  72249. /**
  72250. * return a percentage difference between the polygon area and its triangulation area;
  72251. * used to verify correctness of triangulation
  72252. */
  72253. function deviation(data, holeIndices, dim, triangles) {
  72254. var hasHoles = holeIndices && holeIndices.length;
  72255. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72256. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72257. if (hasHoles) {
  72258. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72259. var start = holeIndices[i] * dim;
  72260. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72261. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72262. }
  72263. }
  72264. var trianglesArea = 0;
  72265. for (i = 0; i < triangles.length; i += 3) {
  72266. var a = triangles[i] * dim;
  72267. var b = triangles[i + 1] * dim;
  72268. var c = triangles[i + 2] * dim;
  72269. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72270. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72271. }
  72272. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72273. }
  72274. Earcut.deviation = deviation;
  72275. ;
  72276. function signedArea(data, start, end, dim) {
  72277. var sum = 0;
  72278. for (var i = start, j = end - dim; i < end; i += dim) {
  72279. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72280. j = i;
  72281. }
  72282. return sum;
  72283. }
  72284. /**
  72285. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72286. */
  72287. function flatten(data) {
  72288. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72289. for (var i = 0; i < data.length; i++) {
  72290. for (var j = 0; j < data[i].length; j++) {
  72291. for (var d = 0; d < dim; d++)
  72292. result.vertices.push(data[i][j][d]);
  72293. }
  72294. if (i > 0) {
  72295. holeIndex += data[i - 1].length;
  72296. result.holes.push(holeIndex);
  72297. }
  72298. }
  72299. return result;
  72300. }
  72301. Earcut.flatten = flatten;
  72302. ;
  72303. })(Earcut || (Earcut = {}));
  72304. //# sourceMappingURL=babylon.earcut.js.map
  72305. var BABYLON;
  72306. (function (BABYLON) {
  72307. var IndexedVector2 = /** @class */ (function (_super) {
  72308. __extends(IndexedVector2, _super);
  72309. function IndexedVector2(original, index) {
  72310. var _this = _super.call(this, original.x, original.y) || this;
  72311. _this.index = index;
  72312. return _this;
  72313. }
  72314. return IndexedVector2;
  72315. }(BABYLON.Vector2));
  72316. var PolygonPoints = /** @class */ (function () {
  72317. function PolygonPoints() {
  72318. this.elements = new Array();
  72319. }
  72320. PolygonPoints.prototype.add = function (originalPoints) {
  72321. var _this = this;
  72322. var result = new Array();
  72323. originalPoints.forEach(function (point) {
  72324. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72325. var newPoint = new IndexedVector2(point, _this.elements.length);
  72326. result.push(newPoint);
  72327. _this.elements.push(newPoint);
  72328. }
  72329. });
  72330. return result;
  72331. };
  72332. PolygonPoints.prototype.computeBounds = function () {
  72333. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72334. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72335. this.elements.forEach(function (point) {
  72336. // x
  72337. if (point.x < lmin.x) {
  72338. lmin.x = point.x;
  72339. }
  72340. else if (point.x > lmax.x) {
  72341. lmax.x = point.x;
  72342. }
  72343. // y
  72344. if (point.y < lmin.y) {
  72345. lmin.y = point.y;
  72346. }
  72347. else if (point.y > lmax.y) {
  72348. lmax.y = point.y;
  72349. }
  72350. });
  72351. return {
  72352. min: lmin,
  72353. max: lmax,
  72354. width: lmax.x - lmin.x,
  72355. height: lmax.y - lmin.y
  72356. };
  72357. };
  72358. return PolygonPoints;
  72359. }());
  72360. var Polygon = /** @class */ (function () {
  72361. function Polygon() {
  72362. }
  72363. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72364. return [
  72365. new BABYLON.Vector2(xmin, ymin),
  72366. new BABYLON.Vector2(xmax, ymin),
  72367. new BABYLON.Vector2(xmax, ymax),
  72368. new BABYLON.Vector2(xmin, ymax)
  72369. ];
  72370. };
  72371. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72372. if (cx === void 0) { cx = 0; }
  72373. if (cy === void 0) { cy = 0; }
  72374. if (numberOfSides === void 0) { numberOfSides = 32; }
  72375. var result = new Array();
  72376. var angle = 0;
  72377. var increment = (Math.PI * 2) / numberOfSides;
  72378. for (var i = 0; i < numberOfSides; i++) {
  72379. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72380. angle -= increment;
  72381. }
  72382. return result;
  72383. };
  72384. Polygon.Parse = function (input) {
  72385. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72386. var i, result = [];
  72387. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72388. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72389. }
  72390. return result;
  72391. };
  72392. Polygon.StartingAt = function (x, y) {
  72393. return BABYLON.Path2.StartingAt(x, y);
  72394. };
  72395. return Polygon;
  72396. }());
  72397. BABYLON.Polygon = Polygon;
  72398. var PolygonMeshBuilder = /** @class */ (function () {
  72399. function PolygonMeshBuilder(name, contours, scene) {
  72400. this._points = new PolygonPoints();
  72401. this._outlinepoints = new PolygonPoints();
  72402. this._holes = new Array();
  72403. this._epoints = new Array();
  72404. this._eholes = new Array();
  72405. this._name = name;
  72406. this._scene = scene;
  72407. var points;
  72408. if (contours instanceof BABYLON.Path2) {
  72409. points = contours.getPoints();
  72410. }
  72411. else {
  72412. points = contours;
  72413. }
  72414. this._addToepoint(points);
  72415. this._points.add(points);
  72416. this._outlinepoints.add(points);
  72417. }
  72418. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72419. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72420. var p = points_1[_i];
  72421. this._epoints.push(p.x, p.y);
  72422. }
  72423. };
  72424. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72425. this._points.add(hole);
  72426. var holepoints = new PolygonPoints();
  72427. holepoints.add(hole);
  72428. this._holes.push(holepoints);
  72429. this._eholes.push(this._epoints.length / 2);
  72430. this._addToepoint(hole);
  72431. return this;
  72432. };
  72433. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72434. var _this = this;
  72435. if (updatable === void 0) { updatable = false; }
  72436. if (depth === void 0) { depth = 0; }
  72437. var result = new BABYLON.Mesh(this._name, this._scene);
  72438. var normals = new Array();
  72439. var positions = new Array();
  72440. var uvs = new Array();
  72441. var bounds = this._points.computeBounds();
  72442. this._points.elements.forEach(function (p) {
  72443. normals.push(0, 1.0, 0);
  72444. positions.push(p.x, 0, p.y);
  72445. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72446. });
  72447. var indices = new Array();
  72448. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72449. for (var i = 0; i < res.length; i++) {
  72450. indices.push(res[i]);
  72451. }
  72452. if (depth > 0) {
  72453. var positionscount = (positions.length / 3); //get the current pointcount
  72454. this._points.elements.forEach(function (p) {
  72455. normals.push(0, -1.0, 0);
  72456. positions.push(p.x, -depth, p.y);
  72457. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72458. });
  72459. var totalCount = indices.length;
  72460. for (var i = 0; i < totalCount; i += 3) {
  72461. var i0 = indices[i + 0];
  72462. var i1 = indices[i + 1];
  72463. var i2 = indices[i + 2];
  72464. indices.push(i2 + positionscount);
  72465. indices.push(i1 + positionscount);
  72466. indices.push(i0 + positionscount);
  72467. }
  72468. //Add the sides
  72469. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72470. this._holes.forEach(function (hole) {
  72471. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72472. });
  72473. }
  72474. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72475. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72476. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72477. result.setIndices(indices);
  72478. return result;
  72479. };
  72480. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72481. var StartIndex = positions.length / 3;
  72482. var ulength = 0;
  72483. for (var i = 0; i < points.elements.length; i++) {
  72484. var p = points.elements[i];
  72485. var p1;
  72486. if ((i + 1) > points.elements.length - 1) {
  72487. p1 = points.elements[0];
  72488. }
  72489. else {
  72490. p1 = points.elements[i + 1];
  72491. }
  72492. positions.push(p.x, 0, p.y);
  72493. positions.push(p.x, -depth, p.y);
  72494. positions.push(p1.x, 0, p1.y);
  72495. positions.push(p1.x, -depth, p1.y);
  72496. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72497. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72498. var v3 = v2.subtract(v1);
  72499. var v4 = new BABYLON.Vector3(0, 1, 0);
  72500. var vn = BABYLON.Vector3.Cross(v3, v4);
  72501. vn = vn.normalize();
  72502. uvs.push(ulength / bounds.width, 0);
  72503. uvs.push(ulength / bounds.width, 1);
  72504. ulength += v3.length();
  72505. uvs.push((ulength / bounds.width), 0);
  72506. uvs.push((ulength / bounds.width), 1);
  72507. if (!flip) {
  72508. normals.push(-vn.x, -vn.y, -vn.z);
  72509. normals.push(-vn.x, -vn.y, -vn.z);
  72510. normals.push(-vn.x, -vn.y, -vn.z);
  72511. normals.push(-vn.x, -vn.y, -vn.z);
  72512. indices.push(StartIndex);
  72513. indices.push(StartIndex + 1);
  72514. indices.push(StartIndex + 2);
  72515. indices.push(StartIndex + 1);
  72516. indices.push(StartIndex + 3);
  72517. indices.push(StartIndex + 2);
  72518. }
  72519. else {
  72520. normals.push(vn.x, vn.y, vn.z);
  72521. normals.push(vn.x, vn.y, vn.z);
  72522. normals.push(vn.x, vn.y, vn.z);
  72523. normals.push(vn.x, vn.y, vn.z);
  72524. indices.push(StartIndex);
  72525. indices.push(StartIndex + 2);
  72526. indices.push(StartIndex + 1);
  72527. indices.push(StartIndex + 1);
  72528. indices.push(StartIndex + 2);
  72529. indices.push(StartIndex + 3);
  72530. }
  72531. StartIndex += 4;
  72532. }
  72533. ;
  72534. };
  72535. return PolygonMeshBuilder;
  72536. }());
  72537. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72538. })(BABYLON || (BABYLON = {}));
  72539. //# sourceMappingURL=babylon.polygonMesh.js.map
  72540. var BABYLON;
  72541. (function (BABYLON) {
  72542. // Unique ID when we import meshes from Babylon to CSG
  72543. var currentCSGMeshId = 0;
  72544. // # class Vertex
  72545. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72546. // one to provide additional features like texture coordinates and vertex
  72547. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72548. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72549. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72550. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72551. // is not used anywhere else.
  72552. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72553. var Vertex = /** @class */ (function () {
  72554. function Vertex(pos, normal, uv) {
  72555. this.pos = pos;
  72556. this.normal = normal;
  72557. this.uv = uv;
  72558. }
  72559. Vertex.prototype.clone = function () {
  72560. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72561. };
  72562. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72563. // orientation of a polygon is flipped.
  72564. Vertex.prototype.flip = function () {
  72565. this.normal = this.normal.scale(-1);
  72566. };
  72567. // Create a new vertex between this vertex and `other` by linearly
  72568. // interpolating all properties using a parameter of `t`. Subclasses should
  72569. // override this to interpolate additional properties.
  72570. Vertex.prototype.interpolate = function (other, t) {
  72571. 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));
  72572. };
  72573. return Vertex;
  72574. }());
  72575. // # class Plane
  72576. // Represents a plane in 3D space.
  72577. var Plane = /** @class */ (function () {
  72578. function Plane(normal, w) {
  72579. this.normal = normal;
  72580. this.w = w;
  72581. }
  72582. Plane.FromPoints = function (a, b, c) {
  72583. var v0 = c.subtract(a);
  72584. var v1 = b.subtract(a);
  72585. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72586. return null;
  72587. }
  72588. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72589. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72590. };
  72591. Plane.prototype.clone = function () {
  72592. return new Plane(this.normal.clone(), this.w);
  72593. };
  72594. Plane.prototype.flip = function () {
  72595. this.normal.scaleInPlace(-1);
  72596. this.w = -this.w;
  72597. };
  72598. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72599. // fragments in the appropriate lists. Coplanar polygons go into either
  72600. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72601. // respect to this plane. Polygons in front or in back of this plane go into
  72602. // either `front` or `back`.
  72603. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72604. var COPLANAR = 0;
  72605. var FRONT = 1;
  72606. var BACK = 2;
  72607. var SPANNING = 3;
  72608. // Classify each point as well as the entire polygon into one of the above
  72609. // four classes.
  72610. var polygonType = 0;
  72611. var types = [];
  72612. var i;
  72613. var t;
  72614. for (i = 0; i < polygon.vertices.length; i++) {
  72615. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72616. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72617. polygonType |= type;
  72618. types.push(type);
  72619. }
  72620. // Put the polygon in the correct list, splitting it when necessary.
  72621. switch (polygonType) {
  72622. case COPLANAR:
  72623. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72624. break;
  72625. case FRONT:
  72626. front.push(polygon);
  72627. break;
  72628. case BACK:
  72629. back.push(polygon);
  72630. break;
  72631. case SPANNING:
  72632. var f = [], b = [];
  72633. for (i = 0; i < polygon.vertices.length; i++) {
  72634. var j = (i + 1) % polygon.vertices.length;
  72635. var ti = types[i], tj = types[j];
  72636. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72637. if (ti !== BACK)
  72638. f.push(vi);
  72639. if (ti !== FRONT)
  72640. b.push(ti !== BACK ? vi.clone() : vi);
  72641. if ((ti | tj) === SPANNING) {
  72642. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72643. var v = vi.interpolate(vj, t);
  72644. f.push(v);
  72645. b.push(v.clone());
  72646. }
  72647. }
  72648. var poly;
  72649. if (f.length >= 3) {
  72650. poly = new Polygon(f, polygon.shared);
  72651. if (poly.plane)
  72652. front.push(poly);
  72653. }
  72654. if (b.length >= 3) {
  72655. poly = new Polygon(b, polygon.shared);
  72656. if (poly.plane)
  72657. back.push(poly);
  72658. }
  72659. break;
  72660. }
  72661. };
  72662. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72663. // point is on the plane.
  72664. Plane.EPSILON = 1e-5;
  72665. return Plane;
  72666. }());
  72667. // # class Polygon
  72668. // Represents a convex polygon. The vertices used to initialize a polygon must
  72669. // be coplanar and form a convex loop.
  72670. //
  72671. // Each convex polygon has a `shared` property, which is shared between all
  72672. // polygons that are clones of each other or were split from the same polygon.
  72673. // This can be used to define per-polygon properties (such as surface color).
  72674. var Polygon = /** @class */ (function () {
  72675. function Polygon(vertices, shared) {
  72676. this.vertices = vertices;
  72677. this.shared = shared;
  72678. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72679. }
  72680. Polygon.prototype.clone = function () {
  72681. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72682. return new Polygon(vertices, this.shared);
  72683. };
  72684. Polygon.prototype.flip = function () {
  72685. this.vertices.reverse().map(function (v) { v.flip(); });
  72686. this.plane.flip();
  72687. };
  72688. return Polygon;
  72689. }());
  72690. // # class Node
  72691. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72692. // by picking a polygon to split along. That polygon (and all other coplanar
  72693. // polygons) are added directly to that node and the other polygons are added to
  72694. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72695. // no distinction between internal and leaf nodes.
  72696. var Node = /** @class */ (function () {
  72697. function Node(polygons) {
  72698. this.plane = null;
  72699. this.front = null;
  72700. this.back = null;
  72701. this.polygons = new Array();
  72702. if (polygons) {
  72703. this.build(polygons);
  72704. }
  72705. }
  72706. Node.prototype.clone = function () {
  72707. var node = new Node();
  72708. node.plane = this.plane && this.plane.clone();
  72709. node.front = this.front && this.front.clone();
  72710. node.back = this.back && this.back.clone();
  72711. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72712. return node;
  72713. };
  72714. // Convert solid space to empty space and empty space to solid space.
  72715. Node.prototype.invert = function () {
  72716. for (var i = 0; i < this.polygons.length; i++) {
  72717. this.polygons[i].flip();
  72718. }
  72719. if (this.plane) {
  72720. this.plane.flip();
  72721. }
  72722. if (this.front) {
  72723. this.front.invert();
  72724. }
  72725. if (this.back) {
  72726. this.back.invert();
  72727. }
  72728. var temp = this.front;
  72729. this.front = this.back;
  72730. this.back = temp;
  72731. };
  72732. // Recursively remove all polygons in `polygons` that are inside this BSP
  72733. // tree.
  72734. Node.prototype.clipPolygons = function (polygons) {
  72735. if (!this.plane)
  72736. return polygons.slice();
  72737. var front = new Array(), back = new Array();
  72738. for (var i = 0; i < polygons.length; i++) {
  72739. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72740. }
  72741. if (this.front) {
  72742. front = this.front.clipPolygons(front);
  72743. }
  72744. if (this.back) {
  72745. back = this.back.clipPolygons(back);
  72746. }
  72747. else {
  72748. back = [];
  72749. }
  72750. return front.concat(back);
  72751. };
  72752. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72753. // `bsp`.
  72754. Node.prototype.clipTo = function (bsp) {
  72755. this.polygons = bsp.clipPolygons(this.polygons);
  72756. if (this.front)
  72757. this.front.clipTo(bsp);
  72758. if (this.back)
  72759. this.back.clipTo(bsp);
  72760. };
  72761. // Return a list of all polygons in this BSP tree.
  72762. Node.prototype.allPolygons = function () {
  72763. var polygons = this.polygons.slice();
  72764. if (this.front)
  72765. polygons = polygons.concat(this.front.allPolygons());
  72766. if (this.back)
  72767. polygons = polygons.concat(this.back.allPolygons());
  72768. return polygons;
  72769. };
  72770. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72771. // new polygons are filtered down to the bottom of the tree and become new
  72772. // nodes there. Each set of polygons is partitioned using the first polygon
  72773. // (no heuristic is used to pick a good split).
  72774. Node.prototype.build = function (polygons) {
  72775. if (!polygons.length)
  72776. return;
  72777. if (!this.plane)
  72778. this.plane = polygons[0].plane.clone();
  72779. var front = new Array(), back = new Array();
  72780. for (var i = 0; i < polygons.length; i++) {
  72781. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72782. }
  72783. if (front.length) {
  72784. if (!this.front)
  72785. this.front = new Node();
  72786. this.front.build(front);
  72787. }
  72788. if (back.length) {
  72789. if (!this.back)
  72790. this.back = new Node();
  72791. this.back.build(back);
  72792. }
  72793. };
  72794. return Node;
  72795. }());
  72796. var CSG = /** @class */ (function () {
  72797. function CSG() {
  72798. this.polygons = new Array();
  72799. }
  72800. // Convert BABYLON.Mesh to BABYLON.CSG
  72801. CSG.FromMesh = function (mesh) {
  72802. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72803. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72804. if (mesh instanceof BABYLON.Mesh) {
  72805. mesh.computeWorldMatrix(true);
  72806. matrix = mesh.getWorldMatrix();
  72807. meshPosition = mesh.position.clone();
  72808. meshRotation = mesh.rotation.clone();
  72809. if (mesh.rotationQuaternion) {
  72810. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72811. }
  72812. meshScaling = mesh.scaling.clone();
  72813. }
  72814. else {
  72815. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72816. }
  72817. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72818. var subMeshes = mesh.subMeshes;
  72819. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72820. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72821. vertices = [];
  72822. for (var j = 0; j < 3; j++) {
  72823. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72824. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72825. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72826. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72827. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72828. vertex = new Vertex(position, normal, uv);
  72829. vertices.push(vertex);
  72830. }
  72831. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72832. // To handle the case of degenerated triangle
  72833. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72834. if (polygon.plane)
  72835. polygons.push(polygon);
  72836. }
  72837. }
  72838. var csg = CSG.FromPolygons(polygons);
  72839. csg.matrix = matrix;
  72840. csg.position = meshPosition;
  72841. csg.rotation = meshRotation;
  72842. csg.scaling = meshScaling;
  72843. csg.rotationQuaternion = meshRotationQuaternion;
  72844. currentCSGMeshId++;
  72845. return csg;
  72846. };
  72847. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72848. CSG.FromPolygons = function (polygons) {
  72849. var csg = new CSG();
  72850. csg.polygons = polygons;
  72851. return csg;
  72852. };
  72853. CSG.prototype.clone = function () {
  72854. var csg = new CSG();
  72855. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72856. csg.copyTransformAttributes(this);
  72857. return csg;
  72858. };
  72859. CSG.prototype.union = function (csg) {
  72860. var a = new Node(this.clone().polygons);
  72861. var b = new Node(csg.clone().polygons);
  72862. a.clipTo(b);
  72863. b.clipTo(a);
  72864. b.invert();
  72865. b.clipTo(a);
  72866. b.invert();
  72867. a.build(b.allPolygons());
  72868. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72869. };
  72870. CSG.prototype.unionInPlace = function (csg) {
  72871. var a = new Node(this.polygons);
  72872. var b = new Node(csg.polygons);
  72873. a.clipTo(b);
  72874. b.clipTo(a);
  72875. b.invert();
  72876. b.clipTo(a);
  72877. b.invert();
  72878. a.build(b.allPolygons());
  72879. this.polygons = a.allPolygons();
  72880. };
  72881. CSG.prototype.subtract = function (csg) {
  72882. var a = new Node(this.clone().polygons);
  72883. var b = new Node(csg.clone().polygons);
  72884. a.invert();
  72885. a.clipTo(b);
  72886. b.clipTo(a);
  72887. b.invert();
  72888. b.clipTo(a);
  72889. b.invert();
  72890. a.build(b.allPolygons());
  72891. a.invert();
  72892. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72893. };
  72894. CSG.prototype.subtractInPlace = function (csg) {
  72895. var a = new Node(this.polygons);
  72896. var b = new Node(csg.polygons);
  72897. a.invert();
  72898. a.clipTo(b);
  72899. b.clipTo(a);
  72900. b.invert();
  72901. b.clipTo(a);
  72902. b.invert();
  72903. a.build(b.allPolygons());
  72904. a.invert();
  72905. this.polygons = a.allPolygons();
  72906. };
  72907. CSG.prototype.intersect = function (csg) {
  72908. var a = new Node(this.clone().polygons);
  72909. var b = new Node(csg.clone().polygons);
  72910. a.invert();
  72911. b.clipTo(a);
  72912. b.invert();
  72913. a.clipTo(b);
  72914. b.clipTo(a);
  72915. a.build(b.allPolygons());
  72916. a.invert();
  72917. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72918. };
  72919. CSG.prototype.intersectInPlace = function (csg) {
  72920. var a = new Node(this.polygons);
  72921. var b = new Node(csg.polygons);
  72922. a.invert();
  72923. b.clipTo(a);
  72924. b.invert();
  72925. a.clipTo(b);
  72926. b.clipTo(a);
  72927. a.build(b.allPolygons());
  72928. a.invert();
  72929. this.polygons = a.allPolygons();
  72930. };
  72931. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72932. // not modified.
  72933. CSG.prototype.inverse = function () {
  72934. var csg = this.clone();
  72935. csg.inverseInPlace();
  72936. return csg;
  72937. };
  72938. CSG.prototype.inverseInPlace = function () {
  72939. this.polygons.map(function (p) { p.flip(); });
  72940. };
  72941. // This is used to keep meshes transformations so they can be restored
  72942. // when we build back a Babylon Mesh
  72943. // NB : All CSG operations are performed in world coordinates
  72944. CSG.prototype.copyTransformAttributes = function (csg) {
  72945. this.matrix = csg.matrix;
  72946. this.position = csg.position;
  72947. this.rotation = csg.rotation;
  72948. this.scaling = csg.scaling;
  72949. this.rotationQuaternion = csg.rotationQuaternion;
  72950. return this;
  72951. };
  72952. // Build Raw mesh from CSG
  72953. // Coordinates here are in world space
  72954. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72955. var matrix = this.matrix.clone();
  72956. matrix.invert();
  72957. 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;
  72958. if (keepSubMeshes) {
  72959. // Sort Polygons, since subMeshes are indices range
  72960. polygons.sort(function (a, b) {
  72961. if (a.shared.meshId === b.shared.meshId) {
  72962. return a.shared.subMeshId - b.shared.subMeshId;
  72963. }
  72964. else {
  72965. return a.shared.meshId - b.shared.meshId;
  72966. }
  72967. });
  72968. }
  72969. for (var i = 0, il = polygons.length; i < il; i++) {
  72970. polygon = polygons[i];
  72971. // Building SubMeshes
  72972. if (!subMesh_dict[polygon.shared.meshId]) {
  72973. subMesh_dict[polygon.shared.meshId] = {};
  72974. }
  72975. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72976. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72977. indexStart: +Infinity,
  72978. indexEnd: -Infinity,
  72979. materialIndex: polygon.shared.materialIndex
  72980. };
  72981. }
  72982. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72983. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72984. polygonIndices[0] = 0;
  72985. polygonIndices[1] = j - 1;
  72986. polygonIndices[2] = j;
  72987. for (var k = 0; k < 3; k++) {
  72988. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72989. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72990. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72991. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72992. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72993. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72994. // Check if 2 points can be merged
  72995. if (!(typeof vertex_idx !== 'undefined' &&
  72996. normals[vertex_idx * 3] === localNormal.x &&
  72997. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72998. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72999. uvs[vertex_idx * 2] === uv.x &&
  73000. uvs[vertex_idx * 2 + 1] === uv.y)) {
  73001. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  73002. uvs.push(uv.x, uv.y);
  73003. normals.push(normal.x, normal.y, normal.z);
  73004. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  73005. }
  73006. indices.push(vertex_idx);
  73007. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  73008. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  73009. currentIndex++;
  73010. }
  73011. }
  73012. }
  73013. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  73014. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  73015. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  73016. mesh.setIndices(indices, null);
  73017. if (keepSubMeshes) {
  73018. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  73019. var materialIndexOffset = 0, materialMaxIndex;
  73020. mesh.subMeshes = new Array();
  73021. for (var m in subMesh_dict) {
  73022. materialMaxIndex = -1;
  73023. for (var sm in subMesh_dict[m]) {
  73024. subMesh_obj = subMesh_dict[m][sm];
  73025. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  73026. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  73027. }
  73028. materialIndexOffset += ++materialMaxIndex;
  73029. }
  73030. }
  73031. return mesh;
  73032. };
  73033. // Build Mesh from CSG taking material and transforms into account
  73034. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  73035. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  73036. mesh.material = material;
  73037. mesh.position.copyFrom(this.position);
  73038. mesh.rotation.copyFrom(this.rotation);
  73039. if (this.rotationQuaternion) {
  73040. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  73041. }
  73042. mesh.scaling.copyFrom(this.scaling);
  73043. mesh.computeWorldMatrix(true);
  73044. return mesh;
  73045. };
  73046. return CSG;
  73047. }());
  73048. BABYLON.CSG = CSG;
  73049. })(BABYLON || (BABYLON = {}));
  73050. //# sourceMappingURL=babylon.csg.js.map
  73051. var BABYLON;
  73052. (function (BABYLON) {
  73053. var LensFlare = /** @class */ (function () {
  73054. function LensFlare(size, position, color, imgUrl, system) {
  73055. this.size = size;
  73056. this.position = position;
  73057. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73058. this.color = color || new BABYLON.Color3(1, 1, 1);
  73059. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  73060. this._system = system;
  73061. system.lensFlares.push(this);
  73062. }
  73063. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  73064. return new LensFlare(size, position, color, imgUrl, system);
  73065. };
  73066. LensFlare.prototype.dispose = function () {
  73067. if (this.texture) {
  73068. this.texture.dispose();
  73069. }
  73070. // Remove from scene
  73071. var index = this._system.lensFlares.indexOf(this);
  73072. this._system.lensFlares.splice(index, 1);
  73073. };
  73074. ;
  73075. return LensFlare;
  73076. }());
  73077. BABYLON.LensFlare = LensFlare;
  73078. })(BABYLON || (BABYLON = {}));
  73079. //# sourceMappingURL=babylon.lensFlare.js.map
  73080. var BABYLON;
  73081. (function (BABYLON) {
  73082. var LensFlareSystem = /** @class */ (function () {
  73083. function LensFlareSystem(name, emitter, scene) {
  73084. this.name = name;
  73085. this.lensFlares = new Array();
  73086. this.borderLimit = 300;
  73087. this.viewportBorder = 0;
  73088. this.layerMask = 0x0FFFFFFF;
  73089. this._vertexBuffers = {};
  73090. this._isEnabled = true;
  73091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73092. this._emitter = emitter;
  73093. this.id = name;
  73094. scene.lensFlareSystems.push(this);
  73095. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73096. var engine = scene.getEngine();
  73097. // VBO
  73098. var vertices = [];
  73099. vertices.push(1, 1);
  73100. vertices.push(-1, 1);
  73101. vertices.push(-1, -1);
  73102. vertices.push(1, -1);
  73103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73104. // Indices
  73105. var indices = [];
  73106. indices.push(0);
  73107. indices.push(1);
  73108. indices.push(2);
  73109. indices.push(0);
  73110. indices.push(2);
  73111. indices.push(3);
  73112. this._indexBuffer = engine.createIndexBuffer(indices);
  73113. // Effects
  73114. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73115. }
  73116. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73117. get: function () {
  73118. return this._isEnabled;
  73119. },
  73120. set: function (value) {
  73121. this._isEnabled = value;
  73122. },
  73123. enumerable: true,
  73124. configurable: true
  73125. });
  73126. LensFlareSystem.prototype.getScene = function () {
  73127. return this._scene;
  73128. };
  73129. LensFlareSystem.prototype.getEmitter = function () {
  73130. return this._emitter;
  73131. };
  73132. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73133. this._emitter = newEmitter;
  73134. };
  73135. LensFlareSystem.prototype.getEmitterPosition = function () {
  73136. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73137. };
  73138. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73139. var position = this.getEmitterPosition();
  73140. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73141. this._positionX = position.x;
  73142. this._positionY = position.y;
  73143. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73144. if (this.viewportBorder > 0) {
  73145. globalViewport.x -= this.viewportBorder;
  73146. globalViewport.y -= this.viewportBorder;
  73147. globalViewport.width += this.viewportBorder * 2;
  73148. globalViewport.height += this.viewportBorder * 2;
  73149. position.x += this.viewportBorder;
  73150. position.y += this.viewportBorder;
  73151. this._positionX += this.viewportBorder;
  73152. this._positionY += this.viewportBorder;
  73153. }
  73154. if (position.z > 0) {
  73155. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73156. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73157. return true;
  73158. }
  73159. return true;
  73160. }
  73161. return false;
  73162. };
  73163. LensFlareSystem.prototype._isVisible = function () {
  73164. if (!this._isEnabled || !this._scene.activeCamera) {
  73165. return false;
  73166. }
  73167. var emitterPosition = this.getEmitterPosition();
  73168. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73169. var distance = direction.length();
  73170. direction.normalize();
  73171. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73172. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73173. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73174. };
  73175. LensFlareSystem.prototype.render = function () {
  73176. if (!this._effect.isReady() || !this._scene.activeCamera)
  73177. return false;
  73178. var engine = this._scene.getEngine();
  73179. var viewport = this._scene.activeCamera.viewport;
  73180. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73181. // Position
  73182. if (!this.computeEffectivePosition(globalViewport)) {
  73183. return false;
  73184. }
  73185. // Visibility
  73186. if (!this._isVisible()) {
  73187. return false;
  73188. }
  73189. // Intensity
  73190. var awayX;
  73191. var awayY;
  73192. if (this._positionX < this.borderLimit + globalViewport.x) {
  73193. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73194. }
  73195. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73196. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73197. }
  73198. else {
  73199. awayX = 0;
  73200. }
  73201. if (this._positionY < this.borderLimit + globalViewport.y) {
  73202. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73203. }
  73204. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73205. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73206. }
  73207. else {
  73208. awayY = 0;
  73209. }
  73210. var away = (awayX > awayY) ? awayX : awayY;
  73211. away -= this.viewportBorder;
  73212. if (away > this.borderLimit) {
  73213. away = this.borderLimit;
  73214. }
  73215. var intensity = 1.0 - (away / this.borderLimit);
  73216. if (intensity < 0) {
  73217. return false;
  73218. }
  73219. if (intensity > 1.0) {
  73220. intensity = 1.0;
  73221. }
  73222. if (this.viewportBorder > 0) {
  73223. globalViewport.x += this.viewportBorder;
  73224. globalViewport.y += this.viewportBorder;
  73225. globalViewport.width -= this.viewportBorder * 2;
  73226. globalViewport.height -= this.viewportBorder * 2;
  73227. this._positionX -= this.viewportBorder;
  73228. this._positionY -= this.viewportBorder;
  73229. }
  73230. // Position
  73231. var centerX = globalViewport.x + globalViewport.width / 2;
  73232. var centerY = globalViewport.y + globalViewport.height / 2;
  73233. var distX = centerX - this._positionX;
  73234. var distY = centerY - this._positionY;
  73235. // Effects
  73236. engine.enableEffect(this._effect);
  73237. engine.setState(false);
  73238. engine.setDepthBuffer(false);
  73239. // VBOs
  73240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73241. // Flares
  73242. for (var index = 0; index < this.lensFlares.length; index++) {
  73243. var flare = this.lensFlares[index];
  73244. engine.setAlphaMode(flare.alphaMode);
  73245. var x = centerX - (distX * flare.position);
  73246. var y = centerY - (distY * flare.position);
  73247. var cw = flare.size;
  73248. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73249. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73250. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73251. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73252. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73253. // Texture
  73254. this._effect.setTexture("textureSampler", flare.texture);
  73255. // Color
  73256. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73257. // Draw order
  73258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73259. }
  73260. engine.setDepthBuffer(true);
  73261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73262. return true;
  73263. };
  73264. LensFlareSystem.prototype.dispose = function () {
  73265. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73266. if (vertexBuffer) {
  73267. vertexBuffer.dispose();
  73268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73269. }
  73270. if (this._indexBuffer) {
  73271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73272. this._indexBuffer = null;
  73273. }
  73274. while (this.lensFlares.length) {
  73275. this.lensFlares[0].dispose();
  73276. }
  73277. // Remove from scene
  73278. var index = this._scene.lensFlareSystems.indexOf(this);
  73279. this._scene.lensFlareSystems.splice(index, 1);
  73280. };
  73281. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73282. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73283. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73284. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73285. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73286. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73287. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73288. var parsedFlare = parsedLensFlareSystem.flares[index];
  73289. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73290. }
  73291. return lensFlareSystem;
  73292. };
  73293. LensFlareSystem.prototype.serialize = function () {
  73294. var serializationObject = {};
  73295. serializationObject.id = this.id;
  73296. serializationObject.name = this.name;
  73297. serializationObject.emitterId = this.getEmitter().id;
  73298. serializationObject.borderLimit = this.borderLimit;
  73299. serializationObject.flares = [];
  73300. for (var index = 0; index < this.lensFlares.length; index++) {
  73301. var flare = this.lensFlares[index];
  73302. serializationObject.flares.push({
  73303. size: flare.size,
  73304. position: flare.position,
  73305. color: flare.color.asArray(),
  73306. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73307. });
  73308. }
  73309. return serializationObject;
  73310. };
  73311. return LensFlareSystem;
  73312. }());
  73313. BABYLON.LensFlareSystem = LensFlareSystem;
  73314. })(BABYLON || (BABYLON = {}));
  73315. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73316. var BABYLON;
  73317. (function (BABYLON) {
  73318. /**
  73319. * This is a holder class for the physics joint created by the physics plugin.
  73320. * It holds a set of functions to control the underlying joint.
  73321. */
  73322. var PhysicsJoint = /** @class */ (function () {
  73323. function PhysicsJoint(type, jointData) {
  73324. this.type = type;
  73325. this.jointData = jointData;
  73326. jointData.nativeParams = jointData.nativeParams || {};
  73327. }
  73328. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73329. get: function () {
  73330. return this._physicsJoint;
  73331. },
  73332. set: function (newJoint) {
  73333. if (this._physicsJoint) {
  73334. //remove from the wolrd
  73335. }
  73336. this._physicsJoint = newJoint;
  73337. },
  73338. enumerable: true,
  73339. configurable: true
  73340. });
  73341. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73342. set: function (physicsPlugin) {
  73343. this._physicsPlugin = physicsPlugin;
  73344. },
  73345. enumerable: true,
  73346. configurable: true
  73347. });
  73348. /**
  73349. * Execute a function that is physics-plugin specific.
  73350. * @param {Function} func the function that will be executed.
  73351. * It accepts two parameters: the physics world and the physics joint.
  73352. */
  73353. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73354. func(this._physicsPlugin.world, this._physicsJoint);
  73355. };
  73356. //TODO check if the native joints are the same
  73357. //Joint Types
  73358. PhysicsJoint.DistanceJoint = 0;
  73359. PhysicsJoint.HingeJoint = 1;
  73360. PhysicsJoint.BallAndSocketJoint = 2;
  73361. PhysicsJoint.WheelJoint = 3;
  73362. PhysicsJoint.SliderJoint = 4;
  73363. //OIMO
  73364. PhysicsJoint.PrismaticJoint = 5;
  73365. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73366. PhysicsJoint.UniversalJoint = 6;
  73367. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73368. //Cannon
  73369. //Similar to a Ball-Joint. Different in params
  73370. PhysicsJoint.PointToPointJoint = 8;
  73371. //Cannon only at the moment
  73372. PhysicsJoint.SpringJoint = 9;
  73373. PhysicsJoint.LockJoint = 10;
  73374. return PhysicsJoint;
  73375. }());
  73376. BABYLON.PhysicsJoint = PhysicsJoint;
  73377. /**
  73378. * A class representing a physics distance joint.
  73379. */
  73380. var DistanceJoint = /** @class */ (function (_super) {
  73381. __extends(DistanceJoint, _super);
  73382. function DistanceJoint(jointData) {
  73383. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73384. }
  73385. /**
  73386. * Update the predefined distance.
  73387. */
  73388. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73389. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73390. };
  73391. return DistanceJoint;
  73392. }(PhysicsJoint));
  73393. BABYLON.DistanceJoint = DistanceJoint;
  73394. var MotorEnabledJoint = /** @class */ (function (_super) {
  73395. __extends(MotorEnabledJoint, _super);
  73396. function MotorEnabledJoint(type, jointData) {
  73397. return _super.call(this, type, jointData) || this;
  73398. }
  73399. /**
  73400. * Set the motor values.
  73401. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73402. * @param {number} force the force to apply
  73403. * @param {number} maxForce max force for this motor.
  73404. */
  73405. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73406. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73407. };
  73408. /**
  73409. * Set the motor's limits.
  73410. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73411. */
  73412. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73413. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73414. };
  73415. return MotorEnabledJoint;
  73416. }(PhysicsJoint));
  73417. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73418. /**
  73419. * This class represents a single hinge physics joint
  73420. */
  73421. var HingeJoint = /** @class */ (function (_super) {
  73422. __extends(HingeJoint, _super);
  73423. function HingeJoint(jointData) {
  73424. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73425. }
  73426. /**
  73427. * Set the motor values.
  73428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73429. * @param {number} force the force to apply
  73430. * @param {number} maxForce max force for this motor.
  73431. */
  73432. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73433. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73434. };
  73435. /**
  73436. * Set the motor's limits.
  73437. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73438. */
  73439. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73440. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73441. };
  73442. return HingeJoint;
  73443. }(MotorEnabledJoint));
  73444. BABYLON.HingeJoint = HingeJoint;
  73445. /**
  73446. * This class represents a dual hinge physics joint (same as wheel joint)
  73447. */
  73448. var Hinge2Joint = /** @class */ (function (_super) {
  73449. __extends(Hinge2Joint, _super);
  73450. function Hinge2Joint(jointData) {
  73451. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73452. }
  73453. /**
  73454. * Set the motor values.
  73455. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73456. * @param {number} force the force to apply
  73457. * @param {number} maxForce max force for this motor.
  73458. * @param {motorIndex} the motor's index, 0 or 1.
  73459. */
  73460. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73461. if (motorIndex === void 0) { motorIndex = 0; }
  73462. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73463. };
  73464. /**
  73465. * Set the motor limits.
  73466. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73467. * @param {number} upperLimit the upper limit
  73468. * @param {number} lowerLimit lower limit
  73469. * @param {motorIndex} the motor's index, 0 or 1.
  73470. */
  73471. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73472. if (motorIndex === void 0) { motorIndex = 0; }
  73473. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73474. };
  73475. return Hinge2Joint;
  73476. }(MotorEnabledJoint));
  73477. BABYLON.Hinge2Joint = Hinge2Joint;
  73478. })(BABYLON || (BABYLON = {}));
  73479. //# sourceMappingURL=babylon.physicsJoint.js.map
  73480. var BABYLON;
  73481. (function (BABYLON) {
  73482. var PhysicsImpostor = /** @class */ (function () {
  73483. function PhysicsImpostor(object, type, _options, _scene) {
  73484. if (_options === void 0) { _options = { mass: 0 }; }
  73485. var _this = this;
  73486. this.object = object;
  73487. this.type = type;
  73488. this._options = _options;
  73489. this._scene = _scene;
  73490. this._bodyUpdateRequired = false;
  73491. this._onBeforePhysicsStepCallbacks = new Array();
  73492. this._onAfterPhysicsStepCallbacks = new Array();
  73493. this._onPhysicsCollideCallbacks = [];
  73494. this._deltaPosition = BABYLON.Vector3.Zero();
  73495. this._isDisposed = false;
  73496. //temp variables for parent rotation calculations
  73497. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73498. this._tmpQuat = new BABYLON.Quaternion();
  73499. this._tmpQuat2 = new BABYLON.Quaternion();
  73500. /**
  73501. * this function is executed by the physics engine.
  73502. */
  73503. this.beforeStep = function () {
  73504. if (!_this._physicsEngine) {
  73505. return;
  73506. }
  73507. _this.object.translate(_this._deltaPosition, -1);
  73508. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73509. _this.object.computeWorldMatrix(false);
  73510. if (_this.object.parent && _this.object.rotationQuaternion) {
  73511. _this.getParentsRotation();
  73512. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73513. }
  73514. else {
  73515. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73516. }
  73517. if (!_this._options.disableBidirectionalTransformation) {
  73518. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73519. }
  73520. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73521. func(_this);
  73522. });
  73523. };
  73524. /**
  73525. * this function is executed by the physics engine.
  73526. */
  73527. this.afterStep = function () {
  73528. if (!_this._physicsEngine) {
  73529. return;
  73530. }
  73531. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73532. func(_this);
  73533. });
  73534. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73535. // object has now its world rotation. needs to be converted to local.
  73536. if (_this.object.parent && _this.object.rotationQuaternion) {
  73537. _this.getParentsRotation();
  73538. _this._tmpQuat.conjugateInPlace();
  73539. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73540. }
  73541. // take the position set and make it the absolute position of this object.
  73542. _this.object.setAbsolutePosition(_this.object.position);
  73543. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73544. _this.object.translate(_this._deltaPosition, 1);
  73545. };
  73546. /**
  73547. * Legacy collision detection event support
  73548. */
  73549. this.onCollideEvent = null;
  73550. //event and body object due to cannon's event-based architecture.
  73551. this.onCollide = function (e) {
  73552. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73553. return;
  73554. }
  73555. if (!_this._physicsEngine) {
  73556. return;
  73557. }
  73558. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73559. if (otherImpostor) {
  73560. // Legacy collision detection event support
  73561. if (_this.onCollideEvent) {
  73562. _this.onCollideEvent(_this, otherImpostor);
  73563. }
  73564. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73565. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73566. }).forEach(function (obj) {
  73567. obj.callback(_this, otherImpostor);
  73568. });
  73569. }
  73570. };
  73571. //sanity check!
  73572. if (!this.object) {
  73573. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73574. return;
  73575. }
  73576. //legacy support for old syntax.
  73577. if (!this._scene && object.getScene) {
  73578. this._scene = object.getScene();
  73579. }
  73580. if (!this._scene) {
  73581. return;
  73582. }
  73583. this._physicsEngine = this._scene.getPhysicsEngine();
  73584. if (!this._physicsEngine) {
  73585. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73586. }
  73587. else {
  73588. //set the object's quaternion, if not set
  73589. if (!this.object.rotationQuaternion) {
  73590. if (this.object.rotation) {
  73591. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73592. }
  73593. else {
  73594. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73595. }
  73596. }
  73597. //default options params
  73598. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73599. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73600. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73601. this._joints = [];
  73602. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73603. if (!this.object.parent || this._options.ignoreParent) {
  73604. this._init();
  73605. }
  73606. else if (this.object.parent.physicsImpostor) {
  73607. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73608. }
  73609. }
  73610. }
  73611. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73612. get: function () {
  73613. return this._isDisposed;
  73614. },
  73615. enumerable: true,
  73616. configurable: true
  73617. });
  73618. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73619. get: function () {
  73620. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73621. },
  73622. set: function (value) {
  73623. this.setMass(value);
  73624. },
  73625. enumerable: true,
  73626. configurable: true
  73627. });
  73628. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73629. get: function () {
  73630. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73631. },
  73632. set: function (value) {
  73633. if (!this._physicsEngine) {
  73634. return;
  73635. }
  73636. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73637. },
  73638. enumerable: true,
  73639. configurable: true
  73640. });
  73641. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73642. get: function () {
  73643. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73644. },
  73645. set: function (value) {
  73646. if (!this._physicsEngine) {
  73647. return;
  73648. }
  73649. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73650. },
  73651. enumerable: true,
  73652. configurable: true
  73653. });
  73654. /**
  73655. * This function will completly initialize this impostor.
  73656. * It will create a new body - but only if this mesh has no parent.
  73657. * If it has, this impostor will not be used other than to define the impostor
  73658. * of the child mesh.
  73659. */
  73660. PhysicsImpostor.prototype._init = function () {
  73661. if (!this._physicsEngine) {
  73662. return;
  73663. }
  73664. this._physicsEngine.removeImpostor(this);
  73665. this.physicsBody = null;
  73666. this._parent = this._parent || this._getPhysicsParent();
  73667. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73668. this._physicsEngine.addImpostor(this);
  73669. }
  73670. };
  73671. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73672. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73673. var parentMesh = this.object.parent;
  73674. return parentMesh.physicsImpostor;
  73675. }
  73676. return null;
  73677. };
  73678. /**
  73679. * Should a new body be generated.
  73680. */
  73681. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73682. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73683. };
  73684. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73685. this.forceUpdate();
  73686. };
  73687. /**
  73688. * Force a regeneration of this or the parent's impostor's body.
  73689. * Use under cautious - This will remove all joints already implemented.
  73690. */
  73691. PhysicsImpostor.prototype.forceUpdate = function () {
  73692. this._init();
  73693. if (this.parent && !this._options.ignoreParent) {
  73694. this.parent.forceUpdate();
  73695. }
  73696. };
  73697. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73698. /*public get mesh(): AbstractMesh {
  73699. return this._mesh;
  73700. }*/
  73701. /**
  73702. * Gets the body that holds this impostor. Either its own, or its parent.
  73703. */
  73704. get: function () {
  73705. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73706. },
  73707. /**
  73708. * Set the physics body. Used mainly by the physics engine/plugin
  73709. */
  73710. set: function (physicsBody) {
  73711. if (this._physicsBody && this._physicsEngine) {
  73712. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73713. }
  73714. this._physicsBody = physicsBody;
  73715. this.resetUpdateFlags();
  73716. },
  73717. enumerable: true,
  73718. configurable: true
  73719. });
  73720. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73721. get: function () {
  73722. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73723. },
  73724. set: function (value) {
  73725. this._parent = value;
  73726. },
  73727. enumerable: true,
  73728. configurable: true
  73729. });
  73730. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73731. this._bodyUpdateRequired = false;
  73732. };
  73733. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73734. if (this.object.getBoundingInfo) {
  73735. var q = this.object.rotationQuaternion;
  73736. //reset rotation
  73737. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73738. //calculate the world matrix with no rotation
  73739. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73740. var boundingInfo = this.object.getBoundingInfo();
  73741. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73742. //bring back the rotation
  73743. this.object.rotationQuaternion = q;
  73744. //calculate the world matrix with the new rotation
  73745. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73746. return size;
  73747. }
  73748. else {
  73749. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73750. }
  73751. };
  73752. PhysicsImpostor.prototype.getObjectCenter = function () {
  73753. if (this.object.getBoundingInfo) {
  73754. var boundingInfo = this.object.getBoundingInfo();
  73755. return boundingInfo.boundingBox.centerWorld;
  73756. }
  73757. else {
  73758. return this.object.position;
  73759. }
  73760. };
  73761. /**
  73762. * Get a specific parametes from the options parameter.
  73763. */
  73764. PhysicsImpostor.prototype.getParam = function (paramName) {
  73765. return this._options[paramName];
  73766. };
  73767. /**
  73768. * Sets a specific parameter in the options given to the physics plugin
  73769. */
  73770. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73771. this._options[paramName] = value;
  73772. this._bodyUpdateRequired = true;
  73773. };
  73774. /**
  73775. * Specifically change the body's mass option. Won't recreate the physics body object
  73776. */
  73777. PhysicsImpostor.prototype.setMass = function (mass) {
  73778. if (this.getParam("mass") !== mass) {
  73779. this.setParam("mass", mass);
  73780. }
  73781. if (this._physicsEngine) {
  73782. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73783. }
  73784. };
  73785. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73786. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73787. };
  73788. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73789. if (this._physicsEngine) {
  73790. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73791. }
  73792. };
  73793. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73794. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73795. };
  73796. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73797. if (this._physicsEngine) {
  73798. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73799. }
  73800. };
  73801. /**
  73802. * Execute a function with the physics plugin native code.
  73803. * Provide a function the will have two variables - the world object and the physics body object.
  73804. */
  73805. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73806. if (this._physicsEngine) {
  73807. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73808. }
  73809. };
  73810. /**
  73811. * Register a function that will be executed before the physics world is stepping forward.
  73812. */
  73813. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73814. this._onBeforePhysicsStepCallbacks.push(func);
  73815. };
  73816. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73817. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73818. if (index > -1) {
  73819. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73820. }
  73821. else {
  73822. BABYLON.Tools.Warn("Function to remove was not found");
  73823. }
  73824. };
  73825. /**
  73826. * Register a function that will be executed after the physics step
  73827. */
  73828. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73829. this._onAfterPhysicsStepCallbacks.push(func);
  73830. };
  73831. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73832. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73833. if (index > -1) {
  73834. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73835. }
  73836. else {
  73837. BABYLON.Tools.Warn("Function to remove was not found");
  73838. }
  73839. };
  73840. /**
  73841. * register a function that will be executed when this impostor collides against a different body.
  73842. */
  73843. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73844. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73845. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73846. };
  73847. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73848. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73849. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73850. if (index > -1) {
  73851. this._onPhysicsCollideCallbacks.splice(index, 1);
  73852. }
  73853. else {
  73854. BABYLON.Tools.Warn("Function to remove was not found");
  73855. }
  73856. };
  73857. PhysicsImpostor.prototype.getParentsRotation = function () {
  73858. var parent = this.object.parent;
  73859. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73860. while (parent) {
  73861. if (parent.rotationQuaternion) {
  73862. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73863. }
  73864. else {
  73865. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73866. }
  73867. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73868. parent = parent.parent;
  73869. }
  73870. return this._tmpQuat;
  73871. };
  73872. /**
  73873. * Apply a force
  73874. */
  73875. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73876. if (this._physicsEngine) {
  73877. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73878. }
  73879. return this;
  73880. };
  73881. /**
  73882. * Apply an impulse
  73883. */
  73884. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73885. if (this._physicsEngine) {
  73886. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73887. }
  73888. return this;
  73889. };
  73890. /**
  73891. * A help function to create a joint.
  73892. */
  73893. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73894. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73895. this.addJoint(otherImpostor, joint);
  73896. return this;
  73897. };
  73898. /**
  73899. * Add a joint to this impostor with a different impostor.
  73900. */
  73901. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73902. this._joints.push({
  73903. otherImpostor: otherImpostor,
  73904. joint: joint
  73905. });
  73906. if (this._physicsEngine) {
  73907. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73908. }
  73909. return this;
  73910. };
  73911. /**
  73912. * Will keep this body still, in a sleep mode.
  73913. */
  73914. PhysicsImpostor.prototype.sleep = function () {
  73915. if (this._physicsEngine) {
  73916. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73917. }
  73918. return this;
  73919. };
  73920. /**
  73921. * Wake the body up.
  73922. */
  73923. PhysicsImpostor.prototype.wakeUp = function () {
  73924. if (this._physicsEngine) {
  73925. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73926. }
  73927. return this;
  73928. };
  73929. PhysicsImpostor.prototype.clone = function (newObject) {
  73930. if (!newObject)
  73931. return null;
  73932. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73933. };
  73934. PhysicsImpostor.prototype.dispose = function () {
  73935. var _this = this;
  73936. //no dispose if no physics engine is available.
  73937. if (!this._physicsEngine) {
  73938. return;
  73939. }
  73940. this._joints.forEach(function (j) {
  73941. if (_this._physicsEngine) {
  73942. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73943. }
  73944. });
  73945. //dispose the physics body
  73946. this._physicsEngine.removeImpostor(this);
  73947. if (this.parent) {
  73948. this.parent.forceUpdate();
  73949. }
  73950. else {
  73951. /*this._object.getChildMeshes().forEach(function(mesh) {
  73952. if (mesh.physicsImpostor) {
  73953. if (disposeChildren) {
  73954. mesh.physicsImpostor.dispose();
  73955. mesh.physicsImpostor = null;
  73956. }
  73957. }
  73958. })*/
  73959. }
  73960. this._isDisposed = true;
  73961. };
  73962. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73963. this._deltaPosition.copyFrom(position);
  73964. };
  73965. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73966. if (!this._deltaRotation) {
  73967. this._deltaRotation = new BABYLON.Quaternion();
  73968. }
  73969. this._deltaRotation.copyFrom(rotation);
  73970. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73971. };
  73972. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73973. if (this._physicsEngine) {
  73974. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73975. }
  73976. return this;
  73977. };
  73978. PhysicsImpostor.prototype.getRadius = function () {
  73979. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73980. };
  73981. /**
  73982. * Sync a bone with this impostor
  73983. * @param bone The bone to sync to the impostor.
  73984. * @param boneMesh The mesh that the bone is influencing.
  73985. * @param jointPivot The pivot of the joint / bone in local space.
  73986. * @param distToJoint Optional distance from the impostor to the joint.
  73987. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73988. */
  73989. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73990. var tempVec = PhysicsImpostor._tmpVecs[0];
  73991. var mesh = this.object;
  73992. if (mesh.rotationQuaternion) {
  73993. if (adjustRotation) {
  73994. var tempQuat = PhysicsImpostor._tmpQuat;
  73995. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73996. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73997. }
  73998. else {
  73999. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  74000. }
  74001. }
  74002. tempVec.x = 0;
  74003. tempVec.y = 0;
  74004. tempVec.z = 0;
  74005. if (jointPivot) {
  74006. tempVec.x = jointPivot.x;
  74007. tempVec.y = jointPivot.y;
  74008. tempVec.z = jointPivot.z;
  74009. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  74010. if (distToJoint === undefined || distToJoint === null) {
  74011. distToJoint = jointPivot.length();
  74012. }
  74013. tempVec.x *= distToJoint;
  74014. tempVec.y *= distToJoint;
  74015. tempVec.z *= distToJoint;
  74016. }
  74017. if (bone.getParent()) {
  74018. tempVec.addInPlace(mesh.getAbsolutePosition());
  74019. bone.setAbsolutePosition(tempVec, boneMesh);
  74020. }
  74021. else {
  74022. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  74023. boneMesh.position.x -= tempVec.x;
  74024. boneMesh.position.y -= tempVec.y;
  74025. boneMesh.position.z -= tempVec.z;
  74026. }
  74027. };
  74028. /**
  74029. * Sync impostor to a bone
  74030. * @param bone The bone that the impostor will be synced to.
  74031. * @param boneMesh The mesh that the bone is influencing.
  74032. * @param jointPivot The pivot of the joint / bone in local space.
  74033. * @param distToJoint Optional distance from the impostor to the joint.
  74034. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74035. * @param boneAxis Optional vector3 axis the bone is aligned with
  74036. */
  74037. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  74038. var mesh = this.object;
  74039. if (mesh.rotationQuaternion) {
  74040. if (adjustRotation) {
  74041. var tempQuat = PhysicsImpostor._tmpQuat;
  74042. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  74043. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  74044. }
  74045. else {
  74046. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  74047. }
  74048. }
  74049. var pos = PhysicsImpostor._tmpVecs[0];
  74050. var boneDir = PhysicsImpostor._tmpVecs[1];
  74051. if (!boneAxis) {
  74052. boneAxis = PhysicsImpostor._tmpVecs[2];
  74053. boneAxis.x = 0;
  74054. boneAxis.y = 1;
  74055. boneAxis.z = 0;
  74056. }
  74057. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  74058. bone.getAbsolutePositionToRef(boneMesh, pos);
  74059. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  74060. distToJoint = jointPivot.length();
  74061. }
  74062. if (distToJoint !== undefined && distToJoint !== null) {
  74063. pos.x += boneDir.x * distToJoint;
  74064. pos.y += boneDir.y * distToJoint;
  74065. pos.z += boneDir.z * distToJoint;
  74066. }
  74067. mesh.setAbsolutePosition(pos);
  74068. };
  74069. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  74070. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  74071. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74072. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  74073. //Impostor types
  74074. PhysicsImpostor.NoImpostor = 0;
  74075. PhysicsImpostor.SphereImpostor = 1;
  74076. PhysicsImpostor.BoxImpostor = 2;
  74077. PhysicsImpostor.PlaneImpostor = 3;
  74078. PhysicsImpostor.MeshImpostor = 4;
  74079. PhysicsImpostor.CylinderImpostor = 7;
  74080. PhysicsImpostor.ParticleImpostor = 8;
  74081. PhysicsImpostor.HeightmapImpostor = 9;
  74082. return PhysicsImpostor;
  74083. }());
  74084. BABYLON.PhysicsImpostor = PhysicsImpostor;
  74085. })(BABYLON || (BABYLON = {}));
  74086. //# sourceMappingURL=babylon.physicsImpostor.js.map
  74087. var BABYLON;
  74088. (function (BABYLON) {
  74089. var PhysicsEngine = /** @class */ (function () {
  74090. function PhysicsEngine(gravity, _physicsPlugin) {
  74091. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  74092. this._physicsPlugin = _physicsPlugin;
  74093. //new methods and parameters
  74094. this._impostors = [];
  74095. this._joints = [];
  74096. if (!this._physicsPlugin.isSupported()) {
  74097. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74098. + "Please make sure it is included.");
  74099. }
  74100. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74101. this.setGravity(gravity);
  74102. this.setTimeStep();
  74103. }
  74104. PhysicsEngine.prototype.setGravity = function (gravity) {
  74105. this.gravity = gravity;
  74106. this._physicsPlugin.setGravity(this.gravity);
  74107. };
  74108. /**
  74109. * Set the time step of the physics engine.
  74110. * default is 1/60.
  74111. * To slow it down, enter 1/600 for example.
  74112. * To speed it up, 1/30
  74113. * @param {number} newTimeStep the new timestep to apply to this world.
  74114. */
  74115. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74116. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74117. this._physicsPlugin.setTimeStep(newTimeStep);
  74118. };
  74119. /**
  74120. * Get the time step of the physics engine.
  74121. */
  74122. PhysicsEngine.prototype.getTimeStep = function () {
  74123. return this._physicsPlugin.getTimeStep();
  74124. };
  74125. PhysicsEngine.prototype.dispose = function () {
  74126. this._impostors.forEach(function (impostor) {
  74127. impostor.dispose();
  74128. });
  74129. this._physicsPlugin.dispose();
  74130. };
  74131. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74132. return this._physicsPlugin.name;
  74133. };
  74134. /**
  74135. * Adding a new impostor for the impostor tracking.
  74136. * This will be done by the impostor itself.
  74137. * @param {PhysicsImpostor} impostor the impostor to add
  74138. */
  74139. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74140. impostor.uniqueId = this._impostors.push(impostor);
  74141. //if no parent, generate the body
  74142. if (!impostor.parent) {
  74143. this._physicsPlugin.generatePhysicsBody(impostor);
  74144. }
  74145. };
  74146. /**
  74147. * Remove an impostor from the engine.
  74148. * This impostor and its mesh will not longer be updated by the physics engine.
  74149. * @param {PhysicsImpostor} impostor the impostor to remove
  74150. */
  74151. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74152. var index = this._impostors.indexOf(impostor);
  74153. if (index > -1) {
  74154. var removed = this._impostors.splice(index, 1);
  74155. //Is it needed?
  74156. if (removed.length) {
  74157. //this will also remove it from the world.
  74158. removed[0].physicsBody = null;
  74159. }
  74160. }
  74161. };
  74162. /**
  74163. * Add a joint to the physics engine
  74164. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74165. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74166. * @param {PhysicsJoint} the joint that will connect both impostors.
  74167. */
  74168. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74169. var impostorJoint = {
  74170. mainImpostor: mainImpostor,
  74171. connectedImpostor: connectedImpostor,
  74172. joint: joint
  74173. };
  74174. joint.physicsPlugin = this._physicsPlugin;
  74175. this._joints.push(impostorJoint);
  74176. this._physicsPlugin.generateJoint(impostorJoint);
  74177. };
  74178. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74179. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74180. return (impostorJoint.connectedImpostor === connectedImpostor
  74181. && impostorJoint.joint === joint
  74182. && impostorJoint.mainImpostor === mainImpostor);
  74183. });
  74184. if (matchingJoints.length) {
  74185. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74186. //TODO remove it from the list as well
  74187. }
  74188. };
  74189. /**
  74190. * Called by the scene. no need to call it.
  74191. */
  74192. PhysicsEngine.prototype._step = function (delta) {
  74193. var _this = this;
  74194. //check if any mesh has no body / requires an update
  74195. this._impostors.forEach(function (impostor) {
  74196. if (impostor.isBodyInitRequired()) {
  74197. _this._physicsPlugin.generatePhysicsBody(impostor);
  74198. }
  74199. });
  74200. if (delta > 0.1) {
  74201. delta = 0.1;
  74202. }
  74203. else if (delta <= 0) {
  74204. delta = 1.0 / 60.0;
  74205. }
  74206. this._physicsPlugin.executeStep(delta, this._impostors);
  74207. };
  74208. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74209. return this._physicsPlugin;
  74210. };
  74211. PhysicsEngine.prototype.getImpostors = function () {
  74212. return this._impostors;
  74213. };
  74214. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74215. for (var i = 0; i < this._impostors.length; ++i) {
  74216. if (this._impostors[i].object === object) {
  74217. return this._impostors[i];
  74218. }
  74219. }
  74220. return null;
  74221. };
  74222. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74223. for (var i = 0; i < this._impostors.length; ++i) {
  74224. if (this._impostors[i].physicsBody === body) {
  74225. return this._impostors[i];
  74226. }
  74227. }
  74228. return null;
  74229. };
  74230. // Statics
  74231. PhysicsEngine.Epsilon = 0.001;
  74232. return PhysicsEngine;
  74233. }());
  74234. BABYLON.PhysicsEngine = PhysicsEngine;
  74235. })(BABYLON || (BABYLON = {}));
  74236. //# sourceMappingURL=babylon.physicsEngine.js.map
  74237. var BABYLON;
  74238. (function (BABYLON) {
  74239. var PhysicsHelper = /** @class */ (function () {
  74240. function PhysicsHelper(scene) {
  74241. this._scene = scene;
  74242. this._physicsEngine = this._scene.getPhysicsEngine();
  74243. if (!this._physicsEngine) {
  74244. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74245. }
  74246. }
  74247. /**
  74248. * @param {Vector3} origin the origin of the explosion
  74249. * @param {number} radius the explosion radius
  74250. * @param {number} strength the explosion strength
  74251. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74252. */
  74253. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74254. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74255. if (!this._physicsEngine) {
  74256. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74257. return null;
  74258. }
  74259. var impostors = this._physicsEngine.getImpostors();
  74260. if (impostors.length === 0) {
  74261. return null;
  74262. }
  74263. var event = new PhysicsRadialExplosionEvent(this._scene);
  74264. impostors.forEach(function (impostor) {
  74265. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74266. if (!impostorForceAndContactPoint) {
  74267. return;
  74268. }
  74269. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74270. });
  74271. event.dispose(false);
  74272. return event;
  74273. };
  74274. /**
  74275. * @param {Vector3} origin the origin of the explosion
  74276. * @param {number} radius the explosion radius
  74277. * @param {number} strength the explosion strength
  74278. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74279. */
  74280. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74281. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74282. if (!this._physicsEngine) {
  74283. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74284. return null;
  74285. }
  74286. var impostors = this._physicsEngine.getImpostors();
  74287. if (impostors.length === 0) {
  74288. return null;
  74289. }
  74290. var event = new PhysicsRadialExplosionEvent(this._scene);
  74291. impostors.forEach(function (impostor) {
  74292. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74293. if (!impostorForceAndContactPoint) {
  74294. return;
  74295. }
  74296. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74297. });
  74298. event.dispose(false);
  74299. return event;
  74300. };
  74301. /**
  74302. * @param {Vector3} origin the origin of the explosion
  74303. * @param {number} radius the explosion radius
  74304. * @param {number} strength the explosion strength
  74305. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74306. */
  74307. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74308. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74309. if (!this._physicsEngine) {
  74310. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74311. return null;
  74312. }
  74313. var impostors = this._physicsEngine.getImpostors();
  74314. if (impostors.length === 0) {
  74315. return null;
  74316. }
  74317. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74318. event.dispose(false);
  74319. return event;
  74320. };
  74321. /**
  74322. * @param {Vector3} origin the origin of the updraft
  74323. * @param {number} radius the radius of the updraft
  74324. * @param {number} strength the strength of the updraft
  74325. * @param {number} height the height of the updraft
  74326. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74327. */
  74328. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74329. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74330. if (!this._physicsEngine) {
  74331. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74332. return null;
  74333. }
  74334. if (this._physicsEngine.getImpostors().length === 0) {
  74335. return null;
  74336. }
  74337. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74338. event.dispose(false);
  74339. return event;
  74340. };
  74341. /**
  74342. * @param {Vector3} origin the of the vortex
  74343. * @param {number} radius the radius of the vortex
  74344. * @param {number} strength the strength of the vortex
  74345. * @param {number} height the height of the vortex
  74346. */
  74347. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74348. if (!this._physicsEngine) {
  74349. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74350. return null;
  74351. }
  74352. if (this._physicsEngine.getImpostors().length === 0) {
  74353. return null;
  74354. }
  74355. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74356. event.dispose(false);
  74357. return event;
  74358. };
  74359. return PhysicsHelper;
  74360. }());
  74361. BABYLON.PhysicsHelper = PhysicsHelper;
  74362. /***** Radial explosion *****/
  74363. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74364. function PhysicsRadialExplosionEvent(scene) {
  74365. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74366. this._rays = [];
  74367. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74368. this._scene = scene;
  74369. }
  74370. /**
  74371. * Returns the data related to the radial explosion event (sphere & rays).
  74372. * @returns {PhysicsRadialExplosionEventData}
  74373. */
  74374. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74375. this._dataFetched = true;
  74376. return {
  74377. sphere: this._sphere,
  74378. rays: this._rays,
  74379. };
  74380. };
  74381. /**
  74382. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74383. * @param impostor
  74384. * @param {Vector3} origin the origin of the explosion
  74385. * @param {number} radius the explosion radius
  74386. * @param {number} strength the explosion strength
  74387. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74388. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74389. */
  74390. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74391. if (impostor.mass === 0) {
  74392. return null;
  74393. }
  74394. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74395. return null;
  74396. }
  74397. if (impostor.object.getClassName() !== 'Mesh') {
  74398. return null;
  74399. }
  74400. var impostorObject = impostor.object;
  74401. var impostorObjectCenter = impostor.getObjectCenter();
  74402. var direction = impostorObjectCenter.subtract(origin);
  74403. var ray = new BABYLON.Ray(origin, direction, radius);
  74404. this._rays.push(ray);
  74405. var hit = ray.intersectsMesh(impostorObject);
  74406. var contactPoint = hit.pickedPoint;
  74407. if (!contactPoint) {
  74408. return null;
  74409. }
  74410. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74411. if (distanceFromOrigin > radius) {
  74412. return null;
  74413. }
  74414. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74415. ? strength
  74416. : strength * (1 - (distanceFromOrigin / radius));
  74417. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74418. return { force: force, contactPoint: contactPoint };
  74419. };
  74420. /**
  74421. * Disposes the sphere.
  74422. * @param {bolean} force
  74423. */
  74424. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74425. var _this = this;
  74426. if (force === void 0) { force = true; }
  74427. if (force) {
  74428. this._sphere.dispose();
  74429. }
  74430. else {
  74431. setTimeout(function () {
  74432. if (!_this._dataFetched) {
  74433. _this._sphere.dispose();
  74434. }
  74435. }, 0);
  74436. }
  74437. };
  74438. /*** Helpers ***/
  74439. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74440. if (!this._sphere) {
  74441. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74442. this._sphere.isVisible = false;
  74443. }
  74444. };
  74445. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74446. var impostorObject = impostor.object;
  74447. this._prepareSphere();
  74448. this._sphere.position = origin;
  74449. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74450. this._sphere._updateBoundingInfo();
  74451. this._sphere.computeWorldMatrix(true);
  74452. return this._sphere.intersectsMesh(impostorObject, true);
  74453. };
  74454. return PhysicsRadialExplosionEvent;
  74455. }());
  74456. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74457. /***** Gravitational Field *****/
  74458. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74459. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74460. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74461. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74462. this._physicsHelper = physicsHelper;
  74463. this._scene = scene;
  74464. this._origin = origin;
  74465. this._radius = radius;
  74466. this._strength = strength;
  74467. this._falloff = falloff;
  74468. this._tickCallback = this._tick.bind(this);
  74469. }
  74470. /**
  74471. * Returns the data related to the gravitational field event (sphere).
  74472. * @returns {PhysicsGravitationalFieldEventData}
  74473. */
  74474. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74475. this._dataFetched = true;
  74476. return {
  74477. sphere: this._sphere,
  74478. };
  74479. };
  74480. /**
  74481. * Enables the gravitational field.
  74482. */
  74483. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74484. this._tickCallback.call(this);
  74485. this._scene.registerBeforeRender(this._tickCallback);
  74486. };
  74487. /**
  74488. * Disables the gravitational field.
  74489. */
  74490. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74491. this._scene.unregisterBeforeRender(this._tickCallback);
  74492. };
  74493. /**
  74494. * Disposes the sphere.
  74495. * @param {bolean} force
  74496. */
  74497. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74498. var _this = this;
  74499. if (force === void 0) { force = true; }
  74500. if (force) {
  74501. this._sphere.dispose();
  74502. }
  74503. else {
  74504. setTimeout(function () {
  74505. if (!_this._dataFetched) {
  74506. _this._sphere.dispose();
  74507. }
  74508. }, 0);
  74509. }
  74510. };
  74511. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74512. // Since the params won't change, we fetch the event only once
  74513. if (this._sphere) {
  74514. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74515. }
  74516. else {
  74517. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74518. if (radialExplosionEvent) {
  74519. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74520. }
  74521. }
  74522. };
  74523. return PhysicsGravitationalFieldEvent;
  74524. }());
  74525. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74526. /***** Updraft *****/
  74527. var PhysicsUpdraftEvent = /** @class */ (function () {
  74528. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74529. this._scene = _scene;
  74530. this._origin = _origin;
  74531. this._radius = _radius;
  74532. this._strength = _strength;
  74533. this._height = _height;
  74534. this._updraftMode = _updraftMode;
  74535. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74536. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74537. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74538. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74539. this._physicsEngine = this._scene.getPhysicsEngine();
  74540. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74541. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74542. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74543. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74544. }
  74545. this._tickCallback = this._tick.bind(this);
  74546. }
  74547. /**
  74548. * Returns the data related to the updraft event (cylinder).
  74549. * @returns {PhysicsUpdraftEventData}
  74550. */
  74551. PhysicsUpdraftEvent.prototype.getData = function () {
  74552. this._dataFetched = true;
  74553. return {
  74554. cylinder: this._cylinder,
  74555. };
  74556. };
  74557. /**
  74558. * Enables the updraft.
  74559. */
  74560. PhysicsUpdraftEvent.prototype.enable = function () {
  74561. this._tickCallback.call(this);
  74562. this._scene.registerBeforeRender(this._tickCallback);
  74563. };
  74564. /**
  74565. * Disables the cortex.
  74566. */
  74567. PhysicsUpdraftEvent.prototype.disable = function () {
  74568. this._scene.unregisterBeforeRender(this._tickCallback);
  74569. };
  74570. /**
  74571. * Disposes the sphere.
  74572. * @param {bolean} force
  74573. */
  74574. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74575. var _this = this;
  74576. if (force === void 0) { force = true; }
  74577. if (force) {
  74578. this._cylinder.dispose();
  74579. }
  74580. else {
  74581. setTimeout(function () {
  74582. if (!_this._dataFetched) {
  74583. _this._cylinder.dispose();
  74584. }
  74585. }, 0);
  74586. }
  74587. };
  74588. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74589. if (impostor.mass === 0) {
  74590. return null;
  74591. }
  74592. if (!this._intersectsWithCylinder(impostor)) {
  74593. return null;
  74594. }
  74595. var impostorObjectCenter = impostor.getObjectCenter();
  74596. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74597. var direction = this._originDirection;
  74598. }
  74599. else {
  74600. var direction = impostorObjectCenter.subtract(this._originTop);
  74601. }
  74602. var multiplier = this._strength * -1;
  74603. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74604. return { force: force, contactPoint: impostorObjectCenter };
  74605. };
  74606. PhysicsUpdraftEvent.prototype._tick = function () {
  74607. var _this = this;
  74608. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74609. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74610. if (!impostorForceAndContactPoint) {
  74611. return;
  74612. }
  74613. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74614. });
  74615. };
  74616. /*** Helpers ***/
  74617. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74618. if (!this._cylinder) {
  74619. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74620. height: this._height,
  74621. diameter: this._radius * 2,
  74622. }, this._scene);
  74623. this._cylinder.isVisible = false;
  74624. }
  74625. };
  74626. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74627. var impostorObject = impostor.object;
  74628. this._prepareCylinder();
  74629. this._cylinder.position = this._cylinderPosition;
  74630. return this._cylinder.intersectsMesh(impostorObject, true);
  74631. };
  74632. return PhysicsUpdraftEvent;
  74633. }());
  74634. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74635. /***** Vortex *****/
  74636. var PhysicsVortexEvent = /** @class */ (function () {
  74637. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74638. this._scene = _scene;
  74639. this._origin = _origin;
  74640. this._radius = _radius;
  74641. this._strength = _strength;
  74642. this._height = _height;
  74643. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74644. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74645. this._updraftMultiplier = 0.02;
  74646. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74647. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74648. this._physicsEngine = this._scene.getPhysicsEngine();
  74649. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74650. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74651. this._tickCallback = this._tick.bind(this);
  74652. }
  74653. /**
  74654. * Returns the data related to the vortex event (cylinder).
  74655. * @returns {PhysicsVortexEventData}
  74656. */
  74657. PhysicsVortexEvent.prototype.getData = function () {
  74658. this._dataFetched = true;
  74659. return {
  74660. cylinder: this._cylinder,
  74661. };
  74662. };
  74663. /**
  74664. * Enables the vortex.
  74665. */
  74666. PhysicsVortexEvent.prototype.enable = function () {
  74667. this._tickCallback.call(this);
  74668. this._scene.registerBeforeRender(this._tickCallback);
  74669. };
  74670. /**
  74671. * Disables the cortex.
  74672. */
  74673. PhysicsVortexEvent.prototype.disable = function () {
  74674. this._scene.unregisterBeforeRender(this._tickCallback);
  74675. };
  74676. /**
  74677. * Disposes the sphere.
  74678. * @param {bolean} force
  74679. */
  74680. PhysicsVortexEvent.prototype.dispose = function (force) {
  74681. var _this = this;
  74682. if (force === void 0) { force = true; }
  74683. if (force) {
  74684. this._cylinder.dispose();
  74685. }
  74686. else {
  74687. setTimeout(function () {
  74688. if (!_this._dataFetched) {
  74689. _this._cylinder.dispose();
  74690. }
  74691. }, 0);
  74692. }
  74693. };
  74694. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74695. if (impostor.mass === 0) {
  74696. return null;
  74697. }
  74698. if (!this._intersectsWithCylinder(impostor)) {
  74699. return null;
  74700. }
  74701. if (impostor.object.getClassName() !== 'Mesh') {
  74702. return null;
  74703. }
  74704. var impostorObject = impostor.object;
  74705. var impostorObjectCenter = impostor.getObjectCenter();
  74706. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  74707. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74708. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74709. var hit = ray.intersectsMesh(impostorObject);
  74710. var contactPoint = hit.pickedPoint;
  74711. if (!contactPoint) {
  74712. return null;
  74713. }
  74714. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74715. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74716. var directionToOrigin = contactPoint.normalize();
  74717. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74718. directionToOrigin = directionToOrigin.negate();
  74719. }
  74720. // TODO: find a more physically based solution
  74721. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74722. var forceX = directionToOrigin.x * this._strength / 8;
  74723. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74724. var forceZ = directionToOrigin.z * this._strength / 8;
  74725. }
  74726. else {
  74727. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74728. var forceY = this._originTop.y * this._updraftMultiplier;
  74729. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74730. }
  74731. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74732. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74733. return { force: force, contactPoint: impostorObjectCenter };
  74734. };
  74735. PhysicsVortexEvent.prototype._tick = function () {
  74736. var _this = this;
  74737. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74738. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74739. if (!impostorForceAndContactPoint) {
  74740. return;
  74741. }
  74742. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74743. });
  74744. };
  74745. /*** Helpers ***/
  74746. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74747. if (!this._cylinder) {
  74748. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74749. height: this._height,
  74750. diameter: this._radius * 2,
  74751. }, this._scene);
  74752. this._cylinder.isVisible = false;
  74753. }
  74754. };
  74755. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74756. var impostorObject = impostor.object;
  74757. this._prepareCylinder();
  74758. this._cylinder.position = this._cylinderPosition;
  74759. return this._cylinder.intersectsMesh(impostorObject, true);
  74760. };
  74761. return PhysicsVortexEvent;
  74762. }());
  74763. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74764. /***** Enums *****/
  74765. /**
  74766. * The strenght of the force in correspondence to the distance of the affected object
  74767. */
  74768. var PhysicsRadialImpulseFalloff;
  74769. (function (PhysicsRadialImpulseFalloff) {
  74770. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74771. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74772. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74773. /**
  74774. * The strenght of the force in correspondence to the distance of the affected object
  74775. */
  74776. var PhysicsUpdraftMode;
  74777. (function (PhysicsUpdraftMode) {
  74778. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74779. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74780. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74781. })(BABYLON || (BABYLON = {}));
  74782. //# sourceMappingURL=babylon.physicsHelper.js.map
  74783. var BABYLON;
  74784. (function (BABYLON) {
  74785. var CannonJSPlugin = /** @class */ (function () {
  74786. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74787. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74788. if (iterations === void 0) { iterations = 10; }
  74789. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74790. this.name = "CannonJSPlugin";
  74791. this._physicsMaterials = new Array();
  74792. this._fixedTimeStep = 1 / 60;
  74793. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74794. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74795. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74796. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74797. this._tmpPosition = BABYLON.Vector3.Zero();
  74798. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74799. this._tmpUnityRotation = new BABYLON.Quaternion();
  74800. if (!this.isSupported()) {
  74801. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74802. return;
  74803. }
  74804. this._extendNamespace();
  74805. this.world = new this.BJSCANNON.World();
  74806. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74807. this.world.solver.iterations = iterations;
  74808. }
  74809. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74810. this.world.gravity.copy(gravity);
  74811. };
  74812. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74813. this._fixedTimeStep = timeStep;
  74814. };
  74815. CannonJSPlugin.prototype.getTimeStep = function () {
  74816. return this._fixedTimeStep;
  74817. };
  74818. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74819. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74820. };
  74821. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74822. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74823. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74824. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74825. };
  74826. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74827. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74828. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74829. impostor.physicsBody.applyForce(impulse, worldPoint);
  74830. };
  74831. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74832. //parent-child relationship. Does this impostor has a parent impostor?
  74833. if (impostor.parent) {
  74834. if (impostor.physicsBody) {
  74835. this.removePhysicsBody(impostor);
  74836. //TODO is that needed?
  74837. impostor.forceUpdate();
  74838. }
  74839. return;
  74840. }
  74841. //should a new body be created for this impostor?
  74842. if (impostor.isBodyInitRequired()) {
  74843. var shape = this._createShape(impostor);
  74844. //unregister events, if body is being changed
  74845. var oldBody = impostor.physicsBody;
  74846. if (oldBody) {
  74847. this.removePhysicsBody(impostor);
  74848. }
  74849. //create the body and material
  74850. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74851. var bodyCreationObject = {
  74852. mass: impostor.getParam("mass"),
  74853. material: material
  74854. };
  74855. // A simple extend, in case native options were used.
  74856. var nativeOptions = impostor.getParam("nativeOptions");
  74857. for (var key in nativeOptions) {
  74858. if (nativeOptions.hasOwnProperty(key)) {
  74859. bodyCreationObject[key] = nativeOptions[key];
  74860. }
  74861. }
  74862. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74863. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74864. this.world.addEventListener("preStep", impostor.beforeStep);
  74865. this.world.addEventListener("postStep", impostor.afterStep);
  74866. impostor.physicsBody.addShape(shape);
  74867. this.world.add(impostor.physicsBody);
  74868. //try to keep the body moving in the right direction by taking old properties.
  74869. //Should be tested!
  74870. if (oldBody) {
  74871. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74872. impostor.physicsBody[param].copy(oldBody[param]);
  74873. });
  74874. }
  74875. this._processChildMeshes(impostor);
  74876. }
  74877. //now update the body's transformation
  74878. this._updatePhysicsBodyTransformation(impostor);
  74879. };
  74880. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74881. var _this = this;
  74882. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74883. var currentRotation = mainImpostor.object.rotationQuaternion;
  74884. if (meshChildren.length) {
  74885. var processMesh = function (localPosition, mesh) {
  74886. if (!currentRotation || !mesh.rotationQuaternion) {
  74887. return;
  74888. }
  74889. var childImpostor = mesh.getPhysicsImpostor();
  74890. if (childImpostor) {
  74891. var parent = childImpostor.parent;
  74892. if (parent !== mainImpostor) {
  74893. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74894. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74895. if (childImpostor.physicsBody) {
  74896. _this.removePhysicsBody(childImpostor);
  74897. childImpostor.physicsBody = null;
  74898. }
  74899. childImpostor.parent = mainImpostor;
  74900. childImpostor.resetUpdateFlags();
  74901. 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));
  74902. //Add the mass of the children.
  74903. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74904. }
  74905. }
  74906. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74907. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74908. };
  74909. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74910. }
  74911. };
  74912. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74913. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74914. this.world.removeEventListener("preStep", impostor.beforeStep);
  74915. this.world.removeEventListener("postStep", impostor.afterStep);
  74916. this.world.remove(impostor.physicsBody);
  74917. };
  74918. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74919. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74920. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74921. if (!mainBody || !connectedBody) {
  74922. return;
  74923. }
  74924. var constraint;
  74925. var jointData = impostorJoint.joint.jointData;
  74926. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74927. var constraintData = {
  74928. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74929. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74930. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74931. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74932. maxForce: jointData.nativeParams.maxForce,
  74933. collideConnected: !!jointData.collision
  74934. };
  74935. switch (impostorJoint.joint.type) {
  74936. case BABYLON.PhysicsJoint.HingeJoint:
  74937. case BABYLON.PhysicsJoint.Hinge2Joint:
  74938. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74939. break;
  74940. case BABYLON.PhysicsJoint.DistanceJoint:
  74941. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74942. break;
  74943. case BABYLON.PhysicsJoint.SpringJoint:
  74944. var springData = jointData;
  74945. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74946. restLength: springData.length,
  74947. stiffness: springData.stiffness,
  74948. damping: springData.damping,
  74949. localAnchorA: constraintData.pivotA,
  74950. localAnchorB: constraintData.pivotB
  74951. });
  74952. break;
  74953. case BABYLON.PhysicsJoint.LockJoint:
  74954. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74955. break;
  74956. case BABYLON.PhysicsJoint.PointToPointJoint:
  74957. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74958. default:
  74959. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74960. break;
  74961. }
  74962. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74963. constraint.collideConnected = !!jointData.collision;
  74964. impostorJoint.joint.physicsJoint = constraint;
  74965. //don't add spring as constraint, as it is not one.
  74966. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74967. this.world.addConstraint(constraint);
  74968. }
  74969. else {
  74970. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74971. constraint.applyForce();
  74972. });
  74973. }
  74974. };
  74975. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74976. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74977. };
  74978. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74979. var index;
  74980. var mat;
  74981. for (index = 0; index < this._physicsMaterials.length; index++) {
  74982. mat = this._physicsMaterials[index];
  74983. if (mat.friction === friction && mat.restitution === restitution) {
  74984. return mat;
  74985. }
  74986. }
  74987. var currentMat = new this.BJSCANNON.Material(name);
  74988. currentMat.friction = friction;
  74989. currentMat.restitution = restitution;
  74990. this._physicsMaterials.push(currentMat);
  74991. return currentMat;
  74992. };
  74993. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74994. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74995. };
  74996. CannonJSPlugin.prototype._createShape = function (impostor) {
  74997. var object = impostor.object;
  74998. var returnValue;
  74999. var extendSize = impostor.getObjectExtendSize();
  75000. switch (impostor.type) {
  75001. case BABYLON.PhysicsImpostor.SphereImpostor:
  75002. var radiusX = extendSize.x;
  75003. var radiusY = extendSize.y;
  75004. var radiusZ = extendSize.z;
  75005. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  75006. break;
  75007. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  75008. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75009. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  75010. break;
  75011. case BABYLON.PhysicsImpostor.BoxImpostor:
  75012. var box = extendSize.scale(0.5);
  75013. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  75014. break;
  75015. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75016. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  75017. returnValue = new this.BJSCANNON.Plane();
  75018. break;
  75019. case BABYLON.PhysicsImpostor.MeshImpostor:
  75020. // should transform the vertex data to world coordinates!!
  75021. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  75022. var rawFaces = object.getIndices ? object.getIndices() : [];
  75023. if (!rawVerts)
  75024. return;
  75025. // get only scale! so the object could transform correctly.
  75026. var oldPosition = object.position.clone();
  75027. var oldRotation = object.rotation && object.rotation.clone();
  75028. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  75029. object.position.copyFromFloats(0, 0, 0);
  75030. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75031. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75032. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75033. var transform = object.computeWorldMatrix(true);
  75034. // convert rawVerts to object space
  75035. var temp = new Array();
  75036. var index;
  75037. for (index = 0; index < rawVerts.length; index += 3) {
  75038. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  75039. }
  75040. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  75041. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  75042. //now set back the transformation!
  75043. object.position.copyFrom(oldPosition);
  75044. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  75045. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  75046. break;
  75047. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  75048. var oldPosition2 = object.position.clone();
  75049. var oldRotation2 = object.rotation && object.rotation.clone();
  75050. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  75051. object.position.copyFromFloats(0, 0, 0);
  75052. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75053. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75054. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75055. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  75056. returnValue = this._createHeightmap(object);
  75057. object.position.copyFrom(oldPosition2);
  75058. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  75059. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  75060. object.computeWorldMatrix(true);
  75061. break;
  75062. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75063. returnValue = new this.BJSCANNON.Particle();
  75064. break;
  75065. }
  75066. return returnValue;
  75067. };
  75068. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  75069. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75070. var transform = object.computeWorldMatrix(true);
  75071. // convert rawVerts to object space
  75072. var temp = new Array();
  75073. var index;
  75074. for (index = 0; index < pos.length; index += 3) {
  75075. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  75076. }
  75077. pos = temp;
  75078. var matrix = new Array();
  75079. //For now pointDepth will not be used and will be automatically calculated.
  75080. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  75081. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  75082. var boundingInfo = object.getBoundingInfo();
  75083. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  75084. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  75085. var elementSize = dim * 2 / arraySize;
  75086. for (var i = 0; i < pos.length; i = i + 3) {
  75087. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  75088. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  75089. var y = -pos[i + 2] + minY;
  75090. if (!matrix[x]) {
  75091. matrix[x] = [];
  75092. }
  75093. if (!matrix[x][z]) {
  75094. matrix[x][z] = y;
  75095. }
  75096. matrix[x][z] = Math.max(y, matrix[x][z]);
  75097. }
  75098. for (var x = 0; x <= arraySize; ++x) {
  75099. if (!matrix[x]) {
  75100. var loc = 1;
  75101. while (!matrix[(x + loc) % arraySize]) {
  75102. loc++;
  75103. }
  75104. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75105. //console.log("missing x", x);
  75106. }
  75107. for (var z = 0; z <= arraySize; ++z) {
  75108. if (!matrix[x][z]) {
  75109. var loc = 1;
  75110. var newValue;
  75111. while (newValue === undefined) {
  75112. newValue = matrix[x][(z + loc++) % arraySize];
  75113. }
  75114. matrix[x][z] = newValue;
  75115. }
  75116. }
  75117. }
  75118. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75119. elementSize: elementSize
  75120. });
  75121. //For future reference, needed for body transformation
  75122. shape.minY = minY;
  75123. return shape;
  75124. };
  75125. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75126. var object = impostor.object;
  75127. //make sure it is updated...
  75128. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75129. // The delta between the mesh position and the mesh bounding box center
  75130. var bInfo = object.getBoundingInfo();
  75131. if (!bInfo)
  75132. return;
  75133. var center = impostor.getObjectCenter();
  75134. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75135. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75136. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75137. this._tmpPosition.copyFrom(center);
  75138. var quaternion = object.rotationQuaternion;
  75139. if (!quaternion) {
  75140. return;
  75141. }
  75142. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75143. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75144. //-90 DEG in X, precalculated
  75145. quaternion = quaternion.multiply(this._minus90X);
  75146. //Invert! (Precalculated, 90 deg in X)
  75147. //No need to clone. this will never change.
  75148. impostor.setDeltaRotation(this._plus90X);
  75149. }
  75150. //If it is a heightfield, if should be centered.
  75151. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75152. var mesh = object;
  75153. var boundingInfo = mesh.getBoundingInfo();
  75154. //calculate the correct body position:
  75155. var rotationQuaternion = mesh.rotationQuaternion;
  75156. mesh.rotationQuaternion = this._tmpUnityRotation;
  75157. mesh.computeWorldMatrix(true);
  75158. //get original center with no rotation
  75159. var c = center.clone();
  75160. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75161. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75162. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75163. mesh.setPreTransformMatrix(p);
  75164. mesh.computeWorldMatrix(true);
  75165. //calculate the translation
  75166. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75167. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75168. //add it inverted to the delta
  75169. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75170. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75171. //rotation is back
  75172. mesh.rotationQuaternion = rotationQuaternion;
  75173. mesh.setPreTransformMatrix(oldPivot);
  75174. mesh.computeWorldMatrix(true);
  75175. }
  75176. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75177. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75178. //this._tmpPosition.copyFrom(object.position);
  75179. }
  75180. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75181. //Now update the impostor object
  75182. impostor.physicsBody.position.copy(this._tmpPosition);
  75183. impostor.physicsBody.quaternion.copy(quaternion);
  75184. };
  75185. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75186. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75187. if (impostor.object.rotationQuaternion) {
  75188. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75189. }
  75190. };
  75191. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75192. impostor.physicsBody.position.copy(newPosition);
  75193. impostor.physicsBody.quaternion.copy(newRotation);
  75194. };
  75195. CannonJSPlugin.prototype.isSupported = function () {
  75196. return this.BJSCANNON !== undefined;
  75197. };
  75198. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75199. impostor.physicsBody.velocity.copy(velocity);
  75200. };
  75201. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75202. impostor.physicsBody.angularVelocity.copy(velocity);
  75203. };
  75204. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75205. var v = impostor.physicsBody.velocity;
  75206. if (!v) {
  75207. return null;
  75208. }
  75209. return new BABYLON.Vector3(v.x, v.y, v.z);
  75210. };
  75211. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75212. var v = impostor.physicsBody.angularVelocity;
  75213. if (!v) {
  75214. return null;
  75215. }
  75216. return new BABYLON.Vector3(v.x, v.y, v.z);
  75217. };
  75218. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75219. impostor.physicsBody.mass = mass;
  75220. impostor.physicsBody.updateMassProperties();
  75221. };
  75222. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75223. return impostor.physicsBody.mass;
  75224. };
  75225. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75226. return impostor.physicsBody.material.friction;
  75227. };
  75228. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75229. impostor.physicsBody.material.friction = friction;
  75230. };
  75231. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75232. return impostor.physicsBody.material.restitution;
  75233. };
  75234. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75235. impostor.physicsBody.material.restitution = restitution;
  75236. };
  75237. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75238. impostor.physicsBody.sleep();
  75239. };
  75240. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75241. impostor.physicsBody.wakeUp();
  75242. };
  75243. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75244. joint.physicsJoint.distance = maxDistance;
  75245. };
  75246. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75247. // if (!motorIndex) {
  75248. // joint.physicsJoint.enableMotor();
  75249. // }
  75250. // }
  75251. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75252. // if (!motorIndex) {
  75253. // joint.physicsJoint.disableMotor();
  75254. // }
  75255. // }
  75256. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75257. if (!motorIndex) {
  75258. joint.physicsJoint.enableMotor();
  75259. joint.physicsJoint.setMotorSpeed(speed);
  75260. if (maxForce) {
  75261. this.setLimit(joint, maxForce);
  75262. }
  75263. }
  75264. };
  75265. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75266. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75267. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75268. };
  75269. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75270. var body = impostor.physicsBody;
  75271. mesh.position.x = body.position.x;
  75272. mesh.position.y = body.position.y;
  75273. mesh.position.z = body.position.z;
  75274. if (mesh.rotationQuaternion) {
  75275. mesh.rotationQuaternion.x = body.quaternion.x;
  75276. mesh.rotationQuaternion.y = body.quaternion.y;
  75277. mesh.rotationQuaternion.z = body.quaternion.z;
  75278. mesh.rotationQuaternion.w = body.quaternion.w;
  75279. }
  75280. };
  75281. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75282. var shape = impostor.physicsBody.shapes[0];
  75283. return shape.boundingSphereRadius;
  75284. };
  75285. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75286. var shape = impostor.physicsBody.shapes[0];
  75287. result.x = shape.halfExtents.x * 2;
  75288. result.y = shape.halfExtents.y * 2;
  75289. result.z = shape.halfExtents.z * 2;
  75290. };
  75291. CannonJSPlugin.prototype.dispose = function () {
  75292. };
  75293. CannonJSPlugin.prototype._extendNamespace = function () {
  75294. //this will force cannon to execute at least one step when using interpolation
  75295. var step_tmp1 = new this.BJSCANNON.Vec3();
  75296. var Engine = this.BJSCANNON;
  75297. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75298. maxSubSteps = maxSubSteps || 10;
  75299. timeSinceLastCalled = timeSinceLastCalled || 0;
  75300. if (timeSinceLastCalled === 0) {
  75301. this.internalStep(dt);
  75302. this.time += dt;
  75303. }
  75304. else {
  75305. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75306. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75307. var t0 = performance.now();
  75308. for (var i = 0; i !== internalSteps; i++) {
  75309. this.internalStep(dt);
  75310. if (performance.now() - t0 > dt * 1000) {
  75311. break;
  75312. }
  75313. }
  75314. this.time += timeSinceLastCalled;
  75315. var h = this.time % dt;
  75316. var h_div_dt = h / dt;
  75317. var interpvelo = step_tmp1;
  75318. var bodies = this.bodies;
  75319. for (var j = 0; j !== bodies.length; j++) {
  75320. var b = bodies[j];
  75321. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75322. b.position.vsub(b.previousPosition, interpvelo);
  75323. interpvelo.scale(h_div_dt, interpvelo);
  75324. b.position.vadd(interpvelo, b.interpolatedPosition);
  75325. }
  75326. else {
  75327. b.interpolatedPosition.copy(b.position);
  75328. b.interpolatedQuaternion.copy(b.quaternion);
  75329. }
  75330. }
  75331. }
  75332. };
  75333. };
  75334. return CannonJSPlugin;
  75335. }());
  75336. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75337. })(BABYLON || (BABYLON = {}));
  75338. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75339. var BABYLON;
  75340. (function (BABYLON) {
  75341. var OimoJSPlugin = /** @class */ (function () {
  75342. function OimoJSPlugin(iterations) {
  75343. this.name = "OimoJSPlugin";
  75344. this._tmpImpostorsArray = [];
  75345. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75346. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75347. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75348. this.world.worldscale(1);
  75349. this.world.clear();
  75350. //making sure no stats are calculated
  75351. this.world.isNoStat = true;
  75352. }
  75353. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75354. this.world.gravity.copy(gravity);
  75355. };
  75356. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75357. this.world.timeStep = timeStep;
  75358. };
  75359. OimoJSPlugin.prototype.getTimeStep = function () {
  75360. return this.world.timeStep;
  75361. };
  75362. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75363. var _this = this;
  75364. impostors.forEach(function (impostor) {
  75365. impostor.beforeStep();
  75366. });
  75367. this.world.step();
  75368. impostors.forEach(function (impostor) {
  75369. impostor.afterStep();
  75370. //update the ordered impostors array
  75371. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75372. });
  75373. //check for collisions
  75374. var contact = this.world.contacts;
  75375. while (contact !== null) {
  75376. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75377. contact = contact.next;
  75378. continue;
  75379. }
  75380. //is this body colliding with any other? get the impostor
  75381. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75382. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75383. if (!mainImpostor || !collidingImpostor) {
  75384. contact = contact.next;
  75385. continue;
  75386. }
  75387. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75388. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75389. contact = contact.next;
  75390. }
  75391. };
  75392. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75393. var mass = impostor.physicsBody.massInfo.mass;
  75394. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75395. };
  75396. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75397. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75398. this.applyImpulse(impostor, force, contactPoint);
  75399. };
  75400. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75401. var _this = this;
  75402. //parent-child relationship. Does this impostor has a parent impostor?
  75403. if (impostor.parent) {
  75404. if (impostor.physicsBody) {
  75405. this.removePhysicsBody(impostor);
  75406. //TODO is that needed?
  75407. impostor.forceUpdate();
  75408. }
  75409. return;
  75410. }
  75411. if (impostor.isBodyInitRequired()) {
  75412. var bodyConfig = {
  75413. name: impostor.uniqueId,
  75414. //Oimo must have mass, also for static objects.
  75415. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75416. size: [],
  75417. type: [],
  75418. pos: [],
  75419. rot: [],
  75420. move: impostor.getParam("mass") !== 0,
  75421. //Supporting older versions of Oimo
  75422. world: this.world
  75423. };
  75424. var impostors = [impostor];
  75425. var addToArray = function (parent) {
  75426. if (!parent.getChildMeshes)
  75427. return;
  75428. parent.getChildMeshes().forEach(function (m) {
  75429. if (m.physicsImpostor) {
  75430. impostors.push(m.physicsImpostor);
  75431. //m.physicsImpostor._init();
  75432. }
  75433. });
  75434. };
  75435. addToArray(impostor.object);
  75436. var checkWithEpsilon_1 = function (value) {
  75437. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75438. };
  75439. impostors.forEach(function (i) {
  75440. if (!impostor.object.rotationQuaternion) {
  75441. return;
  75442. }
  75443. //get the correct bounding box
  75444. var oldQuaternion = i.object.rotationQuaternion;
  75445. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75446. x: impostor.object.rotationQuaternion.x,
  75447. y: impostor.object.rotationQuaternion.y,
  75448. z: impostor.object.rotationQuaternion.z,
  75449. s: impostor.object.rotationQuaternion.w
  75450. });
  75451. var extendSize = i.getObjectExtendSize();
  75452. if (i === impostor) {
  75453. var center = impostor.getObjectCenter();
  75454. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75455. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75456. //Can also use Array.prototype.push.apply
  75457. bodyConfig.pos.push(center.x);
  75458. bodyConfig.pos.push(center.y);
  75459. bodyConfig.pos.push(center.z);
  75460. //tmp solution
  75461. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75462. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75463. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75464. }
  75465. else {
  75466. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75467. bodyConfig.pos.push(localPosition.x);
  75468. bodyConfig.pos.push(localPosition.y);
  75469. bodyConfig.pos.push(localPosition.z);
  75470. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75471. bodyConfig.rot.push(0);
  75472. bodyConfig.rot.push(0);
  75473. bodyConfig.rot.push(0);
  75474. }
  75475. // register mesh
  75476. switch (i.type) {
  75477. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75478. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75479. case BABYLON.PhysicsImpostor.SphereImpostor:
  75480. var radiusX = extendSize.x;
  75481. var radiusY = extendSize.y;
  75482. var radiusZ = extendSize.z;
  75483. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75484. bodyConfig.type.push('sphere');
  75485. //due to the way oimo works with compounds, add 3 times
  75486. bodyConfig.size.push(size);
  75487. bodyConfig.size.push(size);
  75488. bodyConfig.size.push(size);
  75489. break;
  75490. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75491. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75492. var sizeY = checkWithEpsilon_1(extendSize.y);
  75493. bodyConfig.type.push('cylinder');
  75494. bodyConfig.size.push(sizeX);
  75495. bodyConfig.size.push(sizeY);
  75496. //due to the way oimo works with compounds, add one more value.
  75497. bodyConfig.size.push(sizeY);
  75498. break;
  75499. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75500. case BABYLON.PhysicsImpostor.BoxImpostor:
  75501. default:
  75502. var sizeX = checkWithEpsilon_1(extendSize.x);
  75503. var sizeY = checkWithEpsilon_1(extendSize.y);
  75504. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75505. bodyConfig.type.push('box');
  75506. bodyConfig.size.push(sizeX);
  75507. bodyConfig.size.push(sizeY);
  75508. bodyConfig.size.push(sizeZ);
  75509. break;
  75510. }
  75511. //actually not needed, but hey...
  75512. i.object.rotationQuaternion = oldQuaternion;
  75513. });
  75514. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75515. }
  75516. else {
  75517. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75518. }
  75519. impostor.setDeltaPosition(this._tmpPositionVector);
  75520. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75521. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75522. };
  75523. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75524. //impostor.physicsBody.dispose();
  75525. //Same as : (older oimo versions)
  75526. this.world.removeRigidBody(impostor.physicsBody);
  75527. };
  75528. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75529. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75530. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75531. if (!mainBody || !connectedBody) {
  75532. return;
  75533. }
  75534. var jointData = impostorJoint.joint.jointData;
  75535. var options = jointData.nativeParams || {};
  75536. var type;
  75537. var nativeJointData = {
  75538. body1: mainBody,
  75539. body2: connectedBody,
  75540. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75541. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75542. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75543. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75544. min: options.min,
  75545. max: options.max,
  75546. collision: options.collision || jointData.collision,
  75547. spring: options.spring,
  75548. //supporting older version of Oimo
  75549. world: this.world
  75550. };
  75551. switch (impostorJoint.joint.type) {
  75552. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75553. type = "jointBall";
  75554. break;
  75555. case BABYLON.PhysicsJoint.SpringJoint:
  75556. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75557. var springData = jointData;
  75558. nativeJointData.min = springData.length || nativeJointData.min;
  75559. //Max should also be set, just make sure it is at least min
  75560. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75561. case BABYLON.PhysicsJoint.DistanceJoint:
  75562. type = "jointDistance";
  75563. nativeJointData.max = jointData.maxDistance;
  75564. break;
  75565. case BABYLON.PhysicsJoint.PrismaticJoint:
  75566. type = "jointPrisme";
  75567. break;
  75568. case BABYLON.PhysicsJoint.SliderJoint:
  75569. type = "jointSlide";
  75570. break;
  75571. case BABYLON.PhysicsJoint.WheelJoint:
  75572. type = "jointWheel";
  75573. break;
  75574. case BABYLON.PhysicsJoint.HingeJoint:
  75575. default:
  75576. type = "jointHinge";
  75577. break;
  75578. }
  75579. nativeJointData.type = type;
  75580. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75581. };
  75582. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75583. //Bug in Oimo prevents us from disposing a joint in the playground
  75584. //joint.joint.physicsJoint.dispose();
  75585. //So we will bruteforce it!
  75586. try {
  75587. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75588. }
  75589. catch (e) {
  75590. BABYLON.Tools.Warn(e);
  75591. }
  75592. };
  75593. OimoJSPlugin.prototype.isSupported = function () {
  75594. return this.BJSOIMO !== undefined;
  75595. };
  75596. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75597. if (!impostor.physicsBody.sleeping) {
  75598. //TODO check that
  75599. if (impostor.physicsBody.shapes.next) {
  75600. var parentShape = this._getLastShape(impostor.physicsBody);
  75601. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75602. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75603. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75604. }
  75605. else {
  75606. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75607. }
  75608. if (impostor.object.rotationQuaternion) {
  75609. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75610. impostor.object.rotationQuaternion.normalize();
  75611. }
  75612. }
  75613. };
  75614. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75615. var body = impostor.physicsBody;
  75616. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75617. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75618. body.syncShapes();
  75619. body.awake();
  75620. };
  75621. OimoJSPlugin.prototype._getLastShape = function (body) {
  75622. var lastShape = body.shapes;
  75623. while (lastShape.next) {
  75624. lastShape = lastShape.next;
  75625. }
  75626. return lastShape;
  75627. };
  75628. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75629. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75630. };
  75631. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75632. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75633. };
  75634. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75635. var v = impostor.physicsBody.linearVelocity;
  75636. if (!v) {
  75637. return null;
  75638. }
  75639. return new BABYLON.Vector3(v.x, v.y, v.z);
  75640. };
  75641. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75642. var v = impostor.physicsBody.angularVelocity;
  75643. if (!v) {
  75644. return null;
  75645. }
  75646. return new BABYLON.Vector3(v.x, v.y, v.z);
  75647. };
  75648. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75649. var staticBody = mass === 0;
  75650. //this will actually set the body's density and not its mass.
  75651. //But this is how oimo treats the mass variable.
  75652. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75653. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75654. };
  75655. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75656. return impostor.physicsBody.shapes.density;
  75657. };
  75658. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75659. return impostor.physicsBody.shapes.friction;
  75660. };
  75661. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75662. impostor.physicsBody.shapes.friction = friction;
  75663. };
  75664. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75665. return impostor.physicsBody.shapes.restitution;
  75666. };
  75667. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75668. impostor.physicsBody.shapes.restitution = restitution;
  75669. };
  75670. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75671. impostor.physicsBody.sleep();
  75672. };
  75673. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75674. impostor.physicsBody.awake();
  75675. };
  75676. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75677. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75678. if (minDistance !== void 0) {
  75679. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75680. }
  75681. };
  75682. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75683. //TODO separate rotational and transational motors.
  75684. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75685. if (motor) {
  75686. motor.setMotor(speed, maxForce);
  75687. }
  75688. };
  75689. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75690. //TODO separate rotational and transational motors.
  75691. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75692. if (motor) {
  75693. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75694. }
  75695. };
  75696. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75697. var body = impostor.physicsBody;
  75698. mesh.position.x = body.position.x;
  75699. mesh.position.y = body.position.y;
  75700. mesh.position.z = body.position.z;
  75701. if (mesh.rotationQuaternion) {
  75702. mesh.rotationQuaternion.x = body.orientation.x;
  75703. mesh.rotationQuaternion.y = body.orientation.y;
  75704. mesh.rotationQuaternion.z = body.orientation.z;
  75705. mesh.rotationQuaternion.w = body.orientation.s;
  75706. }
  75707. };
  75708. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75709. return impostor.physicsBody.shapes.radius;
  75710. };
  75711. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75712. var shape = impostor.physicsBody.shapes;
  75713. result.x = shape.halfWidth * 2;
  75714. result.y = shape.halfHeight * 2;
  75715. result.z = shape.halfDepth * 2;
  75716. };
  75717. OimoJSPlugin.prototype.dispose = function () {
  75718. this.world.clear();
  75719. };
  75720. return OimoJSPlugin;
  75721. }());
  75722. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75723. })(BABYLON || (BABYLON = {}));
  75724. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75725. var BABYLON;
  75726. (function (BABYLON) {
  75727. /*
  75728. * Based on jsTGALoader - Javascript loader for TGA file
  75729. * By Vincent Thibault
  75730. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75731. */
  75732. var TGATools = /** @class */ (function () {
  75733. function TGATools() {
  75734. }
  75735. TGATools.GetTGAHeader = function (data) {
  75736. var offset = 0;
  75737. var header = {
  75738. id_length: data[offset++],
  75739. colormap_type: data[offset++],
  75740. image_type: data[offset++],
  75741. colormap_index: data[offset++] | data[offset++] << 8,
  75742. colormap_length: data[offset++] | data[offset++] << 8,
  75743. colormap_size: data[offset++],
  75744. origin: [
  75745. data[offset++] | data[offset++] << 8,
  75746. data[offset++] | data[offset++] << 8
  75747. ],
  75748. width: data[offset++] | data[offset++] << 8,
  75749. height: data[offset++] | data[offset++] << 8,
  75750. pixel_size: data[offset++],
  75751. flags: data[offset++]
  75752. };
  75753. return header;
  75754. };
  75755. TGATools.UploadContent = function (gl, data) {
  75756. // Not enough data to contain header ?
  75757. if (data.length < 19) {
  75758. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75759. return;
  75760. }
  75761. // Read Header
  75762. var offset = 18;
  75763. var header = TGATools.GetTGAHeader(data);
  75764. // Assume it's a valid Targa file.
  75765. if (header.id_length + offset > data.length) {
  75766. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75767. return;
  75768. }
  75769. // Skip not needed data
  75770. offset += header.id_length;
  75771. var use_rle = false;
  75772. var use_pal = false;
  75773. var use_grey = false;
  75774. // Get some informations.
  75775. switch (header.image_type) {
  75776. case TGATools._TYPE_RLE_INDEXED:
  75777. use_rle = true;
  75778. case TGATools._TYPE_INDEXED:
  75779. use_pal = true;
  75780. break;
  75781. case TGATools._TYPE_RLE_RGB:
  75782. use_rle = true;
  75783. case TGATools._TYPE_RGB:
  75784. // use_rgb = true;
  75785. break;
  75786. case TGATools._TYPE_RLE_GREY:
  75787. use_rle = true;
  75788. case TGATools._TYPE_GREY:
  75789. use_grey = true;
  75790. break;
  75791. }
  75792. var pixel_data;
  75793. // var numAlphaBits = header.flags & 0xf;
  75794. var pixel_size = header.pixel_size >> 3;
  75795. var pixel_total = header.width * header.height * pixel_size;
  75796. // Read palettes
  75797. var palettes;
  75798. if (use_pal) {
  75799. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75800. }
  75801. // Read LRE
  75802. if (use_rle) {
  75803. pixel_data = new Uint8Array(pixel_total);
  75804. var c, count, i;
  75805. var localOffset = 0;
  75806. var pixels = new Uint8Array(pixel_size);
  75807. while (offset < pixel_total && localOffset < pixel_total) {
  75808. c = data[offset++];
  75809. count = (c & 0x7f) + 1;
  75810. // RLE pixels
  75811. if (c & 0x80) {
  75812. // Bind pixel tmp array
  75813. for (i = 0; i < pixel_size; ++i) {
  75814. pixels[i] = data[offset++];
  75815. }
  75816. // Copy pixel array
  75817. for (i = 0; i < count; ++i) {
  75818. pixel_data.set(pixels, localOffset + i * pixel_size);
  75819. }
  75820. localOffset += pixel_size * count;
  75821. }
  75822. else {
  75823. count *= pixel_size;
  75824. for (i = 0; i < count; ++i) {
  75825. pixel_data[localOffset + i] = data[offset++];
  75826. }
  75827. localOffset += count;
  75828. }
  75829. }
  75830. }
  75831. else {
  75832. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75833. }
  75834. // Load to texture
  75835. var x_start, y_start, x_step, y_step, y_end, x_end;
  75836. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75837. default:
  75838. case TGATools._ORIGIN_UL:
  75839. x_start = 0;
  75840. x_step = 1;
  75841. x_end = header.width;
  75842. y_start = 0;
  75843. y_step = 1;
  75844. y_end = header.height;
  75845. break;
  75846. case TGATools._ORIGIN_BL:
  75847. x_start = 0;
  75848. x_step = 1;
  75849. x_end = header.width;
  75850. y_start = header.height - 1;
  75851. y_step = -1;
  75852. y_end = -1;
  75853. break;
  75854. case TGATools._ORIGIN_UR:
  75855. x_start = header.width - 1;
  75856. x_step = -1;
  75857. x_end = -1;
  75858. y_start = 0;
  75859. y_step = 1;
  75860. y_end = header.height;
  75861. break;
  75862. case TGATools._ORIGIN_BR:
  75863. x_start = header.width - 1;
  75864. x_step = -1;
  75865. x_end = -1;
  75866. y_start = header.height - 1;
  75867. y_step = -1;
  75868. y_end = -1;
  75869. break;
  75870. }
  75871. // Load the specify method
  75872. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75873. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75874. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75875. };
  75876. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75877. var image = pixel_data, colormap = palettes;
  75878. var width = header.width, height = header.height;
  75879. var color, i = 0, x, y;
  75880. var imageData = new Uint8Array(width * height * 4);
  75881. for (y = y_start; y !== y_end; y += y_step) {
  75882. for (x = x_start; x !== x_end; x += x_step, i++) {
  75883. color = image[i];
  75884. imageData[(x + width * y) * 4 + 3] = 255;
  75885. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75886. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75887. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75888. }
  75889. }
  75890. return imageData;
  75891. };
  75892. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75893. var image = pixel_data;
  75894. var width = header.width, height = header.height;
  75895. var color, i = 0, x, y;
  75896. var imageData = new Uint8Array(width * height * 4);
  75897. for (y = y_start; y !== y_end; y += y_step) {
  75898. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75899. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75900. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75901. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75902. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75903. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75904. }
  75905. }
  75906. return imageData;
  75907. };
  75908. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75909. var image = pixel_data;
  75910. var width = header.width, height = header.height;
  75911. var i = 0, x, y;
  75912. var imageData = new Uint8Array(width * height * 4);
  75913. for (y = y_start; y !== y_end; y += y_step) {
  75914. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75915. imageData[(x + width * y) * 4 + 3] = 255;
  75916. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75917. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75918. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75919. }
  75920. }
  75921. return imageData;
  75922. };
  75923. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75924. var image = pixel_data;
  75925. var width = header.width, height = header.height;
  75926. var i = 0, x, y;
  75927. var imageData = new Uint8Array(width * height * 4);
  75928. for (y = y_start; y !== y_end; y += y_step) {
  75929. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75930. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75931. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75932. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75933. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75934. }
  75935. }
  75936. return imageData;
  75937. };
  75938. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75939. var image = pixel_data;
  75940. var width = header.width, height = header.height;
  75941. var color, i = 0, x, y;
  75942. var imageData = new Uint8Array(width * height * 4);
  75943. for (y = y_start; y !== y_end; y += y_step) {
  75944. for (x = x_start; x !== x_end; x += x_step, i++) {
  75945. color = image[i];
  75946. imageData[(x + width * y) * 4 + 0] = color;
  75947. imageData[(x + width * y) * 4 + 1] = color;
  75948. imageData[(x + width * y) * 4 + 2] = color;
  75949. imageData[(x + width * y) * 4 + 3] = 255;
  75950. }
  75951. }
  75952. return imageData;
  75953. };
  75954. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75955. var image = pixel_data;
  75956. var width = header.width, height = header.height;
  75957. var i = 0, x, y;
  75958. var imageData = new Uint8Array(width * height * 4);
  75959. for (y = y_start; y !== y_end; y += y_step) {
  75960. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75961. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75962. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75963. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75964. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75965. }
  75966. }
  75967. return imageData;
  75968. };
  75969. //private static _TYPE_NO_DATA = 0;
  75970. TGATools._TYPE_INDEXED = 1;
  75971. TGATools._TYPE_RGB = 2;
  75972. TGATools._TYPE_GREY = 3;
  75973. TGATools._TYPE_RLE_INDEXED = 9;
  75974. TGATools._TYPE_RLE_RGB = 10;
  75975. TGATools._TYPE_RLE_GREY = 11;
  75976. TGATools._ORIGIN_MASK = 0x30;
  75977. TGATools._ORIGIN_SHIFT = 0x04;
  75978. TGATools._ORIGIN_BL = 0x00;
  75979. TGATools._ORIGIN_BR = 0x01;
  75980. TGATools._ORIGIN_UL = 0x02;
  75981. TGATools._ORIGIN_UR = 0x03;
  75982. return TGATools;
  75983. }());
  75984. BABYLON.TGATools = TGATools;
  75985. })(BABYLON || (BABYLON = {}));
  75986. //# sourceMappingURL=babylon.tga.js.map
  75987. var BABYLON;
  75988. (function (BABYLON) {
  75989. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75990. // All values and structures referenced from:
  75991. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75992. var DDS_MAGIC = 0x20534444;
  75993. var
  75994. //DDSD_CAPS = 0x1,
  75995. //DDSD_HEIGHT = 0x2,
  75996. //DDSD_WIDTH = 0x4,
  75997. //DDSD_PITCH = 0x8,
  75998. //DDSD_PIXELFORMAT = 0x1000,
  75999. DDSD_MIPMAPCOUNT = 0x20000;
  76000. //DDSD_LINEARSIZE = 0x80000,
  76001. //DDSD_DEPTH = 0x800000;
  76002. // var DDSCAPS_COMPLEX = 0x8,
  76003. // DDSCAPS_MIPMAP = 0x400000,
  76004. // DDSCAPS_TEXTURE = 0x1000;
  76005. var DDSCAPS2_CUBEMAP = 0x200;
  76006. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  76007. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  76008. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  76009. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  76010. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  76011. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  76012. // DDSCAPS2_VOLUME = 0x200000;
  76013. var
  76014. //DDPF_ALPHAPIXELS = 0x1,
  76015. //DDPF_ALPHA = 0x2,
  76016. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  76017. //DDPF_YUV = 0x200,
  76018. DDPF_LUMINANCE = 0x20000;
  76019. function FourCCToInt32(value) {
  76020. return value.charCodeAt(0) +
  76021. (value.charCodeAt(1) << 8) +
  76022. (value.charCodeAt(2) << 16) +
  76023. (value.charCodeAt(3) << 24);
  76024. }
  76025. function Int32ToFourCC(value) {
  76026. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  76027. }
  76028. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  76029. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  76030. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  76031. var FOURCC_DX10 = FourCCToInt32("DX10");
  76032. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  76033. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  76034. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  76035. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  76036. var headerLengthInt = 31; // The header length in 32 bit ints
  76037. // Offsets into the header array
  76038. var off_magic = 0;
  76039. var off_size = 1;
  76040. var off_flags = 2;
  76041. var off_height = 3;
  76042. var off_width = 4;
  76043. var off_mipmapCount = 7;
  76044. var off_pfFlags = 20;
  76045. var off_pfFourCC = 21;
  76046. var off_RGBbpp = 22;
  76047. var off_RMask = 23;
  76048. var off_GMask = 24;
  76049. var off_BMask = 25;
  76050. var off_AMask = 26;
  76051. // var off_caps1 = 27;
  76052. var off_caps2 = 28;
  76053. // var off_caps3 = 29;
  76054. // var off_caps4 = 30;
  76055. var off_dxgiFormat = 32;
  76056. ;
  76057. var DDSTools = /** @class */ (function () {
  76058. function DDSTools() {
  76059. }
  76060. DDSTools.GetDDSInfo = function (arrayBuffer) {
  76061. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76062. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  76063. var mipmapCount = 1;
  76064. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  76065. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76066. }
  76067. var fourCC = header[off_pfFourCC];
  76068. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  76069. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76070. switch (fourCC) {
  76071. case FOURCC_D3DFMT_R16G16B16A16F:
  76072. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76073. break;
  76074. case FOURCC_D3DFMT_R32G32B32A32F:
  76075. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76076. break;
  76077. case FOURCC_DX10:
  76078. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  76079. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76080. break;
  76081. }
  76082. }
  76083. return {
  76084. width: header[off_width],
  76085. height: header[off_height],
  76086. mipmapCount: mipmapCount,
  76087. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  76088. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  76089. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  76090. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  76091. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  76092. dxgiFormat: dxgiFormat,
  76093. textureType: textureType
  76094. };
  76095. };
  76096. DDSTools._ToHalfFloat = function (value) {
  76097. if (!DDSTools._FloatView) {
  76098. DDSTools._FloatView = new Float32Array(1);
  76099. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76100. }
  76101. DDSTools._FloatView[0] = value;
  76102. var x = DDSTools._Int32View[0];
  76103. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76104. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76105. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76106. /* If zero, or denormal, or exponent underflows too much for a denormal
  76107. * half, return signed zero. */
  76108. if (e < 103) {
  76109. return bits;
  76110. }
  76111. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76112. if (e > 142) {
  76113. bits |= 0x7c00;
  76114. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76115. * not Inf, so make sure we set one mantissa bit too. */
  76116. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76117. return bits;
  76118. }
  76119. /* If exponent underflows but not too much, return a denormal */
  76120. if (e < 113) {
  76121. m |= 0x0800;
  76122. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76123. * to 1, which is OK. */
  76124. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76125. return bits;
  76126. }
  76127. bits |= ((e - 112) << 10) | (m >> 1);
  76128. bits += m & 1;
  76129. return bits;
  76130. };
  76131. DDSTools._FromHalfFloat = function (value) {
  76132. var s = (value & 0x8000) >> 15;
  76133. var e = (value & 0x7C00) >> 10;
  76134. var f = value & 0x03FF;
  76135. if (e === 0) {
  76136. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76137. }
  76138. else if (e == 0x1F) {
  76139. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76140. }
  76141. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76142. };
  76143. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76144. var destArray = new Float32Array(dataLength);
  76145. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76146. var index = 0;
  76147. for (var y = 0; y < height; y++) {
  76148. for (var x = 0; x < width; x++) {
  76149. var srcPos = (x + y * width) * 4;
  76150. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76151. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76152. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76153. if (DDSTools.StoreLODInAlphaChannel) {
  76154. destArray[index + 3] = lod;
  76155. }
  76156. else {
  76157. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76158. }
  76159. index += 4;
  76160. }
  76161. }
  76162. return destArray;
  76163. };
  76164. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76165. if (DDSTools.StoreLODInAlphaChannel) {
  76166. var destArray = new Uint16Array(dataLength);
  76167. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76168. var index = 0;
  76169. for (var y = 0; y < height; y++) {
  76170. for (var x = 0; x < width; x++) {
  76171. var srcPos = (x + y * width) * 4;
  76172. destArray[index] = srcData[srcPos];
  76173. destArray[index + 1] = srcData[srcPos + 1];
  76174. destArray[index + 2] = srcData[srcPos + 2];
  76175. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76176. index += 4;
  76177. }
  76178. }
  76179. return destArray;
  76180. }
  76181. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76182. };
  76183. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76184. if (DDSTools.StoreLODInAlphaChannel) {
  76185. var destArray = new Float32Array(dataLength);
  76186. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76187. var index = 0;
  76188. for (var y = 0; y < height; y++) {
  76189. for (var x = 0; x < width; x++) {
  76190. var srcPos = (x + y * width) * 4;
  76191. destArray[index] = srcData[srcPos];
  76192. destArray[index + 1] = srcData[srcPos + 1];
  76193. destArray[index + 2] = srcData[srcPos + 2];
  76194. destArray[index + 3] = lod;
  76195. index += 4;
  76196. }
  76197. }
  76198. return destArray;
  76199. }
  76200. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76201. };
  76202. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76203. var destArray = new Uint8Array(dataLength);
  76204. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76205. var index = 0;
  76206. for (var y = 0; y < height; y++) {
  76207. for (var x = 0; x < width; x++) {
  76208. var srcPos = (x + y * width) * 4;
  76209. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76210. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76211. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76212. if (DDSTools.StoreLODInAlphaChannel) {
  76213. destArray[index + 3] = lod;
  76214. }
  76215. else {
  76216. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76217. }
  76218. index += 4;
  76219. }
  76220. }
  76221. return destArray;
  76222. };
  76223. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76224. var destArray = new Uint8Array(dataLength);
  76225. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76226. var index = 0;
  76227. for (var y = 0; y < height; y++) {
  76228. for (var x = 0; x < width; x++) {
  76229. var srcPos = (x + y * width) * 4;
  76230. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76231. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76232. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76233. if (DDSTools.StoreLODInAlphaChannel) {
  76234. destArray[index + 3] = lod;
  76235. }
  76236. else {
  76237. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76238. }
  76239. index += 4;
  76240. }
  76241. }
  76242. return destArray;
  76243. };
  76244. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76245. var byteArray = new Uint8Array(dataLength);
  76246. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76247. var index = 0;
  76248. for (var y = 0; y < height; y++) {
  76249. for (var x = 0; x < width; x++) {
  76250. var srcPos = (x + y * width) * 4;
  76251. byteArray[index] = srcData[srcPos + rOffset];
  76252. byteArray[index + 1] = srcData[srcPos + gOffset];
  76253. byteArray[index + 2] = srcData[srcPos + bOffset];
  76254. byteArray[index + 3] = srcData[srcPos + aOffset];
  76255. index += 4;
  76256. }
  76257. }
  76258. return byteArray;
  76259. };
  76260. DDSTools._ExtractLongWordOrder = function (value) {
  76261. if (value === 0 || value === 255 || value === -16777216) {
  76262. return 0;
  76263. }
  76264. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76265. };
  76266. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76267. var byteArray = new Uint8Array(dataLength);
  76268. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76269. var index = 0;
  76270. for (var y = 0; y < height; y++) {
  76271. for (var x = 0; x < width; x++) {
  76272. var srcPos = (x + y * width) * 3;
  76273. byteArray[index] = srcData[srcPos + rOffset];
  76274. byteArray[index + 1] = srcData[srcPos + gOffset];
  76275. byteArray[index + 2] = srcData[srcPos + bOffset];
  76276. index += 3;
  76277. }
  76278. }
  76279. return byteArray;
  76280. };
  76281. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76282. var byteArray = new Uint8Array(dataLength);
  76283. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76284. var index = 0;
  76285. for (var y = 0; y < height; y++) {
  76286. for (var x = 0; x < width; x++) {
  76287. var srcPos = (x + y * width);
  76288. byteArray[index] = srcData[srcPos];
  76289. index++;
  76290. }
  76291. }
  76292. return byteArray;
  76293. };
  76294. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76295. if (lodIndex === void 0) { lodIndex = -1; }
  76296. var ext = engine.getCaps().s3tc;
  76297. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76298. var fourCC, width, height, dataLength = 0, dataOffset;
  76299. var byteArray, mipmapCount, mip;
  76300. var internalFormat = 0;
  76301. var format = 0;
  76302. var blockBytes = 1;
  76303. if (header[off_magic] !== DDS_MAGIC) {
  76304. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76305. return;
  76306. }
  76307. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76308. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76309. return;
  76310. }
  76311. if (info.isCompressed && !ext) {
  76312. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76313. return;
  76314. }
  76315. var bpp = header[off_RGBbpp];
  76316. dataOffset = header[off_size] + 4;
  76317. var computeFormats = false;
  76318. if (info.isFourCC) {
  76319. fourCC = header[off_pfFourCC];
  76320. switch (fourCC) {
  76321. case FOURCC_DXT1:
  76322. blockBytes = 8;
  76323. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76324. break;
  76325. case FOURCC_DXT3:
  76326. blockBytes = 16;
  76327. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76328. break;
  76329. case FOURCC_DXT5:
  76330. blockBytes = 16;
  76331. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76332. break;
  76333. case FOURCC_D3DFMT_R16G16B16A16F:
  76334. computeFormats = true;
  76335. break;
  76336. case FOURCC_D3DFMT_R32G32B32A32F:
  76337. computeFormats = true;
  76338. break;
  76339. case FOURCC_DX10:
  76340. // There is an additionnal header so dataOffset need to be changed
  76341. dataOffset += 5 * 4; // 5 uints
  76342. var supported = false;
  76343. switch (info.dxgiFormat) {
  76344. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76345. computeFormats = true;
  76346. supported = true;
  76347. break;
  76348. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76349. info.isRGB = true;
  76350. info.isFourCC = false;
  76351. bpp = 32;
  76352. supported = true;
  76353. break;
  76354. }
  76355. if (supported) {
  76356. break;
  76357. }
  76358. default:
  76359. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76360. return;
  76361. }
  76362. }
  76363. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76364. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76365. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76366. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76367. if (computeFormats) {
  76368. format = engine._getWebGLTextureType(info.textureType);
  76369. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76370. }
  76371. mipmapCount = 1;
  76372. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76373. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76374. }
  76375. for (var face = 0; face < faces; face++) {
  76376. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76377. width = header[off_width];
  76378. height = header[off_height];
  76379. for (mip = 0; mip < mipmapCount; ++mip) {
  76380. if (lodIndex === -1 || lodIndex === mip) {
  76381. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76382. var i = (lodIndex === -1) ? mip : 0;
  76383. if (!info.isCompressed && info.isFourCC) {
  76384. dataLength = width * height * 4;
  76385. var floatArray = null;
  76386. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76387. if (bpp === 128) {
  76388. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76389. }
  76390. else if (bpp === 64) {
  76391. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76392. }
  76393. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76394. format = engine._getWebGLTextureType(info.textureType);
  76395. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76396. }
  76397. else {
  76398. if (bpp === 128) {
  76399. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76400. }
  76401. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76402. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76403. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76404. format = engine._getWebGLTextureType(info.textureType);
  76405. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76406. }
  76407. else {
  76408. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76409. }
  76410. }
  76411. if (floatArray) {
  76412. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76413. }
  76414. }
  76415. else if (info.isRGB) {
  76416. if (bpp === 24) {
  76417. dataLength = width * height * 3;
  76418. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76419. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76420. }
  76421. else {
  76422. dataLength = width * height * 4;
  76423. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76424. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76425. }
  76426. }
  76427. else if (info.isLuminance) {
  76428. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76429. var unpaddedRowSize = width;
  76430. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76431. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76432. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76433. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76434. }
  76435. else {
  76436. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76437. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76438. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76439. }
  76440. }
  76441. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76442. width *= 0.5;
  76443. height *= 0.5;
  76444. width = Math.max(1.0, width);
  76445. height = Math.max(1.0, height);
  76446. }
  76447. if (currentFace !== undefined) {
  76448. // Loading a single face
  76449. break;
  76450. }
  76451. }
  76452. };
  76453. DDSTools.StoreLODInAlphaChannel = false;
  76454. return DDSTools;
  76455. }());
  76456. BABYLON.DDSTools = DDSTools;
  76457. })(BABYLON || (BABYLON = {}));
  76458. //# sourceMappingURL=babylon.dds.js.map
  76459. var BABYLON;
  76460. (function (BABYLON) {
  76461. /**
  76462. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76463. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76464. */
  76465. var KhronosTextureContainer = /** @class */ (function () {
  76466. /**
  76467. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76468. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76469. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76470. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76471. */
  76472. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76473. this.arrayBuffer = arrayBuffer;
  76474. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76475. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76476. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76477. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76478. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76479. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76480. BABYLON.Tools.Error("texture missing KTX identifier");
  76481. return;
  76482. }
  76483. // load the reset of the header in native 32 bit int
  76484. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76485. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76486. var oppositeEndianess = header[0] === 0x01020304;
  76487. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76488. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76489. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76490. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76491. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76492. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76493. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76494. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76495. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76496. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76497. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76498. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76499. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76500. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76501. if (this.glType !== 0) {
  76502. BABYLON.Tools.Error("only compressed formats currently supported");
  76503. return;
  76504. }
  76505. else {
  76506. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76507. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76508. }
  76509. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76510. BABYLON.Tools.Error("only 2D textures currently supported");
  76511. return;
  76512. }
  76513. if (this.numberOfArrayElements !== 0) {
  76514. BABYLON.Tools.Error("texture arrays not currently supported");
  76515. return;
  76516. }
  76517. if (this.numberOfFaces !== facesExpected) {
  76518. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76519. return;
  76520. }
  76521. // we now have a completely validated file, so could use existence of loadType as success
  76522. // would need to make this more elaborate & adjust checks above to support more than one load type
  76523. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76524. }
  76525. // not as fast hardware based, but will probably never need to use
  76526. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76527. return ((val & 0xFF) << 24)
  76528. | ((val & 0xFF00) << 8)
  76529. | ((val >> 8) & 0xFF00)
  76530. | ((val >> 24) & 0xFF);
  76531. };
  76532. /**
  76533. * It is assumed that the texture has already been created & is currently bound
  76534. */
  76535. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76536. switch (this.loadType) {
  76537. case KhronosTextureContainer.COMPRESSED_2D:
  76538. this._upload2DCompressedLevels(gl, loadMipmaps);
  76539. break;
  76540. case KhronosTextureContainer.TEX_2D:
  76541. case KhronosTextureContainer.COMPRESSED_3D:
  76542. case KhronosTextureContainer.TEX_3D:
  76543. }
  76544. };
  76545. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76546. // initialize width & height for level 1
  76547. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76548. var width = this.pixelWidth;
  76549. var height = this.pixelHeight;
  76550. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76551. for (var level = 0; level < mipmapCount; level++) {
  76552. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76553. for (var face = 0; face < this.numberOfFaces; face++) {
  76554. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76555. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76556. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76557. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76558. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76559. }
  76560. width = Math.max(1.0, width * 0.5);
  76561. height = Math.max(1.0, height * 0.5);
  76562. }
  76563. };
  76564. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76565. // load types
  76566. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76567. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76568. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76569. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76570. return KhronosTextureContainer;
  76571. }());
  76572. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76573. })(BABYLON || (BABYLON = {}));
  76574. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76575. var BABYLON;
  76576. (function (BABYLON) {
  76577. var Debug = /** @class */ (function () {
  76578. function Debug() {
  76579. }
  76580. Debug.AxesViewer = /** @class */ (function () {
  76581. function AxesViewer(scene, scaleLines) {
  76582. if (scaleLines === void 0) { scaleLines = 1; }
  76583. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76584. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76585. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76586. this.scaleLines = 1;
  76587. this.scaleLines = scaleLines;
  76588. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76589. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76590. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76591. this._xmesh.renderingGroupId = 2;
  76592. this._ymesh.renderingGroupId = 2;
  76593. this._zmesh.renderingGroupId = 2;
  76594. this._xmesh.material.checkReadyOnlyOnce = true;
  76595. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76596. this._ymesh.material.checkReadyOnlyOnce = true;
  76597. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76598. this._zmesh.material.checkReadyOnlyOnce = true;
  76599. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76600. this.scene = scene;
  76601. }
  76602. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76603. var scaleLines = this.scaleLines;
  76604. if (this._xmesh) {
  76605. this._xmesh.position.copyFrom(position);
  76606. }
  76607. if (this._ymesh) {
  76608. this._ymesh.position.copyFrom(position);
  76609. }
  76610. if (this._zmesh) {
  76611. this._zmesh.position.copyFrom(position);
  76612. }
  76613. var point2 = this._xline[1];
  76614. point2.x = xaxis.x * scaleLines;
  76615. point2.y = xaxis.y * scaleLines;
  76616. point2.z = xaxis.z * scaleLines;
  76617. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76618. point2 = this._yline[1];
  76619. point2.x = yaxis.x * scaleLines;
  76620. point2.y = yaxis.y * scaleLines;
  76621. point2.z = yaxis.z * scaleLines;
  76622. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76623. point2 = this._zline[1];
  76624. point2.x = zaxis.x * scaleLines;
  76625. point2.y = zaxis.y * scaleLines;
  76626. point2.z = zaxis.z * scaleLines;
  76627. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76628. };
  76629. AxesViewer.prototype.dispose = function () {
  76630. if (this._xmesh) {
  76631. this._xmesh.dispose();
  76632. }
  76633. if (this._ymesh) {
  76634. this._ymesh.dispose();
  76635. }
  76636. if (this._zmesh) {
  76637. this._zmesh.dispose();
  76638. }
  76639. this._xmesh = null;
  76640. this._ymesh = null;
  76641. this._zmesh = null;
  76642. this.scene = null;
  76643. };
  76644. return AxesViewer;
  76645. }());
  76646. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76647. __extends(BoneAxesViewer, _super);
  76648. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76649. if (scaleLines === void 0) { scaleLines = 1; }
  76650. var _this = _super.call(this, scene, scaleLines) || this;
  76651. _this.pos = BABYLON.Vector3.Zero();
  76652. _this.xaxis = BABYLON.Vector3.Zero();
  76653. _this.yaxis = BABYLON.Vector3.Zero();
  76654. _this.zaxis = BABYLON.Vector3.Zero();
  76655. _this.mesh = mesh;
  76656. _this.bone = bone;
  76657. return _this;
  76658. }
  76659. BoneAxesViewer.prototype.update = function () {
  76660. if (!this.mesh || !this.bone) {
  76661. return;
  76662. }
  76663. var bone = this.bone;
  76664. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76665. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76666. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76667. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76668. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76669. };
  76670. BoneAxesViewer.prototype.dispose = function () {
  76671. if (this.mesh) {
  76672. this.mesh = null;
  76673. this.bone = null;
  76674. _super.prototype.dispose.call(this);
  76675. }
  76676. };
  76677. return BoneAxesViewer;
  76678. }(Debug.AxesViewer));
  76679. Debug.PhysicsViewer = /** @class */ (function () {
  76680. function PhysicsViewer(scene) {
  76681. this._impostors = [];
  76682. this._meshes = [];
  76683. this._numMeshes = 0;
  76684. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76685. var physicEngine = this._scene.getPhysicsEngine();
  76686. if (physicEngine) {
  76687. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76688. }
  76689. }
  76690. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76691. var plugin = this._physicsEnginePlugin;
  76692. for (var i = 0; i < this._numMeshes; i++) {
  76693. var impostor = this._impostors[i];
  76694. if (!impostor) {
  76695. continue;
  76696. }
  76697. if (impostor.isDisposed) {
  76698. this.hideImpostor(this._impostors[i--]);
  76699. }
  76700. else {
  76701. var mesh = this._meshes[i];
  76702. if (mesh && plugin) {
  76703. plugin.syncMeshWithImpostor(mesh, impostor);
  76704. }
  76705. }
  76706. }
  76707. };
  76708. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76709. if (!this._scene) {
  76710. return;
  76711. }
  76712. for (var i = 0; i < this._numMeshes; i++) {
  76713. if (this._impostors[i] == impostor) {
  76714. return;
  76715. }
  76716. }
  76717. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76718. if (debugMesh) {
  76719. this._impostors[this._numMeshes] = impostor;
  76720. this._meshes[this._numMeshes] = debugMesh;
  76721. if (this._numMeshes === 0) {
  76722. this._renderFunction = this._updateDebugMeshes.bind(this);
  76723. this._scene.registerBeforeRender(this._renderFunction);
  76724. }
  76725. this._numMeshes++;
  76726. }
  76727. };
  76728. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76729. if (!impostor || !this._scene) {
  76730. return;
  76731. }
  76732. var removed = false;
  76733. for (var i = 0; i < this._numMeshes; i++) {
  76734. if (this._impostors[i] == impostor) {
  76735. var mesh = this._meshes[i];
  76736. if (!mesh) {
  76737. continue;
  76738. }
  76739. this._scene.removeMesh(mesh);
  76740. mesh.dispose();
  76741. this._numMeshes--;
  76742. if (this._numMeshes > 0) {
  76743. this._meshes[i] = this._meshes[this._numMeshes];
  76744. this._impostors[i] = this._impostors[this._numMeshes];
  76745. this._meshes[this._numMeshes] = null;
  76746. this._impostors[this._numMeshes] = null;
  76747. }
  76748. else {
  76749. this._meshes[0] = null;
  76750. this._impostors[0] = null;
  76751. }
  76752. removed = true;
  76753. break;
  76754. }
  76755. }
  76756. if (removed && this._numMeshes === 0) {
  76757. this._scene.unregisterBeforeRender(this._renderFunction);
  76758. }
  76759. };
  76760. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76761. if (!this._debugMaterial) {
  76762. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76763. this._debugMaterial.wireframe = true;
  76764. }
  76765. return this._debugMaterial;
  76766. };
  76767. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76768. if (!this._debugBoxMesh) {
  76769. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76770. this._debugBoxMesh.renderingGroupId = 1;
  76771. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76772. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76773. scene.removeMesh(this._debugBoxMesh);
  76774. }
  76775. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76776. };
  76777. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76778. if (!this._debugSphereMesh) {
  76779. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76780. this._debugSphereMesh.renderingGroupId = 1;
  76781. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76782. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76783. scene.removeMesh(this._debugSphereMesh);
  76784. }
  76785. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76786. };
  76787. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76788. var mesh = null;
  76789. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76790. mesh = this._getDebugBoxMesh(scene);
  76791. impostor.getBoxSizeToRef(mesh.scaling);
  76792. }
  76793. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76794. mesh = this._getDebugSphereMesh(scene);
  76795. var radius = impostor.getRadius();
  76796. mesh.scaling.x = radius * 2;
  76797. mesh.scaling.y = radius * 2;
  76798. mesh.scaling.z = radius * 2;
  76799. }
  76800. return mesh;
  76801. };
  76802. PhysicsViewer.prototype.dispose = function () {
  76803. for (var i = 0; i < this._numMeshes; i++) {
  76804. this.hideImpostor(this._impostors[i]);
  76805. }
  76806. if (this._debugBoxMesh) {
  76807. this._debugBoxMesh.dispose();
  76808. }
  76809. if (this._debugSphereMesh) {
  76810. this._debugSphereMesh.dispose();
  76811. }
  76812. if (this._debugMaterial) {
  76813. this._debugMaterial.dispose();
  76814. }
  76815. this._impostors.length = 0;
  76816. this._scene = null;
  76817. this._physicsEnginePlugin = null;
  76818. };
  76819. return PhysicsViewer;
  76820. }());
  76821. Debug.SkeletonViewer = /** @class */ (function () {
  76822. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76823. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76824. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76825. this.skeleton = skeleton;
  76826. this.mesh = mesh;
  76827. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76828. this.renderingGroupId = renderingGroupId;
  76829. this.color = BABYLON.Color3.White();
  76830. this._debugLines = new Array();
  76831. this._isEnabled = false;
  76832. this._scene = scene;
  76833. this.update();
  76834. this._renderFunction = this.update.bind(this);
  76835. }
  76836. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76837. get: function () {
  76838. return this._isEnabled;
  76839. },
  76840. set: function (value) {
  76841. if (this._isEnabled === value) {
  76842. return;
  76843. }
  76844. this._isEnabled = value;
  76845. if (value) {
  76846. this._scene.registerBeforeRender(this._renderFunction);
  76847. }
  76848. else {
  76849. this._scene.unregisterBeforeRender(this._renderFunction);
  76850. }
  76851. },
  76852. enumerable: true,
  76853. configurable: true
  76854. });
  76855. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76856. if (x === void 0) { x = 0; }
  76857. if (y === void 0) { y = 0; }
  76858. if (z === void 0) { z = 0; }
  76859. var tmat = BABYLON.Tmp.Matrix[0];
  76860. var parentBone = bone.getParent();
  76861. tmat.copyFrom(bone.getLocalMatrix());
  76862. if (x !== 0 || y !== 0 || z !== 0) {
  76863. var tmat2 = BABYLON.Tmp.Matrix[1];
  76864. BABYLON.Matrix.IdentityToRef(tmat2);
  76865. tmat2.m[12] = x;
  76866. tmat2.m[13] = y;
  76867. tmat2.m[14] = z;
  76868. tmat2.multiplyToRef(tmat, tmat);
  76869. }
  76870. if (parentBone) {
  76871. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76872. }
  76873. tmat.multiplyToRef(meshMat, tmat);
  76874. position.x = tmat.m[12];
  76875. position.y = tmat.m[13];
  76876. position.z = tmat.m[14];
  76877. };
  76878. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76879. var len = bones.length;
  76880. var meshPos = this.mesh.position;
  76881. for (var i = 0; i < len; i++) {
  76882. var bone = bones[i];
  76883. var points = this._debugLines[i];
  76884. if (!points) {
  76885. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76886. this._debugLines[i] = points;
  76887. }
  76888. this._getBonePosition(points[0], bone, meshMat);
  76889. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76890. points[0].subtractInPlace(meshPos);
  76891. points[1].subtractInPlace(meshPos);
  76892. }
  76893. };
  76894. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76895. var len = bones.length;
  76896. var boneNum = 0;
  76897. var meshPos = this.mesh.position;
  76898. for (var i = len - 1; i >= 0; i--) {
  76899. var childBone = bones[i];
  76900. var parentBone = childBone.getParent();
  76901. if (!parentBone) {
  76902. continue;
  76903. }
  76904. var points = this._debugLines[boneNum];
  76905. if (!points) {
  76906. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76907. this._debugLines[boneNum] = points;
  76908. }
  76909. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76910. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76911. points[0].subtractInPlace(meshPos);
  76912. points[1].subtractInPlace(meshPos);
  76913. boneNum++;
  76914. }
  76915. };
  76916. SkeletonViewer.prototype.update = function () {
  76917. if (this.autoUpdateBonesMatrices) {
  76918. this.skeleton.computeAbsoluteTransforms();
  76919. }
  76920. if (this.skeleton.bones[0].length === undefined) {
  76921. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76922. }
  76923. else {
  76924. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76925. }
  76926. if (!this._debugMesh) {
  76927. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76928. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76929. }
  76930. else {
  76931. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76932. }
  76933. this._debugMesh.position.copyFrom(this.mesh.position);
  76934. this._debugMesh.color = this.color;
  76935. };
  76936. SkeletonViewer.prototype.dispose = function () {
  76937. if (this._debugMesh) {
  76938. this.isEnabled = false;
  76939. this._debugMesh.dispose();
  76940. this._debugMesh = null;
  76941. }
  76942. };
  76943. return SkeletonViewer;
  76944. }());
  76945. return Debug;
  76946. }());
  76947. BABYLON.Debug = Debug;
  76948. })(BABYLON || (BABYLON = {}));
  76949. //# sourceMappingURL=babylon.debugModules.js.map
  76950. var BABYLON;
  76951. (function (BABYLON) {
  76952. var RayHelper = /** @class */ (function () {
  76953. function RayHelper(ray) {
  76954. this.ray = ray;
  76955. }
  76956. RayHelper.CreateAndShow = function (ray, scene, color) {
  76957. var helper = new RayHelper(ray);
  76958. helper.show(scene, color);
  76959. return helper;
  76960. };
  76961. RayHelper.prototype.show = function (scene, color) {
  76962. if (!this._renderFunction && this.ray) {
  76963. var ray = this.ray;
  76964. this._renderFunction = this._render.bind(this);
  76965. this._scene = scene;
  76966. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76967. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76968. if (this._renderFunction) {
  76969. this._scene.registerBeforeRender(this._renderFunction);
  76970. }
  76971. }
  76972. if (color && this._renderLine) {
  76973. this._renderLine.color.copyFrom(color);
  76974. }
  76975. };
  76976. RayHelper.prototype.hide = function () {
  76977. if (this._renderFunction && this._scene) {
  76978. this._scene.unregisterBeforeRender(this._renderFunction);
  76979. this._scene = null;
  76980. this._renderFunction = null;
  76981. if (this._renderLine) {
  76982. this._renderLine.dispose();
  76983. this._renderLine = null;
  76984. }
  76985. this._renderPoints = [];
  76986. }
  76987. };
  76988. RayHelper.prototype._render = function () {
  76989. var ray = this.ray;
  76990. if (!ray) {
  76991. return;
  76992. }
  76993. var point = this._renderPoints[1];
  76994. var len = Math.min(ray.length, 1000000);
  76995. point.copyFrom(ray.direction);
  76996. point.scaleInPlace(len);
  76997. point.addInPlace(ray.origin);
  76998. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76999. };
  77000. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  77001. this._attachedToMesh = mesh;
  77002. var ray = this.ray;
  77003. if (!ray) {
  77004. return;
  77005. }
  77006. if (!ray.direction) {
  77007. ray.direction = BABYLON.Vector3.Zero();
  77008. }
  77009. if (!ray.origin) {
  77010. ray.origin = BABYLON.Vector3.Zero();
  77011. }
  77012. if (length) {
  77013. ray.length = length;
  77014. }
  77015. if (!meshSpaceOrigin) {
  77016. meshSpaceOrigin = BABYLON.Vector3.Zero();
  77017. }
  77018. if (!meshSpaceDirection) {
  77019. // -1 so that this will work with Mesh.lookAt
  77020. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  77021. }
  77022. if (!this._meshSpaceDirection) {
  77023. this._meshSpaceDirection = meshSpaceDirection.clone();
  77024. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  77025. }
  77026. else {
  77027. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  77028. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  77029. }
  77030. if (!this._updateToMeshFunction) {
  77031. this._updateToMeshFunction = this._updateToMesh.bind(this);
  77032. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  77033. }
  77034. this._updateToMesh();
  77035. };
  77036. RayHelper.prototype.detachFromMesh = function () {
  77037. if (this._attachedToMesh) {
  77038. if (this._updateToMeshFunction) {
  77039. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  77040. }
  77041. this._attachedToMesh = null;
  77042. this._updateToMeshFunction = null;
  77043. }
  77044. };
  77045. RayHelper.prototype._updateToMesh = function () {
  77046. var ray = this.ray;
  77047. if (!this._attachedToMesh || !ray) {
  77048. return;
  77049. }
  77050. if (this._attachedToMesh._isDisposed) {
  77051. this.detachFromMesh();
  77052. return;
  77053. }
  77054. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  77055. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  77056. };
  77057. RayHelper.prototype.dispose = function () {
  77058. this.hide();
  77059. this.detachFromMesh();
  77060. this.ray = null;
  77061. };
  77062. return RayHelper;
  77063. }());
  77064. BABYLON.RayHelper = RayHelper;
  77065. })(BABYLON || (BABYLON = {}));
  77066. //# sourceMappingURL=babylon.rayHelper.js.map
  77067. var BABYLON;
  77068. (function (BABYLON) {
  77069. // load the inspector using require, if not present in the global namespace.
  77070. var DebugLayer = /** @class */ (function () {
  77071. function DebugLayer(scene) {
  77072. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77073. this._scene = scene;
  77074. // load inspector using require, if it doesn't exist on the global namespace.
  77075. }
  77076. /** Creates the inspector window. */
  77077. DebugLayer.prototype._createInspector = function (config) {
  77078. if (config === void 0) { config = {}; }
  77079. var popup = config.popup || false;
  77080. var initialTab = config.initialTab || 0;
  77081. var parentElement = config.parentElement || null;
  77082. if (!this._inspector) {
  77083. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77084. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  77085. } // else nothing to do,; instance is already existing
  77086. };
  77087. DebugLayer.prototype.isVisible = function () {
  77088. if (!this._inspector) {
  77089. return false;
  77090. }
  77091. return true;
  77092. };
  77093. DebugLayer.prototype.hide = function () {
  77094. if (this._inspector) {
  77095. try {
  77096. this._inspector.dispose();
  77097. }
  77098. catch (e) {
  77099. // If the inspector has been removed directly from the inspector tool
  77100. }
  77101. this._inspector = null;
  77102. }
  77103. };
  77104. DebugLayer.prototype.show = function (config) {
  77105. if (config === void 0) { config = {}; }
  77106. if (typeof this.BJSINSPECTOR == 'undefined') {
  77107. // Load inspector and add it to the DOM
  77108. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77109. }
  77110. else {
  77111. // Otherwise creates the inspector
  77112. this._createInspector(config);
  77113. }
  77114. };
  77115. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77116. return DebugLayer;
  77117. }());
  77118. BABYLON.DebugLayer = DebugLayer;
  77119. })(BABYLON || (BABYLON = {}));
  77120. //# sourceMappingURL=babylon.debugLayer.js.map
  77121. var BABYLON;
  77122. (function (BABYLON) {
  77123. var BoundingBoxRenderer = /** @class */ (function () {
  77124. function BoundingBoxRenderer(scene) {
  77125. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77126. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77127. this.showBackLines = true;
  77128. this.renderList = new BABYLON.SmartArray(32);
  77129. this._vertexBuffers = {};
  77130. this._scene = scene;
  77131. }
  77132. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77133. if (this._colorShader) {
  77134. return;
  77135. }
  77136. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77137. attributes: [BABYLON.VertexBuffer.PositionKind],
  77138. uniforms: ["world", "viewProjection", "color"]
  77139. });
  77140. var engine = this._scene.getEngine();
  77141. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77142. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77143. this._createIndexBuffer();
  77144. };
  77145. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77146. var engine = this._scene.getEngine();
  77147. 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]);
  77148. };
  77149. BoundingBoxRenderer.prototype._rebuild = function () {
  77150. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77151. if (vb) {
  77152. vb._rebuild();
  77153. }
  77154. this._createIndexBuffer();
  77155. };
  77156. BoundingBoxRenderer.prototype.reset = function () {
  77157. this.renderList.reset();
  77158. };
  77159. BoundingBoxRenderer.prototype.render = function () {
  77160. if (this.renderList.length === 0) {
  77161. return;
  77162. }
  77163. this._prepareRessources();
  77164. if (!this._colorShader.isReady()) {
  77165. return;
  77166. }
  77167. var engine = this._scene.getEngine();
  77168. engine.setDepthWrite(false);
  77169. this._colorShader._preBind();
  77170. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77171. var boundingBox = this.renderList.data[boundingBoxIndex];
  77172. var min = boundingBox.minimum;
  77173. var max = boundingBox.maximum;
  77174. var diff = max.subtract(min);
  77175. var median = min.add(diff.scale(0.5));
  77176. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77177. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77178. .multiply(boundingBox.getWorldMatrix());
  77179. // VBOs
  77180. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77181. if (this.showBackLines) {
  77182. // Back
  77183. engine.setDepthFunctionToGreaterOrEqual();
  77184. this._scene.resetCachedMaterial();
  77185. this._colorShader.setColor4("color", this.backColor.toColor4());
  77186. this._colorShader.bind(worldMatrix);
  77187. // Draw order
  77188. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77189. }
  77190. // Front
  77191. engine.setDepthFunctionToLess();
  77192. this._scene.resetCachedMaterial();
  77193. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77194. this._colorShader.bind(worldMatrix);
  77195. // Draw order
  77196. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77197. }
  77198. this._colorShader.unbind();
  77199. engine.setDepthFunctionToLessOrEqual();
  77200. engine.setDepthWrite(true);
  77201. };
  77202. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77203. this._prepareRessources();
  77204. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77205. return;
  77206. }
  77207. var engine = this._scene.getEngine();
  77208. engine.setDepthWrite(false);
  77209. engine.setColorWrite(false);
  77210. this._colorShader._preBind();
  77211. var boundingBox = mesh._boundingInfo.boundingBox;
  77212. var min = boundingBox.minimum;
  77213. var max = boundingBox.maximum;
  77214. var diff = max.subtract(min);
  77215. var median = min.add(diff.scale(0.5));
  77216. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77217. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77218. .multiply(boundingBox.getWorldMatrix());
  77219. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77220. engine.setDepthFunctionToLess();
  77221. this._scene.resetCachedMaterial();
  77222. this._colorShader.bind(worldMatrix);
  77223. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77224. this._colorShader.unbind();
  77225. engine.setDepthFunctionToLessOrEqual();
  77226. engine.setDepthWrite(true);
  77227. engine.setColorWrite(true);
  77228. };
  77229. BoundingBoxRenderer.prototype.dispose = function () {
  77230. if (!this._colorShader) {
  77231. return;
  77232. }
  77233. this.renderList.dispose();
  77234. this._colorShader.dispose();
  77235. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77236. if (buffer) {
  77237. buffer.dispose();
  77238. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77239. }
  77240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77241. };
  77242. return BoundingBoxRenderer;
  77243. }());
  77244. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77245. })(BABYLON || (BABYLON = {}));
  77246. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77247. var BABYLON;
  77248. (function (BABYLON) {
  77249. var MorphTarget = /** @class */ (function () {
  77250. function MorphTarget(name, influence) {
  77251. if (influence === void 0) { influence = 0; }
  77252. this.name = name;
  77253. this.animations = new Array();
  77254. this._positions = null;
  77255. this._normals = null;
  77256. this._tangents = null;
  77257. this.onInfluenceChanged = new BABYLON.Observable();
  77258. this.influence = influence;
  77259. }
  77260. Object.defineProperty(MorphTarget.prototype, "influence", {
  77261. get: function () {
  77262. return this._influence;
  77263. },
  77264. set: function (influence) {
  77265. if (this._influence === influence) {
  77266. return;
  77267. }
  77268. var previous = this._influence;
  77269. this._influence = influence;
  77270. if (this.onInfluenceChanged.hasObservers) {
  77271. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77272. }
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77278. get: function () {
  77279. return !!this._positions;
  77280. },
  77281. enumerable: true,
  77282. configurable: true
  77283. });
  77284. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77285. get: function () {
  77286. return !!this._normals;
  77287. },
  77288. enumerable: true,
  77289. configurable: true
  77290. });
  77291. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77292. get: function () {
  77293. return !!this._tangents;
  77294. },
  77295. enumerable: true,
  77296. configurable: true
  77297. });
  77298. MorphTarget.prototype.setPositions = function (data) {
  77299. this._positions = data;
  77300. };
  77301. MorphTarget.prototype.getPositions = function () {
  77302. return this._positions;
  77303. };
  77304. MorphTarget.prototype.setNormals = function (data) {
  77305. this._normals = data;
  77306. };
  77307. MorphTarget.prototype.getNormals = function () {
  77308. return this._normals;
  77309. };
  77310. MorphTarget.prototype.setTangents = function (data) {
  77311. this._tangents = data;
  77312. };
  77313. MorphTarget.prototype.getTangents = function () {
  77314. return this._tangents;
  77315. };
  77316. /**
  77317. * Serializes the current target into a Serialization object.
  77318. * Returns the serialized object.
  77319. */
  77320. MorphTarget.prototype.serialize = function () {
  77321. var serializationObject = {};
  77322. serializationObject.name = this.name;
  77323. serializationObject.influence = this.influence;
  77324. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77325. if (this.hasNormals) {
  77326. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77327. }
  77328. if (this.hasTangents) {
  77329. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77330. }
  77331. // Animations
  77332. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77333. return serializationObject;
  77334. };
  77335. // Statics
  77336. MorphTarget.Parse = function (serializationObject) {
  77337. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77338. result.setPositions(serializationObject.positions);
  77339. if (serializationObject.normals) {
  77340. result.setNormals(serializationObject.normals);
  77341. }
  77342. if (serializationObject.tangents) {
  77343. result.setTangents(serializationObject.tangents);
  77344. }
  77345. // Animations
  77346. if (serializationObject.animations) {
  77347. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77348. var parsedAnimation = serializationObject.animations[animationIndex];
  77349. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77350. }
  77351. }
  77352. return result;
  77353. };
  77354. MorphTarget.FromMesh = function (mesh, name, influence) {
  77355. if (!name) {
  77356. name = mesh.name;
  77357. }
  77358. var result = new MorphTarget(name, influence);
  77359. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77361. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77362. }
  77363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77364. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77365. }
  77366. return result;
  77367. };
  77368. return MorphTarget;
  77369. }());
  77370. BABYLON.MorphTarget = MorphTarget;
  77371. })(BABYLON || (BABYLON = {}));
  77372. //# sourceMappingURL=babylon.morphTarget.js.map
  77373. var BABYLON;
  77374. (function (BABYLON) {
  77375. var MorphTargetManager = /** @class */ (function () {
  77376. function MorphTargetManager(scene) {
  77377. if (scene === void 0) { scene = null; }
  77378. this._targets = new Array();
  77379. this._targetObservable = new Array();
  77380. this._activeTargets = new BABYLON.SmartArray(16);
  77381. this._supportsNormals = false;
  77382. this._supportsTangents = false;
  77383. this._vertexCount = 0;
  77384. this._uniqueId = 0;
  77385. this._tempInfluences = new Array();
  77386. if (!scene) {
  77387. scene = BABYLON.Engine.LastCreatedScene;
  77388. }
  77389. this._scene = scene;
  77390. if (this._scene) {
  77391. this._scene.morphTargetManagers.push(this);
  77392. this._uniqueId = this._scene.getUniqueId();
  77393. }
  77394. }
  77395. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77396. get: function () {
  77397. return this._uniqueId;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77403. get: function () {
  77404. return this._vertexCount;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77410. get: function () {
  77411. return this._supportsNormals;
  77412. },
  77413. enumerable: true,
  77414. configurable: true
  77415. });
  77416. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77417. get: function () {
  77418. return this._supportsTangents;
  77419. },
  77420. enumerable: true,
  77421. configurable: true
  77422. });
  77423. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77424. get: function () {
  77425. return this._targets.length;
  77426. },
  77427. enumerable: true,
  77428. configurable: true
  77429. });
  77430. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77431. get: function () {
  77432. return this._activeTargets.length;
  77433. },
  77434. enumerable: true,
  77435. configurable: true
  77436. });
  77437. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77438. get: function () {
  77439. return this._influences;
  77440. },
  77441. enumerable: true,
  77442. configurable: true
  77443. });
  77444. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77445. return this._activeTargets.data[index];
  77446. };
  77447. MorphTargetManager.prototype.getTarget = function (index) {
  77448. return this._targets[index];
  77449. };
  77450. MorphTargetManager.prototype.addTarget = function (target) {
  77451. var _this = this;
  77452. this._targets.push(target);
  77453. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77454. _this._syncActiveTargets(needUpdate);
  77455. }));
  77456. this._syncActiveTargets(true);
  77457. };
  77458. MorphTargetManager.prototype.removeTarget = function (target) {
  77459. var index = this._targets.indexOf(target);
  77460. if (index >= 0) {
  77461. this._targets.splice(index, 1);
  77462. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77463. this._syncActiveTargets(true);
  77464. }
  77465. };
  77466. /**
  77467. * Serializes the current manager into a Serialization object.
  77468. * Returns the serialized object.
  77469. */
  77470. MorphTargetManager.prototype.serialize = function () {
  77471. var serializationObject = {};
  77472. serializationObject.id = this.uniqueId;
  77473. serializationObject.targets = [];
  77474. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77475. var target = _a[_i];
  77476. serializationObject.targets.push(target.serialize());
  77477. }
  77478. return serializationObject;
  77479. };
  77480. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77481. var influenceCount = 0;
  77482. this._activeTargets.reset();
  77483. this._supportsNormals = true;
  77484. this._supportsTangents = true;
  77485. this._vertexCount = 0;
  77486. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77487. var target = _a[_i];
  77488. this._activeTargets.push(target);
  77489. this._tempInfluences[influenceCount++] = target.influence;
  77490. var positions = target.getPositions();
  77491. if (positions) {
  77492. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77493. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77494. var vertexCount = positions.length / 3;
  77495. if (this._vertexCount === 0) {
  77496. this._vertexCount = vertexCount;
  77497. }
  77498. else if (this._vertexCount !== vertexCount) {
  77499. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77500. return;
  77501. }
  77502. }
  77503. }
  77504. if (!this._influences || this._influences.length !== influenceCount) {
  77505. this._influences = new Float32Array(influenceCount);
  77506. }
  77507. for (var index = 0; index < influenceCount; index++) {
  77508. this._influences[index] = this._tempInfluences[index];
  77509. }
  77510. if (needUpdate && this._scene) {
  77511. // Flag meshes as dirty to resync with the active targets
  77512. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77513. var mesh = _c[_b];
  77514. if (mesh.morphTargetManager === this) {
  77515. mesh._syncGeometryWithMorphTargetManager();
  77516. }
  77517. }
  77518. }
  77519. };
  77520. // Statics
  77521. MorphTargetManager.Parse = function (serializationObject, scene) {
  77522. var result = new MorphTargetManager(scene);
  77523. result._uniqueId = serializationObject.id;
  77524. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77525. var targetData = _a[_i];
  77526. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77527. }
  77528. return result;
  77529. };
  77530. return MorphTargetManager;
  77531. }());
  77532. BABYLON.MorphTargetManager = MorphTargetManager;
  77533. })(BABYLON || (BABYLON = {}));
  77534. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77535. var BABYLON;
  77536. (function (BABYLON) {
  77537. var Octree = /** @class */ (function () {
  77538. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77539. if (maxDepth === void 0) { maxDepth = 2; }
  77540. this.maxDepth = maxDepth;
  77541. this.dynamicContent = new Array();
  77542. this._maxBlockCapacity = maxBlockCapacity || 64;
  77543. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77544. this._creationFunc = creationFunc;
  77545. }
  77546. // Methods
  77547. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77548. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77549. };
  77550. Octree.prototype.addMesh = function (entry) {
  77551. for (var index = 0; index < this.blocks.length; index++) {
  77552. var block = this.blocks[index];
  77553. block.addEntry(entry);
  77554. }
  77555. };
  77556. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77557. this._selectionContent.reset();
  77558. for (var index = 0; index < this.blocks.length; index++) {
  77559. var block = this.blocks[index];
  77560. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77561. }
  77562. if (allowDuplicate) {
  77563. this._selectionContent.concat(this.dynamicContent);
  77564. }
  77565. else {
  77566. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77567. }
  77568. return this._selectionContent;
  77569. };
  77570. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77571. this._selectionContent.reset();
  77572. for (var index = 0; index < this.blocks.length; index++) {
  77573. var block = this.blocks[index];
  77574. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77575. }
  77576. if (allowDuplicate) {
  77577. this._selectionContent.concat(this.dynamicContent);
  77578. }
  77579. else {
  77580. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77581. }
  77582. return this._selectionContent;
  77583. };
  77584. Octree.prototype.intersectsRay = function (ray) {
  77585. this._selectionContent.reset();
  77586. for (var index = 0; index < this.blocks.length; index++) {
  77587. var block = this.blocks[index];
  77588. block.intersectsRay(ray, this._selectionContent);
  77589. }
  77590. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77591. return this._selectionContent;
  77592. };
  77593. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77594. target.blocks = new Array();
  77595. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77596. // Segmenting space
  77597. for (var x = 0; x < 2; x++) {
  77598. for (var y = 0; y < 2; y++) {
  77599. for (var z = 0; z < 2; z++) {
  77600. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77601. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77602. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77603. block.addEntries(entries);
  77604. target.blocks.push(block);
  77605. }
  77606. }
  77607. }
  77608. };
  77609. Octree.CreationFuncForMeshes = function (entry, block) {
  77610. var boundingInfo = entry.getBoundingInfo();
  77611. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77612. block.entries.push(entry);
  77613. }
  77614. };
  77615. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77616. var boundingInfo = entry.getBoundingInfo();
  77617. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77618. block.entries.push(entry);
  77619. }
  77620. };
  77621. return Octree;
  77622. }());
  77623. BABYLON.Octree = Octree;
  77624. })(BABYLON || (BABYLON = {}));
  77625. //# sourceMappingURL=babylon.octree.js.map
  77626. var BABYLON;
  77627. (function (BABYLON) {
  77628. var OctreeBlock = /** @class */ (function () {
  77629. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77630. this.entries = new Array();
  77631. this._boundingVectors = new Array();
  77632. this._capacity = capacity;
  77633. this._depth = depth;
  77634. this._maxDepth = maxDepth;
  77635. this._creationFunc = creationFunc;
  77636. this._minPoint = minPoint;
  77637. this._maxPoint = maxPoint;
  77638. this._boundingVectors.push(minPoint.clone());
  77639. this._boundingVectors.push(maxPoint.clone());
  77640. this._boundingVectors.push(minPoint.clone());
  77641. this._boundingVectors[2].x = maxPoint.x;
  77642. this._boundingVectors.push(minPoint.clone());
  77643. this._boundingVectors[3].y = maxPoint.y;
  77644. this._boundingVectors.push(minPoint.clone());
  77645. this._boundingVectors[4].z = maxPoint.z;
  77646. this._boundingVectors.push(maxPoint.clone());
  77647. this._boundingVectors[5].z = minPoint.z;
  77648. this._boundingVectors.push(maxPoint.clone());
  77649. this._boundingVectors[6].x = minPoint.x;
  77650. this._boundingVectors.push(maxPoint.clone());
  77651. this._boundingVectors[7].y = minPoint.y;
  77652. }
  77653. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77654. // Property
  77655. get: function () {
  77656. return this._capacity;
  77657. },
  77658. enumerable: true,
  77659. configurable: true
  77660. });
  77661. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77662. get: function () {
  77663. return this._minPoint;
  77664. },
  77665. enumerable: true,
  77666. configurable: true
  77667. });
  77668. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77669. get: function () {
  77670. return this._maxPoint;
  77671. },
  77672. enumerable: true,
  77673. configurable: true
  77674. });
  77675. // Methods
  77676. OctreeBlock.prototype.addEntry = function (entry) {
  77677. if (this.blocks) {
  77678. for (var index = 0; index < this.blocks.length; index++) {
  77679. var block = this.blocks[index];
  77680. block.addEntry(entry);
  77681. }
  77682. return;
  77683. }
  77684. this._creationFunc(entry, this);
  77685. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77686. this.createInnerBlocks();
  77687. }
  77688. };
  77689. OctreeBlock.prototype.addEntries = function (entries) {
  77690. for (var index = 0; index < entries.length; index++) {
  77691. var mesh = entries[index];
  77692. this.addEntry(mesh);
  77693. }
  77694. };
  77695. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77696. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77697. if (this.blocks) {
  77698. for (var index = 0; index < this.blocks.length; index++) {
  77699. var block = this.blocks[index];
  77700. block.select(frustumPlanes, selection, allowDuplicate);
  77701. }
  77702. return;
  77703. }
  77704. if (allowDuplicate) {
  77705. selection.concat(this.entries);
  77706. }
  77707. else {
  77708. selection.concatWithNoDuplicate(this.entries);
  77709. }
  77710. }
  77711. };
  77712. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77713. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77714. if (this.blocks) {
  77715. for (var index = 0; index < this.blocks.length; index++) {
  77716. var block = this.blocks[index];
  77717. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77718. }
  77719. return;
  77720. }
  77721. if (allowDuplicate) {
  77722. selection.concat(this.entries);
  77723. }
  77724. else {
  77725. selection.concatWithNoDuplicate(this.entries);
  77726. }
  77727. }
  77728. };
  77729. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77730. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77731. if (this.blocks) {
  77732. for (var index = 0; index < this.blocks.length; index++) {
  77733. var block = this.blocks[index];
  77734. block.intersectsRay(ray, selection);
  77735. }
  77736. return;
  77737. }
  77738. selection.concatWithNoDuplicate(this.entries);
  77739. }
  77740. };
  77741. OctreeBlock.prototype.createInnerBlocks = function () {
  77742. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77743. };
  77744. return OctreeBlock;
  77745. }());
  77746. BABYLON.OctreeBlock = OctreeBlock;
  77747. })(BABYLON || (BABYLON = {}));
  77748. //# sourceMappingURL=babylon.octreeBlock.js.map
  77749. var BABYLON;
  77750. (function (BABYLON) {
  77751. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77752. __extends(VRDistortionCorrectionPostProcess, _super);
  77753. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77754. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77755. 'LensCenter',
  77756. 'Scale',
  77757. 'ScaleIn',
  77758. 'HmdWarpParam'
  77759. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77760. _this._isRightEye = isRightEye;
  77761. _this._distortionFactors = vrMetrics.distortionK;
  77762. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77763. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77764. _this.adaptScaleToCurrentViewport = true;
  77765. _this.onSizeChangedObservable.add(function () {
  77766. _this.aspectRatio = _this.width * .5 / _this.height;
  77767. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77768. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77769. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77770. });
  77771. _this.onApplyObservable.add(function (effect) {
  77772. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77773. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77774. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77775. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77776. });
  77777. return _this;
  77778. }
  77779. return VRDistortionCorrectionPostProcess;
  77780. }(BABYLON.PostProcess));
  77781. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77782. })(BABYLON || (BABYLON = {}));
  77783. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77784. var BABYLON;
  77785. (function (BABYLON) {
  77786. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77787. __extends(AnaglyphPostProcess, _super);
  77788. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77789. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77790. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77791. _this.onApplyObservable.add(function (effect) {
  77792. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77793. });
  77794. return _this;
  77795. }
  77796. return AnaglyphPostProcess;
  77797. }(BABYLON.PostProcess));
  77798. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77799. })(BABYLON || (BABYLON = {}));
  77800. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77801. var BABYLON;
  77802. (function (BABYLON) {
  77803. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77804. __extends(StereoscopicInterlacePostProcess, _super);
  77805. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77806. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77807. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77808. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77809. _this.onSizeChangedObservable.add(function () {
  77810. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77811. });
  77812. _this.onApplyObservable.add(function (effect) {
  77813. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77814. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77815. });
  77816. return _this;
  77817. }
  77818. return StereoscopicInterlacePostProcess;
  77819. }(BABYLON.PostProcess));
  77820. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77821. })(BABYLON || (BABYLON = {}));
  77822. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77823. var BABYLON;
  77824. (function (BABYLON) {
  77825. /**
  77826. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77827. * Screen rotation is taken into account.
  77828. */
  77829. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77830. function FreeCameraDeviceOrientationInput() {
  77831. var _this = this;
  77832. this._screenOrientationAngle = 0;
  77833. this._screenQuaternion = new BABYLON.Quaternion();
  77834. this._alpha = 0;
  77835. this._beta = 0;
  77836. this._gamma = 0;
  77837. this._orientationChanged = function () {
  77838. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77839. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77840. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77841. };
  77842. this._deviceOrientation = function (evt) {
  77843. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77844. _this._beta = evt.beta !== null ? evt.beta : 0;
  77845. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77846. };
  77847. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77848. this._orientationChanged();
  77849. }
  77850. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77851. get: function () {
  77852. return this._camera;
  77853. },
  77854. set: function (camera) {
  77855. this._camera = camera;
  77856. if (this._camera != null && !this._camera.rotationQuaternion) {
  77857. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77858. }
  77859. },
  77860. enumerable: true,
  77861. configurable: true
  77862. });
  77863. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77864. window.addEventListener("orientationchange", this._orientationChanged);
  77865. window.addEventListener("deviceorientation", this._deviceOrientation);
  77866. //In certain cases, the attach control is called AFTER orientation was changed,
  77867. //So this is needed.
  77868. this._orientationChanged();
  77869. };
  77870. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77871. window.removeEventListener("orientationchange", this._orientationChanged);
  77872. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77873. };
  77874. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77875. //if no device orientation provided, don't update the rotation.
  77876. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77877. if (!this._alpha)
  77878. return;
  77879. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77880. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77881. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77882. //Mirror on XY Plane
  77883. this._camera.rotationQuaternion.z *= -1;
  77884. this._camera.rotationQuaternion.w *= -1;
  77885. };
  77886. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77887. return "FreeCameraDeviceOrientationInput";
  77888. };
  77889. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77890. return "deviceOrientation";
  77891. };
  77892. return FreeCameraDeviceOrientationInput;
  77893. }());
  77894. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77895. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77896. })(BABYLON || (BABYLON = {}));
  77897. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77898. var BABYLON;
  77899. (function (BABYLON) {
  77900. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77901. function ArcRotateCameraVRDeviceOrientationInput() {
  77902. this.alphaCorrection = 1;
  77903. this.betaCorrection = 1;
  77904. this.gammaCorrection = 1;
  77905. this._alpha = 0;
  77906. this._gamma = 0;
  77907. this._dirty = false;
  77908. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77909. }
  77910. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77911. this.camera.attachControl(element, noPreventDefault);
  77912. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77913. };
  77914. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77915. if (evt.alpha !== null) {
  77916. this._alpha = +evt.alpha | 0;
  77917. }
  77918. if (evt.gamma !== null) {
  77919. this._gamma = +evt.gamma | 0;
  77920. }
  77921. this._dirty = true;
  77922. };
  77923. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77924. if (this._dirty) {
  77925. this._dirty = false;
  77926. if (this._gamma < 0) {
  77927. this._gamma = 180 + this._gamma;
  77928. }
  77929. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77930. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77931. }
  77932. };
  77933. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77934. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77935. };
  77936. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77937. return "ArcRotateCameraVRDeviceOrientationInput";
  77938. };
  77939. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77940. return "VRDeviceOrientation";
  77941. };
  77942. return ArcRotateCameraVRDeviceOrientationInput;
  77943. }());
  77944. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77945. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77946. })(BABYLON || (BABYLON = {}));
  77947. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77948. var BABYLON;
  77949. (function (BABYLON) {
  77950. var VRCameraMetrics = /** @class */ (function () {
  77951. function VRCameraMetrics() {
  77952. this.compensateDistortion = true;
  77953. }
  77954. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77955. get: function () {
  77956. return this.hResolution / (2 * this.vResolution);
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77962. get: function () {
  77963. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77964. },
  77965. enumerable: true,
  77966. configurable: true
  77967. });
  77968. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77969. get: function () {
  77970. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77971. var h = (4 * meters) / this.hScreenSize;
  77972. return BABYLON.Matrix.Translation(h, 0, 0);
  77973. },
  77974. enumerable: true,
  77975. configurable: true
  77976. });
  77977. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77978. get: function () {
  77979. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77980. var h = (4 * meters) / this.hScreenSize;
  77981. return BABYLON.Matrix.Translation(-h, 0, 0);
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77987. get: function () {
  77988. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77994. get: function () {
  77995. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77996. },
  77997. enumerable: true,
  77998. configurable: true
  77999. });
  78000. VRCameraMetrics.GetDefault = function () {
  78001. var result = new VRCameraMetrics();
  78002. result.hResolution = 1280;
  78003. result.vResolution = 800;
  78004. result.hScreenSize = 0.149759993;
  78005. result.vScreenSize = 0.0935999975;
  78006. result.vScreenCenter = 0.0467999987;
  78007. result.eyeToScreenDistance = 0.0410000011;
  78008. result.lensSeparationDistance = 0.0635000020;
  78009. result.interpupillaryDistance = 0.0640000030;
  78010. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  78011. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  78012. result.postProcessScaleFactor = 1.714605507808412;
  78013. result.lensCenterOffset = 0.151976421;
  78014. return result;
  78015. };
  78016. return VRCameraMetrics;
  78017. }());
  78018. BABYLON.VRCameraMetrics = VRCameraMetrics;
  78019. })(BABYLON || (BABYLON = {}));
  78020. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  78021. var BABYLON;
  78022. (function (BABYLON) {
  78023. /**
  78024. * This represents a WebVR camera.
  78025. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  78026. * @example http://doc.babylonjs.com/how_to/webvr_camera
  78027. */
  78028. var WebVRFreeCamera = /** @class */ (function (_super) {
  78029. __extends(WebVRFreeCamera, _super);
  78030. /**
  78031. * Instantiates a WebVRFreeCamera.
  78032. * @param name The name of the WebVRFreeCamera
  78033. * @param position The starting anchor position for the camera
  78034. * @param scene The scene the camera belongs to
  78035. * @param webVROptions a set of customizable options for the webVRCamera
  78036. */
  78037. function WebVRFreeCamera(name, position, scene, webVROptions) {
  78038. if (webVROptions === void 0) { webVROptions = {}; }
  78039. var _this = _super.call(this, name, position, scene) || this;
  78040. _this.webVROptions = webVROptions;
  78041. /**
  78042. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  78043. */
  78044. _this._vrDevice = null;
  78045. /**
  78046. * The rawPose of the vrDevice.
  78047. */
  78048. _this.rawPose = null;
  78049. _this._specsVersion = "1.1";
  78050. _this._attached = false;
  78051. _this._descendants = [];
  78052. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78053. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78054. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  78055. _this._standingMatrix = null;
  78056. /**
  78057. * Represents device position in babylon space.
  78058. */
  78059. _this.devicePosition = BABYLON.Vector3.Zero();
  78060. /**
  78061. * Represents device rotation in babylon space.
  78062. */
  78063. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  78064. /**
  78065. * The scale of the device to be used when translating from device space to babylon space.
  78066. */
  78067. _this.deviceScaleFactor = 1;
  78068. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78069. _this._worldToDevice = BABYLON.Matrix.Identity();
  78070. /**
  78071. * References to the webVR controllers for the vrDevice.
  78072. */
  78073. _this.controllers = [];
  78074. /**
  78075. * Emits an event when a controller is attached.
  78076. */
  78077. _this.onControllersAttachedObservable = new BABYLON.Observable();
  78078. /**
  78079. * Emits an event when a controller's mesh has been loaded;
  78080. */
  78081. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78082. /**
  78083. * If the rig cameras be used as parent instead of this camera.
  78084. */
  78085. _this.rigParenting = true;
  78086. _this._defaultHeight = undefined;
  78087. _this._workingVector = BABYLON.Vector3.Zero();
  78088. _this._oneVector = BABYLON.Vector3.One();
  78089. _this._workingMatrix = BABYLON.Matrix.Identity();
  78090. _this._cache.position = BABYLON.Vector3.Zero();
  78091. if (webVROptions.defaultHeight) {
  78092. _this._defaultHeight = webVROptions.defaultHeight;
  78093. _this.position.y = _this._defaultHeight;
  78094. }
  78095. _this.minZ = 0.1;
  78096. //legacy support - the compensation boolean was removed.
  78097. if (arguments.length === 5) {
  78098. _this.webVROptions = arguments[4];
  78099. }
  78100. // default webVR options
  78101. if (_this.webVROptions.trackPosition == undefined) {
  78102. _this.webVROptions.trackPosition = true;
  78103. }
  78104. if (_this.webVROptions.controllerMeshes == undefined) {
  78105. _this.webVROptions.controllerMeshes = true;
  78106. }
  78107. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78108. _this.webVROptions.defaultLightingOnControllers = true;
  78109. }
  78110. _this.rotationQuaternion = new BABYLON.Quaternion();
  78111. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78112. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78113. }
  78114. //enable VR
  78115. var engine = _this.getEngine();
  78116. _this._onVREnabled = function (success) { if (success) {
  78117. _this.initControllers();
  78118. } };
  78119. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78120. engine.initWebVR().add(function (event) {
  78121. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78122. return;
  78123. }
  78124. _this._vrDevice = event.vrDisplay;
  78125. //reset the rig parameters.
  78126. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78127. if (_this._attached) {
  78128. _this.getEngine().enableVR();
  78129. }
  78130. });
  78131. if (typeof (VRFrameData) !== "undefined")
  78132. _this._frameData = new VRFrameData();
  78133. /**
  78134. * The idea behind the following lines:
  78135. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78136. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78137. * the second will not show it correctly.
  78138. *
  78139. * To solve this - each object that has the camera as parent will be added to a protected array.
  78140. * When the rig camera renders, it will take this array and set all of those to be its children.
  78141. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78142. * Amazing!
  78143. */
  78144. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78145. if (camera.parent === _this && _this.rigParenting) {
  78146. _this._descendants = _this.getDescendants(true, function (n) {
  78147. // don't take the cameras or the controllers!
  78148. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78149. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78150. return !isController && !isRigCamera;
  78151. });
  78152. _this._descendants.forEach(function (node) {
  78153. node.parent = camera;
  78154. });
  78155. }
  78156. });
  78157. scene.onAfterCameraRenderObservable.add(function (camera) {
  78158. if (camera.parent === _this && _this.rigParenting) {
  78159. _this._descendants.forEach(function (node) {
  78160. node.parent = _this;
  78161. });
  78162. }
  78163. });
  78164. return _this;
  78165. }
  78166. /**
  78167. * Gets the device distance from the ground in meters.
  78168. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  78169. */
  78170. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78171. if (this._standingMatrix) {
  78172. // Add standing matrix offset to get real offset from ground in room
  78173. this._standingMatrix.getTranslationToRef(this._workingVector);
  78174. return this._deviceRoomPosition.y + this._workingVector.y;
  78175. }
  78176. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78177. return this._defaultHeight || 0;
  78178. };
  78179. /**
  78180. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78181. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78182. */
  78183. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78184. var _this = this;
  78185. if (callback === void 0) { callback = function (bool) { }; }
  78186. // Use standing matrix if available
  78187. this.getEngine().initWebVRAsync().then(function (result) {
  78188. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  78189. callback(false);
  78190. }
  78191. else {
  78192. _this._standingMatrix = new BABYLON.Matrix();
  78193. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78194. if (!_this.getScene().useRightHandedSystem) {
  78195. [2, 6, 8, 9, 14].forEach(function (num) {
  78196. if (_this._standingMatrix) {
  78197. _this._standingMatrix.m[num] *= -1;
  78198. }
  78199. });
  78200. }
  78201. callback(true);
  78202. }
  78203. });
  78204. };
  78205. /**
  78206. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78207. * @returns A promise with a boolean set to if the standing matrix is supported.
  78208. */
  78209. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  78210. var _this = this;
  78211. return new Promise(function (res, rej) {
  78212. _this.useStandingMatrix(function (supported) {
  78213. res(supported);
  78214. });
  78215. });
  78216. };
  78217. /**
  78218. * Disposes the camera
  78219. */
  78220. WebVRFreeCamera.prototype.dispose = function () {
  78221. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78222. _super.prototype.dispose.call(this);
  78223. };
  78224. /**
  78225. * Gets a vrController by name.
  78226. * @param name The name of the controller to retreive
  78227. * @returns the controller matching the name specified or null if not found
  78228. */
  78229. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78230. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78231. var gp = _a[_i];
  78232. if (gp.hand === name) {
  78233. return gp;
  78234. }
  78235. }
  78236. return null;
  78237. };
  78238. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78239. /**
  78240. * The controller corrisponding to the users left hand.
  78241. */
  78242. get: function () {
  78243. if (!this._leftController) {
  78244. this._leftController = this.getControllerByName("left");
  78245. }
  78246. return this._leftController;
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. ;
  78252. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78253. /**
  78254. * The controller corrisponding to the users right hand.
  78255. */
  78256. get: function () {
  78257. if (!this._rightController) {
  78258. this._rightController = this.getControllerByName("right");
  78259. }
  78260. return this._rightController;
  78261. },
  78262. enumerable: true,
  78263. configurable: true
  78264. });
  78265. ;
  78266. /**
  78267. * Casts a ray forward from the vrCamera's gaze.
  78268. * @param length Length of the ray (default: 100)
  78269. * @returns the ray corrisponding to the gaze
  78270. */
  78271. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78272. if (length === void 0) { length = 100; }
  78273. if (this.leftCamera) {
  78274. // Use left eye to avoid computation to compute center on every call
  78275. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78276. }
  78277. else {
  78278. return _super.prototype.getForwardRay.call(this, length);
  78279. }
  78280. };
  78281. /**
  78282. * Updates the camera based on device's frame data
  78283. */
  78284. WebVRFreeCamera.prototype._checkInputs = function () {
  78285. if (this._vrDevice && this._vrDevice.isPresenting) {
  78286. this._vrDevice.getFrameData(this._frameData);
  78287. this.updateFromDevice(this._frameData.pose);
  78288. }
  78289. _super.prototype._checkInputs.call(this);
  78290. };
  78291. /**
  78292. * Updates the poseControlled values based on the input device pose.
  78293. * @param poseData Pose coming from the device
  78294. */
  78295. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78296. if (poseData && poseData.orientation) {
  78297. this.rawPose = poseData;
  78298. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78299. if (this.getScene().useRightHandedSystem) {
  78300. this._deviceRoomRotationQuaternion.z *= -1;
  78301. this._deviceRoomRotationQuaternion.w *= -1;
  78302. }
  78303. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78304. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78305. if (this.getScene().useRightHandedSystem) {
  78306. this._deviceRoomPosition.z *= -1;
  78307. }
  78308. }
  78309. }
  78310. };
  78311. /**
  78312. * WebVR's attach control will start broadcasting frames to the device.
  78313. * Note that in certain browsers (chrome for example) this function must be called
  78314. * within a user-interaction callback. Example:
  78315. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78316. *
  78317. * @param element html element to attach the vrDevice to
  78318. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78319. */
  78320. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78321. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78322. this._attached = true;
  78323. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78324. if (this._vrDevice) {
  78325. this.getEngine().enableVR();
  78326. }
  78327. };
  78328. /**
  78329. * Detaches the camera from the html element and disables VR
  78330. *
  78331. * @param element html element to detach from
  78332. */
  78333. WebVRFreeCamera.prototype.detachControl = function (element) {
  78334. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78335. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78336. _super.prototype.detachControl.call(this, element);
  78337. this._attached = false;
  78338. this.getEngine().disableVR();
  78339. };
  78340. /**
  78341. * @returns the name of this class
  78342. */
  78343. WebVRFreeCamera.prototype.getClassName = function () {
  78344. return "WebVRFreeCamera";
  78345. };
  78346. /**
  78347. * Calls resetPose on the vrDisplay
  78348. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78349. */
  78350. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78351. //uses the vrDisplay's "resetPose()".
  78352. //pitch and roll won't be affected.
  78353. this._vrDevice.resetPose();
  78354. };
  78355. /**
  78356. * Updates the rig cameras (left and right eye)
  78357. */
  78358. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78359. var camLeft = this._rigCameras[0];
  78360. var camRight = this._rigCameras[1];
  78361. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78362. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78363. camLeft.position.copyFrom(this._deviceRoomPosition);
  78364. camRight.position.copyFrom(this._deviceRoomPosition);
  78365. };
  78366. /**
  78367. * Updates the cached values of the camera
  78368. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78369. */
  78370. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78371. var _this = this;
  78372. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78373. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78374. if (!this.updateCacheCalled) {
  78375. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78376. this.updateCacheCalled = true;
  78377. this.update();
  78378. }
  78379. // Set working vector to the device position in room space rotated by the new rotation
  78380. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78381. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78382. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78383. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78384. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78385. // Add translation from anchor position
  78386. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78387. this._workingVector.addInPlace(this.position);
  78388. this._workingVector.subtractInPlace(this._cache.position);
  78389. this._deviceToWorld.setTranslation(this._workingVector);
  78390. // Set an inverted matrix to be used when updating the camera
  78391. this._deviceToWorld.invertToRef(this._worldToDevice);
  78392. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78393. this.controllers.forEach(function (controller) {
  78394. controller._deviceToWorld = _this._deviceToWorld;
  78395. controller.update();
  78396. });
  78397. }
  78398. if (!ignoreParentClass) {
  78399. _super.prototype._updateCache.call(this);
  78400. }
  78401. this.updateCacheCalled = false;
  78402. };
  78403. /**
  78404. * Updates the current device position and rotation in the babylon world
  78405. */
  78406. WebVRFreeCamera.prototype.update = function () {
  78407. // Get current device position in babylon world
  78408. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78409. // Get current device rotation in babylon world
  78410. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78411. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78412. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78413. _super.prototype.update.call(this);
  78414. };
  78415. /**
  78416. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78417. * @returns an identity matrix
  78418. */
  78419. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78420. return BABYLON.Matrix.Identity();
  78421. };
  78422. /**
  78423. * This function is called by the two RIG cameras.
  78424. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78425. */
  78426. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78427. var _this = this;
  78428. //WebVR 1.1
  78429. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78430. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78431. if (!this.getScene().useRightHandedSystem) {
  78432. [2, 6, 8, 9, 14].forEach(function (num) {
  78433. _this._webvrViewMatrix.m[num] *= -1;
  78434. });
  78435. }
  78436. // update the camera rotation matrix
  78437. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78438. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78439. // Computing target and final matrix
  78440. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78441. var parentCamera = this._cameraRigParams["parentCamera"];
  78442. // should the view matrix be updated with scale and position offset?
  78443. if (parentCamera.deviceScaleFactor !== 1) {
  78444. this._webvrViewMatrix.invert();
  78445. // scale the position, if set
  78446. if (parentCamera.deviceScaleFactor) {
  78447. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78448. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78449. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78450. }
  78451. this._webvrViewMatrix.invert();
  78452. }
  78453. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78454. return this._webvrViewMatrix;
  78455. };
  78456. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78457. var _this = this;
  78458. var parentCamera = this.parent;
  78459. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78460. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78461. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78462. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78463. //babylon compatible matrix
  78464. if (!this.getScene().useRightHandedSystem) {
  78465. [8, 9, 10, 11].forEach(function (num) {
  78466. _this._projectionMatrix.m[num] *= -1;
  78467. });
  78468. }
  78469. return this._projectionMatrix;
  78470. };
  78471. /**
  78472. * Initializes the controllers and their meshes
  78473. */
  78474. WebVRFreeCamera.prototype.initControllers = function () {
  78475. var _this = this;
  78476. this.controllers = [];
  78477. var manager = this.getScene().gamepadManager;
  78478. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78479. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78480. var webVrController = gamepad;
  78481. if (webVrController.defaultModel) {
  78482. webVrController.defaultModel.setEnabled(false);
  78483. }
  78484. if (webVrController.hand === "right") {
  78485. _this._rightController = null;
  78486. }
  78487. if (webVrController.hand === "left") {
  78488. _this._rightController = null;
  78489. }
  78490. var controllerIndex = _this.controllers.indexOf(webVrController);
  78491. if (controllerIndex !== -1) {
  78492. _this.controllers.splice(controllerIndex, 1);
  78493. }
  78494. }
  78495. });
  78496. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78497. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78498. var webVrController_1 = gamepad;
  78499. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78500. if (_this.webVROptions.controllerMeshes) {
  78501. if (webVrController_1.defaultModel) {
  78502. webVrController_1.defaultModel.setEnabled(true);
  78503. }
  78504. else {
  78505. // Load the meshes
  78506. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78507. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78508. if (_this.webVROptions.defaultLightingOnControllers) {
  78509. if (!_this._lightOnControllers) {
  78510. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78511. }
  78512. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78513. var children = mesh.getChildren();
  78514. if (children.length !== 0) {
  78515. children.forEach(function (mesh) {
  78516. light.includedOnlyMeshes.push(mesh);
  78517. activateLightOnSubMeshes_1(mesh, light);
  78518. });
  78519. }
  78520. };
  78521. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78522. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78523. }
  78524. });
  78525. }
  78526. }
  78527. webVrController_1.attachToPoseControlledCamera(_this);
  78528. // since this is async - sanity check. Is the controller already stored?
  78529. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78530. //add to the controllers array
  78531. _this.controllers.push(webVrController_1);
  78532. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78533. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78534. // So we're overriding setting left & right manually to be sure
  78535. var firstViveWandDetected = false;
  78536. for (var i = 0; i < _this.controllers.length; i++) {
  78537. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78538. if (!firstViveWandDetected) {
  78539. firstViveWandDetected = true;
  78540. _this.controllers[i].hand = "left";
  78541. }
  78542. else {
  78543. _this.controllers[i].hand = "right";
  78544. }
  78545. }
  78546. }
  78547. //did we find enough controllers? Great! let the developer know.
  78548. if (_this.controllers.length >= 2) {
  78549. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78550. }
  78551. }
  78552. }
  78553. });
  78554. };
  78555. return WebVRFreeCamera;
  78556. }(BABYLON.FreeCamera));
  78557. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78558. })(BABYLON || (BABYLON = {}));
  78559. //# sourceMappingURL=babylon.webVRCamera.js.map
  78560. var BABYLON;
  78561. (function (BABYLON) {
  78562. // We're mainly based on the logic defined into the FreeCamera code
  78563. /**
  78564. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78565. * being tilted forward or back and left or right.
  78566. */
  78567. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78568. __extends(DeviceOrientationCamera, _super);
  78569. /**
  78570. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78571. * @param name The name of the camera
  78572. * @param position The start position camera
  78573. * @param scene The scene the camera belongs to
  78574. */
  78575. function DeviceOrientationCamera(name, position, scene) {
  78576. var _this = _super.call(this, name, position, scene) || this;
  78577. _this._quaternionCache = new BABYLON.Quaternion();
  78578. _this.inputs.addDeviceOrientation();
  78579. return _this;
  78580. }
  78581. /**
  78582. * Gets the current instance class name ("DeviceOrientationCamera").
  78583. * This helps avoiding instanceof at run time.
  78584. * @returns the class name
  78585. */
  78586. DeviceOrientationCamera.prototype.getClassName = function () {
  78587. return "DeviceOrientationCamera";
  78588. };
  78589. /**
  78590. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78591. */
  78592. DeviceOrientationCamera.prototype._checkInputs = function () {
  78593. _super.prototype._checkInputs.call(this);
  78594. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78595. if (this._initialQuaternion) {
  78596. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78597. }
  78598. };
  78599. /**
  78600. * Reset the camera to its default orientation on the specified axis only.
  78601. * @param axis The axis to reset
  78602. */
  78603. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78604. var _this = this;
  78605. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78606. //can only work if this camera has a rotation quaternion already.
  78607. if (!this.rotationQuaternion)
  78608. return;
  78609. if (!this._initialQuaternion) {
  78610. this._initialQuaternion = new BABYLON.Quaternion();
  78611. }
  78612. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78613. ['x', 'y', 'z'].forEach(function (axisName) {
  78614. if (!axis[axisName]) {
  78615. _this._initialQuaternion[axisName] = 0;
  78616. }
  78617. else {
  78618. _this._initialQuaternion[axisName] *= -1;
  78619. }
  78620. });
  78621. this._initialQuaternion.normalize();
  78622. //force rotation update
  78623. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78624. };
  78625. return DeviceOrientationCamera;
  78626. }(BABYLON.FreeCamera));
  78627. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78628. })(BABYLON || (BABYLON = {}));
  78629. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78630. var BABYLON;
  78631. (function (BABYLON) {
  78632. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78633. __extends(VRDeviceOrientationFreeCamera, _super);
  78634. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78635. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78636. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78637. var _this = _super.call(this, name, position, scene) || this;
  78638. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78639. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78640. return _this;
  78641. }
  78642. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78643. return "VRDeviceOrientationFreeCamera";
  78644. };
  78645. return VRDeviceOrientationFreeCamera;
  78646. }(BABYLON.DeviceOrientationCamera));
  78647. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78648. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78649. __extends(VRDeviceOrientationGamepadCamera, _super);
  78650. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78651. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78652. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78653. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78654. _this.inputs.addGamepad();
  78655. return _this;
  78656. }
  78657. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78658. return "VRDeviceOrientationGamepadCamera";
  78659. };
  78660. return VRDeviceOrientationGamepadCamera;
  78661. }(VRDeviceOrientationFreeCamera));
  78662. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78663. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78664. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78665. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78666. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78667. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78668. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78669. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78670. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78671. _this.inputs.addVRDeviceOrientation();
  78672. return _this;
  78673. }
  78674. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78675. return "VRDeviceOrientationArcRotateCamera";
  78676. };
  78677. return VRDeviceOrientationArcRotateCamera;
  78678. }(BABYLON.ArcRotateCamera));
  78679. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78680. })(BABYLON || (BABYLON = {}));
  78681. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78682. var BABYLON;
  78683. (function (BABYLON) {
  78684. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78685. __extends(AnaglyphFreeCamera, _super);
  78686. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78687. var _this = _super.call(this, name, position, scene) || this;
  78688. _this.interaxialDistance = interaxialDistance;
  78689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78690. return _this;
  78691. }
  78692. AnaglyphFreeCamera.prototype.getClassName = function () {
  78693. return "AnaglyphFreeCamera";
  78694. };
  78695. return AnaglyphFreeCamera;
  78696. }(BABYLON.FreeCamera));
  78697. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78698. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78699. __extends(AnaglyphArcRotateCamera, _super);
  78700. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78701. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78702. _this.interaxialDistance = interaxialDistance;
  78703. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78704. return _this;
  78705. }
  78706. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78707. return "AnaglyphArcRotateCamera";
  78708. };
  78709. return AnaglyphArcRotateCamera;
  78710. }(BABYLON.ArcRotateCamera));
  78711. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78712. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78713. __extends(AnaglyphGamepadCamera, _super);
  78714. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78715. var _this = _super.call(this, name, position, scene) || this;
  78716. _this.interaxialDistance = interaxialDistance;
  78717. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78718. return _this;
  78719. }
  78720. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78721. return "AnaglyphGamepadCamera";
  78722. };
  78723. return AnaglyphGamepadCamera;
  78724. }(BABYLON.GamepadCamera));
  78725. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78726. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78727. __extends(AnaglyphUniversalCamera, _super);
  78728. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78729. var _this = _super.call(this, name, position, scene) || this;
  78730. _this.interaxialDistance = interaxialDistance;
  78731. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78732. return _this;
  78733. }
  78734. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78735. return "AnaglyphUniversalCamera";
  78736. };
  78737. return AnaglyphUniversalCamera;
  78738. }(BABYLON.UniversalCamera));
  78739. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78740. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78741. __extends(StereoscopicFreeCamera, _super);
  78742. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78743. var _this = _super.call(this, name, position, scene) || this;
  78744. _this.interaxialDistance = interaxialDistance;
  78745. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78746. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78747. return _this;
  78748. }
  78749. StereoscopicFreeCamera.prototype.getClassName = function () {
  78750. return "StereoscopicFreeCamera";
  78751. };
  78752. return StereoscopicFreeCamera;
  78753. }(BABYLON.FreeCamera));
  78754. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78755. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78756. __extends(StereoscopicArcRotateCamera, _super);
  78757. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78758. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78759. _this.interaxialDistance = interaxialDistance;
  78760. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78761. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78762. return _this;
  78763. }
  78764. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78765. return "StereoscopicArcRotateCamera";
  78766. };
  78767. return StereoscopicArcRotateCamera;
  78768. }(BABYLON.ArcRotateCamera));
  78769. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78770. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78771. __extends(StereoscopicGamepadCamera, _super);
  78772. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78773. var _this = _super.call(this, name, position, scene) || this;
  78774. _this.interaxialDistance = interaxialDistance;
  78775. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78776. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78777. return _this;
  78778. }
  78779. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78780. return "StereoscopicGamepadCamera";
  78781. };
  78782. return StereoscopicGamepadCamera;
  78783. }(BABYLON.GamepadCamera));
  78784. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78785. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78786. __extends(StereoscopicUniversalCamera, _super);
  78787. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78788. var _this = _super.call(this, name, position, scene) || this;
  78789. _this.interaxialDistance = interaxialDistance;
  78790. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78791. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78792. return _this;
  78793. }
  78794. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78795. return "StereoscopicUniversalCamera";
  78796. };
  78797. return StereoscopicUniversalCamera;
  78798. }(BABYLON.UniversalCamera));
  78799. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78800. })(BABYLON || (BABYLON = {}));
  78801. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78802. var BABYLON;
  78803. (function (BABYLON) {
  78804. /**
  78805. * Helps to quickly add VR support to an existing scene.
  78806. * See http://doc.babylonjs.com/how_to/webvr_helper
  78807. */
  78808. var VRExperienceHelper = /** @class */ (function () {
  78809. /**
  78810. * Instantiates a VRExperienceHelper.
  78811. * Helps to quickly add VR support to an existing scene.
  78812. * @param scene The scene the VRExperienceHelper belongs to.
  78813. * @param webVROptions Options to modify the vr experience helper's behavior.
  78814. */
  78815. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78816. if (webVROptions === void 0) { webVROptions = {}; }
  78817. var _this = this;
  78818. this.webVROptions = webVROptions;
  78819. // Can the system support WebVR, even if a headset isn't plugged in?
  78820. this._webVRsupported = false;
  78821. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78822. this._webVRready = false;
  78823. // Are we waiting for the requestPresent callback to complete?
  78824. this._webVRrequesting = false;
  78825. // Are we presenting to the headset right now?
  78826. this._webVRpresenting = false;
  78827. // Are we presenting in the fullscreen fallback?
  78828. this._fullscreenVRpresenting = false;
  78829. /**
  78830. * Observable raised when entering VR.
  78831. */
  78832. this.onEnteringVRObservable = new BABYLON.Observable();
  78833. /**
  78834. * Observable raised when exiting VR.
  78835. */
  78836. this.onExitingVRObservable = new BABYLON.Observable();
  78837. /**
  78838. * Observable raised when controller mesh is loaded.
  78839. */
  78840. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78841. this._useCustomVRButton = false;
  78842. this._teleportationRequested = false;
  78843. this._teleportationEnabledOnLeftController = false;
  78844. this._teleportationEnabledOnRightController = false;
  78845. this._interactionsEnabledOnLeftController = false;
  78846. this._interactionsEnabledOnRightController = false;
  78847. this._leftControllerReady = false;
  78848. this._rightControllerReady = false;
  78849. this._floorMeshesCollection = [];
  78850. this._teleportationAllowed = false;
  78851. this._rotationAllowed = true;
  78852. this._teleportationRequestInitiated = false;
  78853. this._teleportationBackRequestInitiated = false;
  78854. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78855. this._rotationRightAsked = false;
  78856. this._rotationLeftAsked = false;
  78857. this._isDefaultTeleportationTarget = true;
  78858. this._teleportationFillColor = "#444444";
  78859. this._teleportationBorderColor = "#FFFFFF";
  78860. this._rotationAngle = 0;
  78861. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78862. this._padSensibilityUp = 0.65;
  78863. this._padSensibilityDown = 0.35;
  78864. /**
  78865. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78866. */
  78867. this.onNewMeshSelected = new BABYLON.Observable();
  78868. /**
  78869. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78870. */
  78871. this.onNewMeshPicked = new BABYLON.Observable();
  78872. /**
  78873. * Observable raised before camera teleportation
  78874. */
  78875. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78876. /**
  78877. * Observable raised after camera teleportation
  78878. */
  78879. this.onAfterCameraTeleport = new BABYLON.Observable();
  78880. /**
  78881. * Observable raised when current selected mesh gets unselected
  78882. */
  78883. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78884. /**
  78885. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78886. */
  78887. this.teleportationEnabled = true;
  78888. this._pointerDownOnMeshAsked = false;
  78889. this._isActionableMesh = false;
  78890. this._teleportationInitialized = false;
  78891. this._interactionsEnabled = false;
  78892. this._interactionsRequested = false;
  78893. this._displayGaze = true;
  78894. this._displayLaserPointer = true;
  78895. this._dpadPressed = true;
  78896. this._onResize = function () {
  78897. _this.moveButtonToBottomRight();
  78898. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78899. _this.exitVR();
  78900. }
  78901. };
  78902. this._onFullscreenChange = function () {
  78903. if (document.fullscreen !== undefined) {
  78904. _this._fullscreenVRpresenting = document.fullscreen;
  78905. }
  78906. else if (document.mozFullScreen !== undefined) {
  78907. _this._fullscreenVRpresenting = document.mozFullScreen;
  78908. }
  78909. else if (document.webkitIsFullScreen !== undefined) {
  78910. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78911. }
  78912. else if (document.msIsFullScreen !== undefined) {
  78913. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78914. }
  78915. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78916. _this.exitVR();
  78917. if (!_this._useCustomVRButton) {
  78918. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78919. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78920. }
  78921. }
  78922. };
  78923. this.beforeRender = function () {
  78924. _this._castRayAndSelectObject();
  78925. };
  78926. this._onNewGamepadConnected = function (gamepad) {
  78927. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78928. if (gamepad.leftStick) {
  78929. gamepad.onleftstickchanged(function (stickValues) {
  78930. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78931. // Listening to classic/xbox gamepad only if no VR controller is active
  78932. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78933. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78934. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78935. _this._checkTeleportWithRay(stickValues);
  78936. _this._checkTeleportBackwards(stickValues);
  78937. }
  78938. }
  78939. });
  78940. }
  78941. if (gamepad.rightStick) {
  78942. gamepad.onrightstickchanged(function (stickValues) {
  78943. if (_this._teleportationInitialized) {
  78944. _this._checkRotate(stickValues);
  78945. }
  78946. });
  78947. }
  78948. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78949. gamepad.onbuttondown(function (buttonPressed) {
  78950. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78951. _this._selectionPointerDown();
  78952. }
  78953. });
  78954. gamepad.onbuttonup(function (buttonPressed) {
  78955. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78956. _this._selectionPointerUp();
  78957. }
  78958. });
  78959. }
  78960. }
  78961. else {
  78962. var webVRController = gamepad;
  78963. _this._tryEnableInteractionOnController(webVRController);
  78964. }
  78965. };
  78966. // 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
  78967. this._tryEnableInteractionOnController = function (webVRController) {
  78968. if (webVRController.hand === "left") {
  78969. _this._leftControllerReady = true;
  78970. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78971. _this._enableInteractionOnController(webVRController);
  78972. }
  78973. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78974. _this._enableTeleportationOnController(webVRController);
  78975. }
  78976. }
  78977. if (webVRController.hand === "right") {
  78978. _this._rightControllerReady = true;
  78979. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78980. _this._enableInteractionOnController(webVRController);
  78981. }
  78982. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78983. _this._enableTeleportationOnController(webVRController);
  78984. }
  78985. }
  78986. };
  78987. this._onNewGamepadDisconnected = function (gamepad) {
  78988. if (gamepad instanceof BABYLON.WebVRController) {
  78989. if (gamepad.hand === "left") {
  78990. _this._interactionsEnabledOnLeftController = false;
  78991. _this._teleportationEnabledOnLeftController = false;
  78992. _this._leftControllerReady = false;
  78993. if (_this._leftLaserPointer) {
  78994. _this._leftLaserPointer.dispose();
  78995. }
  78996. }
  78997. if (gamepad.hand === "right") {
  78998. _this._interactionsEnabledOnRightController = false;
  78999. _this._teleportationEnabledOnRightController = false;
  79000. _this._rightControllerReady = false;
  79001. if (_this._rightLaserPointer) {
  79002. _this._rightLaserPointer.dispose();
  79003. }
  79004. }
  79005. }
  79006. };
  79007. this._workingVector = BABYLON.Vector3.Zero();
  79008. this._workingQuaternion = BABYLON.Quaternion.Identity();
  79009. this._workingMatrix = BABYLON.Matrix.Identity();
  79010. this._scene = scene;
  79011. this._canvas = scene.getEngine().getRenderingCanvas();
  79012. // Parse options
  79013. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  79014. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  79015. }
  79016. if (webVROptions.createDeviceOrientationCamera === undefined) {
  79017. webVROptions.createDeviceOrientationCamera = true;
  79018. }
  79019. if (webVROptions.defaultHeight === undefined) {
  79020. webVROptions.defaultHeight = 1.7;
  79021. }
  79022. if (webVROptions.useCustomVRButton) {
  79023. this._useCustomVRButton = true;
  79024. if (webVROptions.customVRButton) {
  79025. this._btnVR = webVROptions.customVRButton;
  79026. }
  79027. }
  79028. if (webVROptions.rayLength) {
  79029. this._rayLength = webVROptions.rayLength;
  79030. }
  79031. this._defaultHeight = webVROptions.defaultHeight;
  79032. // Set position
  79033. if (this._scene.activeCamera) {
  79034. this._position = this._scene.activeCamera.position.clone();
  79035. }
  79036. else {
  79037. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  79038. }
  79039. // Set non-vr camera
  79040. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  79041. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  79042. // Copy data from existing camera
  79043. if (this._scene.activeCamera) {
  79044. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  79045. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  79046. // Set rotation from previous camera
  79047. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  79048. var targetCamera = this._scene.activeCamera;
  79049. if (targetCamera.rotationQuaternion) {
  79050. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  79051. }
  79052. else {
  79053. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  79054. }
  79055. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  79056. }
  79057. }
  79058. this._scene.activeCamera = this._deviceOrientationCamera;
  79059. if (this._canvas) {
  79060. this._scene.activeCamera.attachControl(this._canvas);
  79061. }
  79062. }
  79063. else {
  79064. this._existingCamera = this._scene.activeCamera;
  79065. }
  79066. // Create VR cameras
  79067. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79068. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  79069. }
  79070. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  79071. this._webVRCamera.useStandingMatrix();
  79072. // Create default button
  79073. if (!this._useCustomVRButton) {
  79074. this._btnVR = document.createElement("BUTTON");
  79075. this._btnVR.className = "babylonVRicon";
  79076. this._btnVR.id = "babylonVRiconbtn";
  79077. this._btnVR.title = "Click to switch to VR";
  79078. 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) }";
  79079. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  79080. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  79081. // css += ".babylonVRicon.vrdisplaysupported { }";
  79082. // css += ".babylonVRicon.vrdisplayready { }";
  79083. // css += ".babylonVRicon.vrdisplayrequesting { }";
  79084. var style = document.createElement('style');
  79085. style.appendChild(document.createTextNode(css));
  79086. document.getElementsByTagName('head')[0].appendChild(style);
  79087. this.moveButtonToBottomRight();
  79088. }
  79089. // VR button click event
  79090. if (this._btnVR) {
  79091. this._btnVR.addEventListener("click", function () {
  79092. if (!_this.isInVRMode) {
  79093. _this.enterVR();
  79094. }
  79095. else {
  79096. _this.exitVR();
  79097. }
  79098. });
  79099. }
  79100. // Window events
  79101. window.addEventListener("resize", this._onResize);
  79102. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79103. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79104. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79105. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79106. // Display vr button when headset is connected
  79107. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79108. this.displayVRButton();
  79109. }
  79110. else {
  79111. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79112. if (e.vrDisplay) {
  79113. _this.displayVRButton();
  79114. }
  79115. });
  79116. }
  79117. // Exiting VR mode using 'ESC' key on desktop
  79118. this._onKeyDown = function (event) {
  79119. if (event.keyCode === 27 && _this.isInVRMode) {
  79120. _this.exitVR();
  79121. }
  79122. };
  79123. document.addEventListener("keydown", this._onKeyDown);
  79124. // Exiting VR mode double tapping the touch screen
  79125. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79126. if (_this.isInVRMode) {
  79127. _this.exitVR();
  79128. if (_this._fullscreenVRpresenting) {
  79129. _this._scene.getEngine().switchFullscreen(true);
  79130. }
  79131. }
  79132. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79133. // Listen for WebVR display changes
  79134. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79135. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79136. this._onVRRequestPresentStart = function () {
  79137. _this._webVRrequesting = true;
  79138. _this.updateButtonVisibility();
  79139. };
  79140. this._onVRRequestPresentComplete = function (success) {
  79141. _this._webVRrequesting = false;
  79142. _this.updateButtonVisibility();
  79143. };
  79144. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  79145. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  79146. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  79147. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79148. scene.onDisposeObservable.add(function () {
  79149. _this.dispose();
  79150. });
  79151. // Gamepad connection events
  79152. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  79153. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  79154. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  79155. this.updateButtonVisibility();
  79156. //create easing functions
  79157. this._circleEase = new BABYLON.CircleEase();
  79158. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79159. }
  79160. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  79161. /** Return this.onEnteringVRObservable
  79162. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  79163. */
  79164. get: function () {
  79165. return this.onEnteringVRObservable;
  79166. },
  79167. enumerable: true,
  79168. configurable: true
  79169. });
  79170. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  79171. /** Return this.onExitingVRObservable
  79172. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  79173. */
  79174. get: function () {
  79175. return this.onExitingVRObservable;
  79176. },
  79177. enumerable: true,
  79178. configurable: true
  79179. });
  79180. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  79181. /** Return this.onControllerMeshLoadedObservable
  79182. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  79183. */
  79184. get: function () {
  79185. return this.onControllerMeshLoadedObservable;
  79186. },
  79187. enumerable: true,
  79188. configurable: true
  79189. });
  79190. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  79191. /**
  79192. * The mesh used to display where the user is going to teleport.
  79193. */
  79194. get: function () {
  79195. return this._teleportationTarget;
  79196. },
  79197. /**
  79198. * Sets the mesh to be used to display where the user is going to teleport.
  79199. */
  79200. set: function (value) {
  79201. if (value) {
  79202. value.name = "teleportationTarget";
  79203. this._isDefaultTeleportationTarget = false;
  79204. this._teleportationTarget = value;
  79205. }
  79206. },
  79207. enumerable: true,
  79208. configurable: true
  79209. });
  79210. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79211. /**
  79212. * The mesh used to display where the user is selecting,
  79213. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  79214. * See http://doc.babylonjs.com/resources/baking_transformations
  79215. */
  79216. get: function () {
  79217. return this._gazeTracker;
  79218. },
  79219. set: function (value) {
  79220. if (value) {
  79221. this._gazeTracker = value;
  79222. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79223. this._gazeTracker.isPickable = false;
  79224. this._gazeTracker.isVisible = false;
  79225. }
  79226. },
  79227. enumerable: true,
  79228. configurable: true
  79229. });
  79230. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79231. /**
  79232. * If the ray of the gaze should be displayed.
  79233. */
  79234. get: function () {
  79235. return this._displayGaze;
  79236. },
  79237. /**
  79238. * Sets if the ray of the gaze should be displayed.
  79239. */
  79240. set: function (value) {
  79241. this._displayGaze = value;
  79242. if (!value) {
  79243. this._gazeTracker.isVisible = false;
  79244. }
  79245. },
  79246. enumerable: true,
  79247. configurable: true
  79248. });
  79249. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79250. /**
  79251. * If the ray of the LaserPointer should be displayed.
  79252. */
  79253. get: function () {
  79254. return this._displayLaserPointer;
  79255. },
  79256. /**
  79257. * Sets if the ray of the LaserPointer should be displayed.
  79258. */
  79259. set: function (value) {
  79260. this._displayLaserPointer = value;
  79261. if (!value) {
  79262. if (this._rightLaserPointer) {
  79263. this._rightLaserPointer.isVisible = false;
  79264. }
  79265. if (this._leftLaserPointer) {
  79266. this._leftLaserPointer.isVisible = false;
  79267. }
  79268. }
  79269. else {
  79270. if (this._rightLaserPointer) {
  79271. this._rightLaserPointer.isVisible = true;
  79272. }
  79273. else if (this._leftLaserPointer) {
  79274. this._leftLaserPointer.isVisible = true;
  79275. }
  79276. }
  79277. },
  79278. enumerable: true,
  79279. configurable: true
  79280. });
  79281. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79282. /**
  79283. * The deviceOrientationCamera used as the camera when not in VR.
  79284. */
  79285. get: function () {
  79286. return this._deviceOrientationCamera;
  79287. },
  79288. enumerable: true,
  79289. configurable: true
  79290. });
  79291. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79292. /**
  79293. * Based on the current WebVR support, returns the current VR camera used.
  79294. */
  79295. get: function () {
  79296. if (this._webVRready) {
  79297. return this._webVRCamera;
  79298. }
  79299. else {
  79300. return this._scene.activeCamera;
  79301. }
  79302. },
  79303. enumerable: true,
  79304. configurable: true
  79305. });
  79306. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79307. /**
  79308. * The webVRCamera which is used when in VR.
  79309. */
  79310. get: function () {
  79311. return this._webVRCamera;
  79312. },
  79313. enumerable: true,
  79314. configurable: true
  79315. });
  79316. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79317. /**
  79318. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79319. */
  79320. get: function () {
  79321. return this._vrDeviceOrientationCamera;
  79322. },
  79323. enumerable: true,
  79324. configurable: true
  79325. });
  79326. // Raised when one of the controller has loaded successfully its associated default mesh
  79327. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79328. this._tryEnableInteractionOnController(webVRController);
  79329. try {
  79330. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79331. }
  79332. catch (err) {
  79333. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79334. }
  79335. };
  79336. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79337. /**
  79338. * Gets a value indicating if we are currently in VR mode.
  79339. */
  79340. get: function () {
  79341. return this._webVRpresenting || this._fullscreenVRpresenting;
  79342. },
  79343. enumerable: true,
  79344. configurable: true
  79345. });
  79346. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79347. var vrDisplay = this._scene.getEngine().getVRDevice();
  79348. if (vrDisplay) {
  79349. var wasPresenting = this._webVRpresenting;
  79350. // A VR display is connected
  79351. this._webVRpresenting = vrDisplay.isPresenting;
  79352. if (wasPresenting && !this._webVRpresenting)
  79353. this.exitVR();
  79354. }
  79355. else {
  79356. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79357. }
  79358. this.updateButtonVisibility();
  79359. };
  79360. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79361. this._webVRsupported = eventArgs.vrSupported;
  79362. this._webVRready = !!eventArgs.vrDisplay;
  79363. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79364. this.updateButtonVisibility();
  79365. };
  79366. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79367. if (this._canvas && !this._useCustomVRButton) {
  79368. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79369. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79370. }
  79371. };
  79372. VRExperienceHelper.prototype.displayVRButton = function () {
  79373. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79374. document.body.appendChild(this._btnVR);
  79375. this._btnVRDisplayed = true;
  79376. }
  79377. };
  79378. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79379. if (!this._btnVR || this._useCustomVRButton) {
  79380. return;
  79381. }
  79382. this._btnVR.className = "babylonVRicon";
  79383. if (this.isInVRMode) {
  79384. this._btnVR.className += " vrdisplaypresenting";
  79385. }
  79386. else {
  79387. if (this._webVRready)
  79388. this._btnVR.className += " vrdisplayready";
  79389. if (this._webVRsupported)
  79390. this._btnVR.className += " vrdisplaysupported";
  79391. if (this._webVRrequesting)
  79392. this._btnVR.className += " vrdisplayrequesting";
  79393. }
  79394. };
  79395. /**
  79396. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79397. * Otherwise, will use the fullscreen API.
  79398. */
  79399. VRExperienceHelper.prototype.enterVR = function () {
  79400. if (this.onEnteringVRObservable) {
  79401. try {
  79402. this.onEnteringVRObservable.notifyObservers(this);
  79403. }
  79404. catch (err) {
  79405. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79406. }
  79407. }
  79408. if (this._scene.activeCamera) {
  79409. this._position = this._scene.activeCamera.position.clone();
  79410. // make sure that we return to the last active camera
  79411. this._existingCamera = this._scene.activeCamera;
  79412. }
  79413. if (this._webVRrequesting)
  79414. return;
  79415. // If WebVR is supported and a headset is connected
  79416. if (this._webVRready) {
  79417. if (!this._webVRpresenting) {
  79418. this._webVRCamera.position = this._position;
  79419. this._scene.activeCamera = this._webVRCamera;
  79420. }
  79421. }
  79422. else if (this._vrDeviceOrientationCamera) {
  79423. this._vrDeviceOrientationCamera.position = this._position;
  79424. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79425. this._scene.getEngine().switchFullscreen(true);
  79426. this.updateButtonVisibility();
  79427. }
  79428. if (this._scene.activeCamera && this._canvas) {
  79429. this._scene.activeCamera.attachControl(this._canvas);
  79430. }
  79431. if (this._interactionsEnabled) {
  79432. this._scene.registerBeforeRender(this.beforeRender);
  79433. }
  79434. };
  79435. /**
  79436. * Attempt to exit VR, or fullscreen.
  79437. */
  79438. VRExperienceHelper.prototype.exitVR = function () {
  79439. if (this.onExitingVRObservable) {
  79440. try {
  79441. this.onExitingVRObservable.notifyObservers(this);
  79442. }
  79443. catch (err) {
  79444. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79445. }
  79446. }
  79447. if (this._webVRpresenting) {
  79448. this._scene.getEngine().disableVR();
  79449. }
  79450. if (this._scene.activeCamera) {
  79451. this._position = this._scene.activeCamera.position.clone();
  79452. }
  79453. if (this._deviceOrientationCamera) {
  79454. this._deviceOrientationCamera.position = this._position;
  79455. this._scene.activeCamera = this._deviceOrientationCamera;
  79456. if (this._canvas) {
  79457. this._scene.activeCamera.attachControl(this._canvas);
  79458. }
  79459. }
  79460. else if (this._existingCamera) {
  79461. this._existingCamera.position = this._position;
  79462. this._scene.activeCamera = this._existingCamera;
  79463. }
  79464. this.updateButtonVisibility();
  79465. if (this._interactionsEnabled) {
  79466. this._scene.unregisterBeforeRender(this.beforeRender);
  79467. }
  79468. };
  79469. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79470. /**
  79471. * The position of the vr experience helper.
  79472. */
  79473. get: function () {
  79474. return this._position;
  79475. },
  79476. /**
  79477. * Sets the position of the vr experience helper.
  79478. */
  79479. set: function (value) {
  79480. this._position = value;
  79481. if (this._scene.activeCamera) {
  79482. this._scene.activeCamera.position = value;
  79483. }
  79484. },
  79485. enumerable: true,
  79486. configurable: true
  79487. });
  79488. /**
  79489. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79490. */
  79491. VRExperienceHelper.prototype.enableInteractions = function () {
  79492. var _this = this;
  79493. if (!this._interactionsEnabled) {
  79494. this._interactionsRequested = true;
  79495. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79496. this._enableInteractionOnController(this._webVRCamera.leftController);
  79497. }
  79498. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79499. this._enableInteractionOnController(this._webVRCamera.rightController);
  79500. }
  79501. if (!this._gazeTracker) {
  79502. this._createGazeTracker();
  79503. }
  79504. this.raySelectionPredicate = function (mesh) {
  79505. return mesh.isVisible;
  79506. };
  79507. this.meshSelectionPredicate = function (mesh) {
  79508. return true;
  79509. };
  79510. this._raySelectionPredicate = function (mesh) {
  79511. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79512. && mesh.name.indexOf("teleportationTarget") === -1
  79513. && mesh.name.indexOf("torusTeleportation") === -1
  79514. && mesh.name.indexOf("laserPointer") === -1)) {
  79515. return _this.raySelectionPredicate(mesh);
  79516. }
  79517. return false;
  79518. };
  79519. this._interactionsEnabled = true;
  79520. }
  79521. };
  79522. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79523. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79524. if (this._floorMeshesCollection[i].id === mesh.id) {
  79525. return true;
  79526. }
  79527. }
  79528. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79529. return true;
  79530. }
  79531. return false;
  79532. };
  79533. /**
  79534. * Adds a floor mesh to be used for teleportation.
  79535. * @param floorMesh the mesh to be used for teleportation.
  79536. */
  79537. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79538. if (!this._floorMeshesCollection) {
  79539. return;
  79540. }
  79541. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79542. return;
  79543. }
  79544. this._floorMeshesCollection.push(floorMesh);
  79545. };
  79546. /**
  79547. * Removes a floor mesh from being used for teleportation.
  79548. * @param floorMesh the mesh to be removed.
  79549. */
  79550. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79551. if (!this._floorMeshesCollection) {
  79552. return;
  79553. }
  79554. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79555. if (meshIndex !== -1) {
  79556. this._floorMeshesCollection.splice(meshIndex, 1);
  79557. }
  79558. };
  79559. /**
  79560. * Enables interactions and teleportation using the VR controllers and gaze.
  79561. * @param vrTeleportationOptions options to modify teleportation behavior.
  79562. */
  79563. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79564. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79565. if (!this._teleportationInitialized) {
  79566. this._teleportationRequested = true;
  79567. this.enableInteractions();
  79568. if (vrTeleportationOptions.floorMeshName) {
  79569. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79570. }
  79571. if (vrTeleportationOptions.floorMeshes) {
  79572. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79573. }
  79574. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79575. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79576. }
  79577. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79578. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79579. }
  79580. // Creates an image processing post process for the vignette not relying
  79581. // on the main scene configuration for image processing to reduce setup and spaces
  79582. // (gamma/linear) conflicts.
  79583. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79584. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79585. imageProcessingConfiguration.vignetteEnabled = true;
  79586. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79587. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79588. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79589. this._teleportationInitialized = true;
  79590. if (this._isDefaultTeleportationTarget) {
  79591. this._createTeleportationCircles();
  79592. }
  79593. }
  79594. };
  79595. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79596. var _this = this;
  79597. var controllerMesh = webVRController.mesh;
  79598. if (controllerMesh) {
  79599. var makeNotPick = function (root) {
  79600. root.name += " laserPointer";
  79601. root.getChildMeshes().forEach(function (c) {
  79602. makeNotPick(c);
  79603. });
  79604. };
  79605. makeNotPick(controllerMesh);
  79606. var childMeshes = controllerMesh.getChildMeshes();
  79607. for (var i = 0; i < childMeshes.length; i++) {
  79608. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79609. controllerMesh = childMeshes[i];
  79610. break;
  79611. }
  79612. }
  79613. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79614. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79615. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79616. laserPointerMaterial.alpha = 0.6;
  79617. laserPointer.material = laserPointerMaterial;
  79618. laserPointer.rotation.x = Math.PI / 2;
  79619. laserPointer.parent = controllerMesh;
  79620. laserPointer.position.z = -0.5;
  79621. laserPointer.isVisible = false;
  79622. if (webVRController.hand === "left") {
  79623. this._leftLaserPointer = laserPointer;
  79624. this._interactionsEnabledOnLeftController = true;
  79625. if (!this._rightLaserPointer) {
  79626. this._leftLaserPointer.isVisible = true;
  79627. }
  79628. }
  79629. else {
  79630. this._rightLaserPointer = laserPointer;
  79631. this._interactionsEnabledOnRightController = true;
  79632. if (!this._leftLaserPointer) {
  79633. this._rightLaserPointer.isVisible = true;
  79634. }
  79635. }
  79636. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79637. // Enabling / disabling laserPointer
  79638. if (_this._displayLaserPointer && stateObject.value === 1) {
  79639. laserPointer.isVisible = !laserPointer.isVisible;
  79640. // Laser pointer can only be active on left or right, not both at the same time
  79641. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79642. _this._rightLaserPointer.isVisible = false;
  79643. }
  79644. else if (_this._leftLaserPointer) {
  79645. _this._leftLaserPointer.isVisible = false;
  79646. }
  79647. }
  79648. });
  79649. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79650. if (!_this._pointerDownOnMeshAsked) {
  79651. if (stateObject.value > _this._padSensibilityUp) {
  79652. _this._selectionPointerDown();
  79653. }
  79654. }
  79655. else if (stateObject.value < _this._padSensibilityDown) {
  79656. _this._selectionPointerUp();
  79657. }
  79658. });
  79659. }
  79660. };
  79661. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79662. if (webVRController === void 0) { webVRController = null; }
  79663. if (!this._teleportationRequestInitiated) {
  79664. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79665. if (webVRController) {
  79666. // If laser pointer wasn't enabled yet
  79667. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79668. this._leftLaserPointer.isVisible = true;
  79669. if (this._rightLaserPointer) {
  79670. this._rightLaserPointer.isVisible = false;
  79671. }
  79672. }
  79673. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79674. this._rightLaserPointer.isVisible = true;
  79675. if (this._leftLaserPointer) {
  79676. this._leftLaserPointer.isVisible = false;
  79677. }
  79678. }
  79679. }
  79680. this._teleportationRequestInitiated = true;
  79681. }
  79682. }
  79683. else {
  79684. // Listening to the proper controller values changes to confirm teleportation
  79685. if (webVRController == null
  79686. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79687. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79688. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79689. if (this._teleportationAllowed) {
  79690. this._teleportationAllowed = false;
  79691. this._teleportCamera();
  79692. }
  79693. this._teleportationRequestInitiated = false;
  79694. }
  79695. }
  79696. }
  79697. };
  79698. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79699. this._pointerDownOnMeshAsked = true;
  79700. if (this._currentMeshSelected && this._currentHit) {
  79701. this._scene.simulatePointerDown(this._currentHit);
  79702. }
  79703. };
  79704. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79705. if (this._currentMeshSelected && this._currentHit) {
  79706. this._scene.simulatePointerUp(this._currentHit);
  79707. }
  79708. this._pointerDownOnMeshAsked = false;
  79709. };
  79710. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79711. // Only rotate when user is not currently selecting a teleportation location
  79712. if (this._teleportationRequestInitiated) {
  79713. return;
  79714. }
  79715. if (!this._rotationLeftAsked) {
  79716. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79717. this._rotationLeftAsked = true;
  79718. if (this._rotationAllowed) {
  79719. this._rotateCamera(false);
  79720. }
  79721. }
  79722. }
  79723. else {
  79724. if (stateObject.x > -this._padSensibilityDown) {
  79725. this._rotationLeftAsked = false;
  79726. }
  79727. }
  79728. if (!this._rotationRightAsked) {
  79729. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79730. this._rotationRightAsked = true;
  79731. if (this._rotationAllowed) {
  79732. this._rotateCamera(true);
  79733. }
  79734. }
  79735. }
  79736. else {
  79737. if (stateObject.x < this._padSensibilityDown) {
  79738. this._rotationRightAsked = false;
  79739. }
  79740. }
  79741. };
  79742. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79743. // Only teleport backwards when user is not currently selecting a teleportation location
  79744. if (this._teleportationRequestInitiated) {
  79745. return;
  79746. }
  79747. // Teleport backwards
  79748. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79749. if (!this._teleportationBackRequestInitiated) {
  79750. if (!this.currentVRCamera) {
  79751. return;
  79752. }
  79753. // Get rotation and position of the current camera
  79754. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79755. var position = this.currentVRCamera.position;
  79756. // If the camera has device position, use that instead
  79757. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79758. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79759. position = this.currentVRCamera.devicePosition;
  79760. }
  79761. // Get matrix with only the y rotation of the device rotation
  79762. rotation.toEulerAnglesToRef(this._workingVector);
  79763. this._workingVector.z = 0;
  79764. this._workingVector.x = 0;
  79765. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79766. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79767. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79768. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79769. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79770. var ray = new BABYLON.Ray(position, this._workingVector);
  79771. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79772. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79773. this._teleportCamera(hit.pickedPoint);
  79774. }
  79775. this._teleportationBackRequestInitiated = true;
  79776. }
  79777. }
  79778. else {
  79779. this._teleportationBackRequestInitiated = false;
  79780. }
  79781. };
  79782. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79783. var _this = this;
  79784. var controllerMesh = webVRController.mesh;
  79785. if (controllerMesh) {
  79786. if (webVRController.hand === "left") {
  79787. if (!this._interactionsEnabledOnLeftController) {
  79788. this._enableInteractionOnController(webVRController);
  79789. }
  79790. this._teleportationEnabledOnLeftController = true;
  79791. }
  79792. else {
  79793. if (!this._interactionsEnabledOnRightController) {
  79794. this._enableInteractionOnController(webVRController);
  79795. }
  79796. this._teleportationEnabledOnRightController = true;
  79797. }
  79798. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79799. this._dpadPressed = false;
  79800. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79801. _this._dpadPressed = stateObject.pressed;
  79802. if (!_this._dpadPressed) {
  79803. _this._rotationLeftAsked = false;
  79804. _this._rotationRightAsked = false;
  79805. _this._teleportationBackRequestInitiated = false;
  79806. }
  79807. });
  79808. }
  79809. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79810. if (_this.teleportationEnabled) {
  79811. _this._checkTeleportBackwards(stateObject);
  79812. _this._checkTeleportWithRay(stateObject, webVRController);
  79813. }
  79814. _this._checkRotate(stateObject);
  79815. });
  79816. }
  79817. };
  79818. // Gaze support used to point to teleport or to interact with an object
  79819. VRExperienceHelper.prototype._createGazeTracker = function () {
  79820. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79821. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79822. this._gazeTracker.isPickable = false;
  79823. this._gazeTracker.isVisible = false;
  79824. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79825. targetMat.specularColor = BABYLON.Color3.Black();
  79826. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79827. targetMat.backFaceCulling = false;
  79828. this._gazeTracker.material = targetMat;
  79829. };
  79830. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79831. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79832. this._teleportationTarget.isPickable = false;
  79833. var length = 512;
  79834. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79835. dynamicTexture.hasAlpha = true;
  79836. var context = dynamicTexture.getContext();
  79837. var centerX = length / 2;
  79838. var centerY = length / 2;
  79839. var radius = 200;
  79840. context.beginPath();
  79841. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79842. context.fillStyle = this._teleportationFillColor;
  79843. context.fill();
  79844. context.lineWidth = 10;
  79845. context.strokeStyle = this._teleportationBorderColor;
  79846. context.stroke();
  79847. context.closePath();
  79848. dynamicTexture.update();
  79849. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79850. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79851. this._teleportationTarget.material = teleportationCircleMaterial;
  79852. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79853. torus.isPickable = false;
  79854. torus.parent = this._teleportationTarget;
  79855. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79856. var keys = [];
  79857. keys.push({
  79858. frame: 0,
  79859. value: 0
  79860. });
  79861. keys.push({
  79862. frame: 30,
  79863. value: 0.4
  79864. });
  79865. keys.push({
  79866. frame: 60,
  79867. value: 0
  79868. });
  79869. animationInnerCircle.setKeys(keys);
  79870. var easingFunction = new BABYLON.SineEase();
  79871. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79872. animationInnerCircle.setEasingFunction(easingFunction);
  79873. torus.animations = [];
  79874. torus.animations.push(animationInnerCircle);
  79875. this._scene.beginAnimation(torus, 0, 60, true);
  79876. this._hideTeleportationTarget();
  79877. };
  79878. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79879. if (this._teleportationInitialized) {
  79880. this._teleportationTarget.isVisible = true;
  79881. if (this._isDefaultTeleportationTarget) {
  79882. this._teleportationTarget.getChildren()[0].isVisible = true;
  79883. }
  79884. }
  79885. };
  79886. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79887. if (this._teleportationInitialized) {
  79888. this._teleportationTarget.isVisible = false;
  79889. if (this._isDefaultTeleportationTarget) {
  79890. this._teleportationTarget.getChildren()[0].isVisible = false;
  79891. }
  79892. }
  79893. };
  79894. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79895. var _this = this;
  79896. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79897. return;
  79898. }
  79899. if (right) {
  79900. this._rotationAngle++;
  79901. }
  79902. else {
  79903. this._rotationAngle--;
  79904. }
  79905. this.currentVRCamera.animations = [];
  79906. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79907. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79908. var animationRotationKeys = [];
  79909. animationRotationKeys.push({
  79910. frame: 0,
  79911. value: this.currentVRCamera.rotationQuaternion
  79912. });
  79913. animationRotationKeys.push({
  79914. frame: 6,
  79915. value: target
  79916. });
  79917. animationRotation.setKeys(animationRotationKeys);
  79918. animationRotation.setEasingFunction(this._circleEase);
  79919. this.currentVRCamera.animations.push(animationRotation);
  79920. this._postProcessMove.animations = [];
  79921. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79922. var vignetteWeightKeys = [];
  79923. vignetteWeightKeys.push({
  79924. frame: 0,
  79925. value: 0
  79926. });
  79927. vignetteWeightKeys.push({
  79928. frame: 3,
  79929. value: 4
  79930. });
  79931. vignetteWeightKeys.push({
  79932. frame: 6,
  79933. value: 0
  79934. });
  79935. animationPP.setKeys(vignetteWeightKeys);
  79936. animationPP.setEasingFunction(this._circleEase);
  79937. this._postProcessMove.animations.push(animationPP);
  79938. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79939. var vignetteStretchKeys = [];
  79940. vignetteStretchKeys.push({
  79941. frame: 0,
  79942. value: 0
  79943. });
  79944. vignetteStretchKeys.push({
  79945. frame: 3,
  79946. value: 10
  79947. });
  79948. vignetteStretchKeys.push({
  79949. frame: 6,
  79950. value: 0
  79951. });
  79952. animationPP2.setKeys(vignetteStretchKeys);
  79953. animationPP2.setEasingFunction(this._circleEase);
  79954. this._postProcessMove.animations.push(animationPP2);
  79955. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79956. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79957. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79958. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79959. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79960. });
  79961. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79962. };
  79963. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79964. if (hit.pickedPoint) {
  79965. this._teleportationAllowed = true;
  79966. if (this._teleportationRequestInitiated) {
  79967. this._displayTeleportationTarget();
  79968. }
  79969. else {
  79970. this._hideTeleportationTarget();
  79971. }
  79972. this._haloCenter.copyFrom(hit.pickedPoint);
  79973. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79974. var pickNormal = hit.getNormal(true, false);
  79975. if (pickNormal) {
  79976. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79977. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79978. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79979. }
  79980. this._teleportationTarget.position.y += 0.1;
  79981. }
  79982. };
  79983. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79984. var _this = this;
  79985. if (location === void 0) { location = null; }
  79986. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79987. return;
  79988. }
  79989. if (!location) {
  79990. location = this._haloCenter;
  79991. }
  79992. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79993. // offset of the headset from the anchor.
  79994. if (this.webVRCamera.leftCamera) {
  79995. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79996. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79997. location.subtractToRef(this._workingVector, this._workingVector);
  79998. }
  79999. else {
  80000. this._workingVector.copyFrom(location);
  80001. }
  80002. // Add height to account for user's height offset
  80003. if (this.isInVRMode) {
  80004. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  80005. }
  80006. else {
  80007. this._workingVector.y += this._defaultHeight;
  80008. }
  80009. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  80010. // Create animation from the camera's position to the new location
  80011. this.currentVRCamera.animations = [];
  80012. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80013. var animationCameraTeleportationKeys = [{
  80014. frame: 0,
  80015. value: this.currentVRCamera.position
  80016. },
  80017. {
  80018. frame: 11,
  80019. value: this._workingVector
  80020. }
  80021. ];
  80022. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  80023. animationCameraTeleportation.setEasingFunction(this._circleEase);
  80024. this.currentVRCamera.animations.push(animationCameraTeleportation);
  80025. this._postProcessMove.animations = [];
  80026. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80027. var vignetteWeightKeys = [];
  80028. vignetteWeightKeys.push({
  80029. frame: 0,
  80030. value: 0
  80031. });
  80032. vignetteWeightKeys.push({
  80033. frame: 5,
  80034. value: 8
  80035. });
  80036. vignetteWeightKeys.push({
  80037. frame: 11,
  80038. value: 0
  80039. });
  80040. animationPP.setKeys(vignetteWeightKeys);
  80041. this._postProcessMove.animations.push(animationPP);
  80042. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80043. var vignetteStretchKeys = [];
  80044. vignetteStretchKeys.push({
  80045. frame: 0,
  80046. value: 0
  80047. });
  80048. vignetteStretchKeys.push({
  80049. frame: 5,
  80050. value: 10
  80051. });
  80052. vignetteStretchKeys.push({
  80053. frame: 11,
  80054. value: 0
  80055. });
  80056. animationPP2.setKeys(vignetteStretchKeys);
  80057. this._postProcessMove.animations.push(animationPP2);
  80058. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80059. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80060. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80061. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  80062. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80063. });
  80064. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  80065. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  80066. });
  80067. };
  80068. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  80069. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80070. return;
  80071. }
  80072. var ray;
  80073. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  80074. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  80075. }
  80076. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  80077. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  80078. }
  80079. else {
  80080. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  80081. }
  80082. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80083. // Moving the gazeTracker on the mesh face targetted
  80084. if (hit && hit.pickedPoint) {
  80085. if (this._displayGaze) {
  80086. var multiplier = 1;
  80087. this._gazeTracker.isVisible = true;
  80088. if (this._isActionableMesh) {
  80089. multiplier = 3;
  80090. }
  80091. this._gazeTracker.scaling.x = hit.distance * multiplier;
  80092. this._gazeTracker.scaling.y = hit.distance * multiplier;
  80093. this._gazeTracker.scaling.z = hit.distance * multiplier;
  80094. var pickNormal = hit.getNormal();
  80095. // To avoid z-fighting
  80096. var deltaFighting = 0.002;
  80097. if (pickNormal) {
  80098. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80099. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80100. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  80101. }
  80102. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  80103. if (this._gazeTracker.position.x < 0) {
  80104. this._gazeTracker.position.x += deltaFighting;
  80105. }
  80106. else {
  80107. this._gazeTracker.position.x -= deltaFighting;
  80108. }
  80109. if (this._gazeTracker.position.y < 0) {
  80110. this._gazeTracker.position.y += deltaFighting;
  80111. }
  80112. else {
  80113. this._gazeTracker.position.y -= deltaFighting;
  80114. }
  80115. if (this._gazeTracker.position.z < 0) {
  80116. this._gazeTracker.position.z += deltaFighting;
  80117. }
  80118. else {
  80119. this._gazeTracker.position.z -= deltaFighting;
  80120. }
  80121. }
  80122. // Changing the size of the laser pointer based on the distance from the targetted point
  80123. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  80124. this._rightLaserPointer.scaling.y = hit.distance;
  80125. this._rightLaserPointer.position.z = -hit.distance / 2;
  80126. }
  80127. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  80128. this._leftLaserPointer.scaling.y = hit.distance;
  80129. this._leftLaserPointer.position.z = -hit.distance / 2;
  80130. }
  80131. }
  80132. else {
  80133. this._gazeTracker.isVisible = false;
  80134. }
  80135. if (hit && hit.pickedMesh) {
  80136. this._currentHit = hit;
  80137. if (this._pointerDownOnMeshAsked) {
  80138. this._scene.simulatePointerMove(this._currentHit);
  80139. }
  80140. // The object selected is the floor, we're in a teleportation scenario
  80141. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80142. // Moving the teleportation area to this targetted point
  80143. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80144. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  80145. this._notifySelectedMeshUnselected();
  80146. }
  80147. this._currentMeshSelected = null;
  80148. this._moveTeleportationSelectorTo(hit);
  80149. return;
  80150. }
  80151. // If not, we're in a selection scenario
  80152. this._hideTeleportationTarget();
  80153. this._teleportationAllowed = false;
  80154. if (hit.pickedMesh !== this._currentMeshSelected) {
  80155. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80156. this.onNewMeshPicked.notifyObservers(hit);
  80157. this._currentMeshSelected = hit.pickedMesh;
  80158. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80159. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80160. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80161. this._isActionableMesh = true;
  80162. }
  80163. else {
  80164. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80165. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80166. this._isActionableMesh = false;
  80167. }
  80168. try {
  80169. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  80170. }
  80171. catch (err) {
  80172. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80173. }
  80174. }
  80175. else {
  80176. this._notifySelectedMeshUnselected();
  80177. this._currentMeshSelected = null;
  80178. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80179. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80180. }
  80181. }
  80182. }
  80183. else {
  80184. this._currentHit = null;
  80185. this._notifySelectedMeshUnselected();
  80186. this._currentMeshSelected = null;
  80187. this._teleportationAllowed = false;
  80188. this._hideTeleportationTarget();
  80189. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80190. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80191. }
  80192. };
  80193. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80194. if (this._currentMeshSelected) {
  80195. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80196. }
  80197. };
  80198. /**
  80199. * Sets the color of the laser ray from the vr controllers.
  80200. * @param color new color for the ray.
  80201. */
  80202. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80203. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80204. this._leftLaserPointer.material.emissiveColor = color;
  80205. }
  80206. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80207. this._rightLaserPointer.material.emissiveColor = color;
  80208. }
  80209. };
  80210. /**
  80211. * Sets the color of the ray from the vr headsets gaze.
  80212. * @param color new color for the ray.
  80213. */
  80214. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80215. if (this._gazeTracker.material) {
  80216. this._gazeTracker.material.emissiveColor = color;
  80217. }
  80218. };
  80219. /**
  80220. * Exits VR and disposes of the vr experience helper
  80221. */
  80222. VRExperienceHelper.prototype.dispose = function () {
  80223. if (this.isInVRMode) {
  80224. this.exitVR();
  80225. }
  80226. if (this._passProcessMove) {
  80227. this._passProcessMove.dispose();
  80228. }
  80229. if (this._postProcessMove) {
  80230. this._postProcessMove.dispose();
  80231. }
  80232. if (this._webVRCamera) {
  80233. this._webVRCamera.dispose();
  80234. }
  80235. if (this._vrDeviceOrientationCamera) {
  80236. this._vrDeviceOrientationCamera.dispose();
  80237. }
  80238. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80239. document.body.removeChild(this._btnVR);
  80240. }
  80241. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80242. this._deviceOrientationCamera.dispose();
  80243. }
  80244. if (this._gazeTracker) {
  80245. this._gazeTracker.dispose();
  80246. }
  80247. if (this._teleportationTarget) {
  80248. this._teleportationTarget.dispose();
  80249. }
  80250. this._floorMeshesCollection = [];
  80251. document.removeEventListener("keydown", this._onKeyDown);
  80252. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80253. window.removeEventListener("resize", this._onResize);
  80254. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80255. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80256. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80257. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80258. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80259. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80260. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80261. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80262. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80263. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80264. this._scene.unregisterBeforeRender(this.beforeRender);
  80265. };
  80266. /**
  80267. * Gets the name of the VRExperienceHelper class
  80268. * @returns "VRExperienceHelper"
  80269. */
  80270. VRExperienceHelper.prototype.getClassName = function () {
  80271. return "VRExperienceHelper";
  80272. };
  80273. return VRExperienceHelper;
  80274. }());
  80275. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80276. })(BABYLON || (BABYLON = {}));
  80277. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80278. // Mainly based on these 2 articles :
  80279. // 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
  80280. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80281. var BABYLON;
  80282. (function (BABYLON) {
  80283. var JoystickAxis;
  80284. (function (JoystickAxis) {
  80285. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80286. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80287. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80288. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80289. var VirtualJoystick = /** @class */ (function () {
  80290. function VirtualJoystick(leftJoystick) {
  80291. var _this = this;
  80292. if (leftJoystick) {
  80293. this._leftJoystick = true;
  80294. }
  80295. else {
  80296. this._leftJoystick = false;
  80297. }
  80298. VirtualJoystick._globalJoystickIndex++;
  80299. // By default left & right arrow keys are moving the X
  80300. // and up & down keys are moving the Y
  80301. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80302. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80303. this.reverseLeftRight = false;
  80304. this.reverseUpDown = false;
  80305. // collections of pointers
  80306. this._touches = new BABYLON.StringDictionary();
  80307. this.deltaPosition = BABYLON.Vector3.Zero();
  80308. this._joystickSensibility = 25;
  80309. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80310. this._onResize = function (evt) {
  80311. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80312. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80313. if (VirtualJoystick.vjCanvas) {
  80314. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80315. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80316. }
  80317. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80318. };
  80319. // injecting a canvas element on top of the canvas 3D game
  80320. if (!VirtualJoystick.vjCanvas) {
  80321. window.addEventListener("resize", this._onResize, false);
  80322. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80323. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80324. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80325. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80326. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80327. VirtualJoystick.vjCanvas.style.width = "100%";
  80328. VirtualJoystick.vjCanvas.style.height = "100%";
  80329. VirtualJoystick.vjCanvas.style.position = "absolute";
  80330. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80331. VirtualJoystick.vjCanvas.style.top = "0px";
  80332. VirtualJoystick.vjCanvas.style.left = "0px";
  80333. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80334. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80335. // Support for jQuery PEP polyfill
  80336. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80337. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80338. if (!context) {
  80339. throw new Error("Unable to create canvas for virtual joystick");
  80340. }
  80341. VirtualJoystick.vjCanvasContext = context;
  80342. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80343. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80344. document.body.appendChild(VirtualJoystick.vjCanvas);
  80345. }
  80346. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80347. this.pressed = false;
  80348. // default joystick color
  80349. this._joystickColor = "cyan";
  80350. this._joystickPointerID = -1;
  80351. // current joystick position
  80352. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80353. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80354. // origin joystick position
  80355. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80356. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80357. this._onPointerDownHandlerRef = function (evt) {
  80358. _this._onPointerDown(evt);
  80359. };
  80360. this._onPointerMoveHandlerRef = function (evt) {
  80361. _this._onPointerMove(evt);
  80362. };
  80363. this._onPointerUpHandlerRef = function (evt) {
  80364. _this._onPointerUp(evt);
  80365. };
  80366. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80367. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80368. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80369. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80370. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80371. evt.preventDefault(); // Disables system menu
  80372. }, false);
  80373. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80374. }
  80375. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80376. this._joystickSensibility = newJoystickSensibility;
  80377. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80378. };
  80379. VirtualJoystick.prototype._onPointerDown = function (e) {
  80380. var positionOnScreenCondition;
  80381. e.preventDefault();
  80382. if (this._leftJoystick === true) {
  80383. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80384. }
  80385. else {
  80386. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80387. }
  80388. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80389. // First contact will be dedicated to the virtual joystick
  80390. this._joystickPointerID = e.pointerId;
  80391. this._joystickPointerStartPos.x = e.clientX;
  80392. this._joystickPointerStartPos.y = e.clientY;
  80393. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80394. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80395. this._deltaJoystickVector.x = 0;
  80396. this._deltaJoystickVector.y = 0;
  80397. this.pressed = true;
  80398. this._touches.add(e.pointerId.toString(), e);
  80399. }
  80400. else {
  80401. // You can only trigger the action buttons with a joystick declared
  80402. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80403. this._action();
  80404. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80405. }
  80406. }
  80407. };
  80408. VirtualJoystick.prototype._onPointerMove = function (e) {
  80409. // If the current pointer is the one associated to the joystick (first touch contact)
  80410. if (this._joystickPointerID == e.pointerId) {
  80411. this._joystickPointerPos.x = e.clientX;
  80412. this._joystickPointerPos.y = e.clientY;
  80413. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80414. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80415. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80416. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80417. switch (this._axisTargetedByLeftAndRight) {
  80418. case JoystickAxis.X:
  80419. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80420. break;
  80421. case JoystickAxis.Y:
  80422. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80423. break;
  80424. case JoystickAxis.Z:
  80425. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80426. break;
  80427. }
  80428. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80429. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80430. switch (this._axisTargetedByUpAndDown) {
  80431. case JoystickAxis.X:
  80432. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80433. break;
  80434. case JoystickAxis.Y:
  80435. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80436. break;
  80437. case JoystickAxis.Z:
  80438. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80439. break;
  80440. }
  80441. }
  80442. else {
  80443. var data = this._touches.get(e.pointerId.toString());
  80444. if (data) {
  80445. data.x = e.clientX;
  80446. data.y = e.clientY;
  80447. }
  80448. }
  80449. };
  80450. VirtualJoystick.prototype._onPointerUp = function (e) {
  80451. if (this._joystickPointerID == e.pointerId) {
  80452. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80453. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80454. this._joystickPointerID = -1;
  80455. this.pressed = false;
  80456. }
  80457. else {
  80458. var touch = this._touches.get(e.pointerId.toString());
  80459. if (touch) {
  80460. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80461. }
  80462. }
  80463. this._deltaJoystickVector.x = 0;
  80464. this._deltaJoystickVector.y = 0;
  80465. this._touches.remove(e.pointerId.toString());
  80466. };
  80467. /**
  80468. * Change the color of the virtual joystick
  80469. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80470. */
  80471. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80472. this._joystickColor = newColor;
  80473. };
  80474. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80475. this._action = action;
  80476. };
  80477. // Define which axis you'd like to control for left & right
  80478. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80479. switch (axis) {
  80480. case JoystickAxis.X:
  80481. case JoystickAxis.Y:
  80482. case JoystickAxis.Z:
  80483. this._axisTargetedByLeftAndRight = axis;
  80484. break;
  80485. default:
  80486. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80487. break;
  80488. }
  80489. };
  80490. // Define which axis you'd like to control for up & down
  80491. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80492. switch (axis) {
  80493. case JoystickAxis.X:
  80494. case JoystickAxis.Y:
  80495. case JoystickAxis.Z:
  80496. this._axisTargetedByUpAndDown = axis;
  80497. break;
  80498. default:
  80499. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80500. break;
  80501. }
  80502. };
  80503. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80504. var _this = this;
  80505. if (this.pressed) {
  80506. this._touches.forEach(function (key, touch) {
  80507. if (touch.pointerId === _this._joystickPointerID) {
  80508. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80509. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80510. VirtualJoystick.vjCanvasContext.beginPath();
  80511. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80512. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80513. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80514. VirtualJoystick.vjCanvasContext.stroke();
  80515. VirtualJoystick.vjCanvasContext.closePath();
  80516. VirtualJoystick.vjCanvasContext.beginPath();
  80517. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80518. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80519. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80520. VirtualJoystick.vjCanvasContext.stroke();
  80521. VirtualJoystick.vjCanvasContext.closePath();
  80522. VirtualJoystick.vjCanvasContext.beginPath();
  80523. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80524. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80525. VirtualJoystick.vjCanvasContext.stroke();
  80526. VirtualJoystick.vjCanvasContext.closePath();
  80527. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80528. }
  80529. else {
  80530. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80531. VirtualJoystick.vjCanvasContext.beginPath();
  80532. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80533. VirtualJoystick.vjCanvasContext.beginPath();
  80534. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80535. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80536. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80537. VirtualJoystick.vjCanvasContext.stroke();
  80538. VirtualJoystick.vjCanvasContext.closePath();
  80539. touch.prevX = touch.x;
  80540. touch.prevY = touch.y;
  80541. }
  80542. ;
  80543. });
  80544. }
  80545. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80546. };
  80547. VirtualJoystick.prototype.releaseCanvas = function () {
  80548. if (VirtualJoystick.vjCanvas) {
  80549. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80550. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80551. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80552. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80553. window.removeEventListener("resize", this._onResize);
  80554. document.body.removeChild(VirtualJoystick.vjCanvas);
  80555. VirtualJoystick.vjCanvas = null;
  80556. }
  80557. };
  80558. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80559. VirtualJoystick._globalJoystickIndex = 0;
  80560. return VirtualJoystick;
  80561. }());
  80562. BABYLON.VirtualJoystick = VirtualJoystick;
  80563. })(BABYLON || (BABYLON = {}));
  80564. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80565. var BABYLON;
  80566. (function (BABYLON) {
  80567. // We're mainly based on the logic defined into the FreeCamera code
  80568. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80569. __extends(VirtualJoysticksCamera, _super);
  80570. function VirtualJoysticksCamera(name, position, scene) {
  80571. var _this = _super.call(this, name, position, scene) || this;
  80572. _this.inputs.addVirtualJoystick();
  80573. return _this;
  80574. }
  80575. VirtualJoysticksCamera.prototype.getClassName = function () {
  80576. return "VirtualJoysticksCamera";
  80577. };
  80578. return VirtualJoysticksCamera;
  80579. }(BABYLON.FreeCamera));
  80580. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80581. })(BABYLON || (BABYLON = {}));
  80582. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80583. var BABYLON;
  80584. (function (BABYLON) {
  80585. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80586. function FreeCameraVirtualJoystickInput() {
  80587. }
  80588. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80589. return this._leftjoystick;
  80590. };
  80591. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80592. return this._rightjoystick;
  80593. };
  80594. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80595. if (this._leftjoystick) {
  80596. var camera = this.camera;
  80597. var speed = camera._computeLocalCameraSpeed() * 50;
  80598. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80599. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80600. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80601. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80602. if (!this._leftjoystick.pressed) {
  80603. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80604. }
  80605. if (!this._rightjoystick.pressed) {
  80606. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80607. }
  80608. }
  80609. };
  80610. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80611. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80612. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80613. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80614. this._leftjoystick.setJoystickSensibility(0.15);
  80615. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80616. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80617. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80618. this._rightjoystick.reverseUpDown = true;
  80619. this._rightjoystick.setJoystickSensibility(0.05);
  80620. this._rightjoystick.setJoystickColor("yellow");
  80621. };
  80622. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80623. this._leftjoystick.releaseCanvas();
  80624. this._rightjoystick.releaseCanvas();
  80625. };
  80626. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80627. return "FreeCameraVirtualJoystickInput";
  80628. };
  80629. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80630. return "virtualJoystick";
  80631. };
  80632. return FreeCameraVirtualJoystickInput;
  80633. }());
  80634. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80635. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80636. })(BABYLON || (BABYLON = {}));
  80637. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80638. var BABYLON;
  80639. (function (BABYLON) {
  80640. var SimplificationSettings = /** @class */ (function () {
  80641. function SimplificationSettings(quality, distance, optimizeMesh) {
  80642. this.quality = quality;
  80643. this.distance = distance;
  80644. this.optimizeMesh = optimizeMesh;
  80645. }
  80646. return SimplificationSettings;
  80647. }());
  80648. BABYLON.SimplificationSettings = SimplificationSettings;
  80649. var SimplificationQueue = /** @class */ (function () {
  80650. function SimplificationQueue() {
  80651. this.running = false;
  80652. this._simplificationArray = [];
  80653. }
  80654. SimplificationQueue.prototype.addTask = function (task) {
  80655. this._simplificationArray.push(task);
  80656. };
  80657. SimplificationQueue.prototype.executeNext = function () {
  80658. var task = this._simplificationArray.pop();
  80659. if (task) {
  80660. this.running = true;
  80661. this.runSimplification(task);
  80662. }
  80663. else {
  80664. this.running = false;
  80665. }
  80666. };
  80667. SimplificationQueue.prototype.runSimplification = function (task) {
  80668. var _this = this;
  80669. if (task.parallelProcessing) {
  80670. //parallel simplifier
  80671. task.settings.forEach(function (setting) {
  80672. var simplifier = _this.getSimplifier(task);
  80673. simplifier.simplify(setting, function (newMesh) {
  80674. task.mesh.addLODLevel(setting.distance, newMesh);
  80675. newMesh.isVisible = true;
  80676. //check if it is the last
  80677. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80678. //all done, run the success callback.
  80679. task.successCallback();
  80680. }
  80681. _this.executeNext();
  80682. });
  80683. });
  80684. }
  80685. else {
  80686. //single simplifier.
  80687. var simplifier = this.getSimplifier(task);
  80688. var runDecimation = function (setting, callback) {
  80689. simplifier.simplify(setting, function (newMesh) {
  80690. task.mesh.addLODLevel(setting.distance, newMesh);
  80691. newMesh.isVisible = true;
  80692. //run the next quality level
  80693. callback();
  80694. });
  80695. };
  80696. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80697. runDecimation(task.settings[loop.index], function () {
  80698. loop.executeNext();
  80699. });
  80700. }, function () {
  80701. //execution ended, run the success callback.
  80702. if (task.successCallback) {
  80703. task.successCallback();
  80704. }
  80705. _this.executeNext();
  80706. });
  80707. }
  80708. };
  80709. SimplificationQueue.prototype.getSimplifier = function (task) {
  80710. switch (task.simplificationType) {
  80711. case SimplificationType.QUADRATIC:
  80712. default:
  80713. return new QuadraticErrorSimplification(task.mesh);
  80714. }
  80715. };
  80716. return SimplificationQueue;
  80717. }());
  80718. BABYLON.SimplificationQueue = SimplificationQueue;
  80719. /**
  80720. * The implemented types of simplification.
  80721. * At the moment only Quadratic Error Decimation is implemented.
  80722. */
  80723. var SimplificationType;
  80724. (function (SimplificationType) {
  80725. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80726. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80727. var DecimationTriangle = /** @class */ (function () {
  80728. function DecimationTriangle(vertices) {
  80729. this.vertices = vertices;
  80730. this.error = new Array(4);
  80731. this.deleted = false;
  80732. this.isDirty = false;
  80733. this.deletePending = false;
  80734. this.borderFactor = 0;
  80735. }
  80736. return DecimationTriangle;
  80737. }());
  80738. BABYLON.DecimationTriangle = DecimationTriangle;
  80739. var DecimationVertex = /** @class */ (function () {
  80740. function DecimationVertex(position, id) {
  80741. this.position = position;
  80742. this.id = id;
  80743. this.isBorder = true;
  80744. this.q = new QuadraticMatrix();
  80745. this.triangleCount = 0;
  80746. this.triangleStart = 0;
  80747. this.originalOffsets = [];
  80748. }
  80749. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80750. this.position.copyFrom(newPosition);
  80751. };
  80752. return DecimationVertex;
  80753. }());
  80754. BABYLON.DecimationVertex = DecimationVertex;
  80755. var QuadraticMatrix = /** @class */ (function () {
  80756. function QuadraticMatrix(data) {
  80757. this.data = new Array(10);
  80758. for (var i = 0; i < 10; ++i) {
  80759. if (data && data[i]) {
  80760. this.data[i] = data[i];
  80761. }
  80762. else {
  80763. this.data[i] = 0;
  80764. }
  80765. }
  80766. }
  80767. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80768. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80769. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80770. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80771. return det;
  80772. };
  80773. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80774. for (var i = 0; i < 10; ++i) {
  80775. this.data[i] += matrix.data[i];
  80776. }
  80777. };
  80778. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80779. for (var i = 0; i < 10; ++i) {
  80780. this.data[i] += data[i];
  80781. }
  80782. };
  80783. QuadraticMatrix.prototype.add = function (matrix) {
  80784. var m = new QuadraticMatrix();
  80785. for (var i = 0; i < 10; ++i) {
  80786. m.data[i] = this.data[i] + matrix.data[i];
  80787. }
  80788. return m;
  80789. };
  80790. QuadraticMatrix.FromData = function (a, b, c, d) {
  80791. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80792. };
  80793. //returning an array to avoid garbage collection
  80794. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80795. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80796. };
  80797. return QuadraticMatrix;
  80798. }());
  80799. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80800. var Reference = /** @class */ (function () {
  80801. function Reference(vertexId, triangleId) {
  80802. this.vertexId = vertexId;
  80803. this.triangleId = triangleId;
  80804. }
  80805. return Reference;
  80806. }());
  80807. BABYLON.Reference = Reference;
  80808. /**
  80809. * An implementation of the Quadratic Error simplification algorithm.
  80810. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80811. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80812. * @author RaananW
  80813. */
  80814. var QuadraticErrorSimplification = /** @class */ (function () {
  80815. function QuadraticErrorSimplification(_mesh) {
  80816. this._mesh = _mesh;
  80817. this.syncIterations = 5000;
  80818. this.aggressiveness = 7;
  80819. this.decimationIterations = 100;
  80820. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80821. }
  80822. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80823. var _this = this;
  80824. this.initDecimatedMesh();
  80825. //iterating through the submeshes array, one after the other.
  80826. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80827. _this.initWithMesh(loop.index, function () {
  80828. _this.runDecimation(settings, loop.index, function () {
  80829. loop.executeNext();
  80830. });
  80831. }, settings.optimizeMesh);
  80832. }, function () {
  80833. setTimeout(function () {
  80834. successCallback(_this._reconstructedMesh);
  80835. }, 0);
  80836. });
  80837. };
  80838. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80839. var _this = this;
  80840. var targetCount = ~~(this.triangles.length * settings.quality);
  80841. var deletedTriangles = 0;
  80842. var triangleCount = this.triangles.length;
  80843. var iterationFunction = function (iteration, callback) {
  80844. setTimeout(function () {
  80845. if (iteration % 5 === 0) {
  80846. _this.updateMesh(iteration === 0);
  80847. }
  80848. for (var i = 0; i < _this.triangles.length; ++i) {
  80849. _this.triangles[i].isDirty = false;
  80850. }
  80851. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80852. var trianglesIterator = function (i) {
  80853. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80854. var t = _this.triangles[tIdx];
  80855. if (!t)
  80856. return;
  80857. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80858. return;
  80859. }
  80860. for (var j = 0; j < 3; ++j) {
  80861. if (t.error[j] < threshold) {
  80862. var deleted0 = [];
  80863. var deleted1 = [];
  80864. var v0 = t.vertices[j];
  80865. var v1 = t.vertices[(j + 1) % 3];
  80866. if (v0.isBorder || v1.isBorder)
  80867. continue;
  80868. var p = BABYLON.Vector3.Zero();
  80869. var n = BABYLON.Vector3.Zero();
  80870. var uv = BABYLON.Vector2.Zero();
  80871. var color = new BABYLON.Color4(0, 0, 0, 1);
  80872. _this.calculateError(v0, v1, p, n, uv, color);
  80873. var delTr = new Array();
  80874. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80875. continue;
  80876. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80877. continue;
  80878. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80879. continue;
  80880. var uniqueArray = new Array();
  80881. delTr.forEach(function (deletedT) {
  80882. if (uniqueArray.indexOf(deletedT) === -1) {
  80883. deletedT.deletePending = true;
  80884. uniqueArray.push(deletedT);
  80885. }
  80886. });
  80887. if (uniqueArray.length % 2 !== 0) {
  80888. continue;
  80889. }
  80890. v0.q = v1.q.add(v0.q);
  80891. v0.updatePosition(p);
  80892. var tStart = _this.references.length;
  80893. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80894. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80895. var tCount = _this.references.length - tStart;
  80896. if (tCount <= v0.triangleCount) {
  80897. if (tCount) {
  80898. for (var c = 0; c < tCount; c++) {
  80899. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80900. }
  80901. }
  80902. }
  80903. else {
  80904. v0.triangleStart = tStart;
  80905. }
  80906. v0.triangleCount = tCount;
  80907. break;
  80908. }
  80909. }
  80910. };
  80911. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80912. }, 0);
  80913. };
  80914. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80915. if (triangleCount - deletedTriangles <= targetCount)
  80916. loop.breakLoop();
  80917. else {
  80918. iterationFunction(loop.index, function () {
  80919. loop.executeNext();
  80920. });
  80921. }
  80922. }, function () {
  80923. setTimeout(function () {
  80924. //reconstruct this part of the mesh
  80925. _this.reconstructMesh(submeshIndex);
  80926. successCallback();
  80927. }, 0);
  80928. });
  80929. };
  80930. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80931. var _this = this;
  80932. this.vertices = [];
  80933. this.triangles = [];
  80934. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80935. var indices = this._mesh.getIndices();
  80936. var submesh = this._mesh.subMeshes[submeshIndex];
  80937. var findInVertices = function (positionToSearch) {
  80938. if (optimizeMesh) {
  80939. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80940. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80941. return _this.vertices[ii];
  80942. }
  80943. }
  80944. }
  80945. return null;
  80946. };
  80947. var vertexReferences = [];
  80948. var vertexInit = function (i) {
  80949. if (!positionData) {
  80950. return;
  80951. }
  80952. var offset = i + submesh.verticesStart;
  80953. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80954. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80955. vertex.originalOffsets.push(offset);
  80956. if (vertex.id === _this.vertices.length) {
  80957. _this.vertices.push(vertex);
  80958. }
  80959. vertexReferences.push(vertex.id);
  80960. };
  80961. //var totalVertices = mesh.getTotalVertices();
  80962. var totalVertices = submesh.verticesCount;
  80963. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80964. var indicesInit = function (i) {
  80965. if (!indices) {
  80966. return;
  80967. }
  80968. var offset = (submesh.indexStart / 3) + i;
  80969. var pos = (offset * 3);
  80970. var i0 = indices[pos + 0];
  80971. var i1 = indices[pos + 1];
  80972. var i2 = indices[pos + 2];
  80973. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80974. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80975. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80976. var triangle = new DecimationTriangle([v0, v1, v2]);
  80977. triangle.originalOffset = pos;
  80978. _this.triangles.push(triangle);
  80979. };
  80980. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80981. _this.init(callback);
  80982. });
  80983. });
  80984. };
  80985. QuadraticErrorSimplification.prototype.init = function (callback) {
  80986. var _this = this;
  80987. var triangleInit1 = function (i) {
  80988. var t = _this.triangles[i];
  80989. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80990. for (var j = 0; j < 3; j++) {
  80991. 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))));
  80992. }
  80993. };
  80994. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80995. var triangleInit2 = function (i) {
  80996. var t = _this.triangles[i];
  80997. for (var j = 0; j < 3; ++j) {
  80998. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80999. }
  81000. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81001. };
  81002. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  81003. callback();
  81004. });
  81005. });
  81006. };
  81007. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  81008. var newTriangles = [];
  81009. var i;
  81010. for (i = 0; i < this.vertices.length; ++i) {
  81011. this.vertices[i].triangleCount = 0;
  81012. }
  81013. var t;
  81014. var j;
  81015. for (i = 0; i < this.triangles.length; ++i) {
  81016. if (!this.triangles[i].deleted) {
  81017. t = this.triangles[i];
  81018. for (j = 0; j < 3; ++j) {
  81019. t.vertices[j].triangleCount = 1;
  81020. }
  81021. newTriangles.push(t);
  81022. }
  81023. }
  81024. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  81025. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  81026. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  81027. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  81028. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  81029. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81030. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  81031. var vertexCount = 0;
  81032. for (i = 0; i < this.vertices.length; ++i) {
  81033. var vertex = this.vertices[i];
  81034. vertex.id = vertexCount;
  81035. if (vertex.triangleCount) {
  81036. vertex.originalOffsets.forEach(function (originalOffset) {
  81037. if (!normalData) {
  81038. return;
  81039. }
  81040. newPositionData.push(vertex.position.x);
  81041. newPositionData.push(vertex.position.y);
  81042. newPositionData.push(vertex.position.z);
  81043. newNormalData.push(normalData[originalOffset * 3]);
  81044. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  81045. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  81046. if (uvs && uvs.length) {
  81047. newUVsData.push(uvs[(originalOffset * 2)]);
  81048. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  81049. }
  81050. else if (colorsData && colorsData.length) {
  81051. newColorsData.push(colorsData[(originalOffset * 4)]);
  81052. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  81053. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  81054. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  81055. }
  81056. ++vertexCount;
  81057. });
  81058. }
  81059. }
  81060. var startingIndex = this._reconstructedMesh.getTotalIndices();
  81061. var startingVertex = this._reconstructedMesh.getTotalVertices();
  81062. var submeshesArray = this._reconstructedMesh.subMeshes;
  81063. this._reconstructedMesh.subMeshes = [];
  81064. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  81065. var originalIndices = this._mesh.getIndices();
  81066. for (i = 0; i < newTriangles.length; ++i) {
  81067. t = newTriangles[i]; //now get the new referencing point for each vertex
  81068. [0, 1, 2].forEach(function (idx) {
  81069. var id = originalIndices[t.originalOffset + idx];
  81070. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  81071. if (offset < 0)
  81072. offset = 0;
  81073. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  81074. });
  81075. }
  81076. //overwriting the old vertex buffers and indices.
  81077. this._reconstructedMesh.setIndices(newIndicesArray);
  81078. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  81079. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  81080. if (newUVsData.length > 0)
  81081. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  81082. if (newColorsData.length > 0)
  81083. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  81084. //create submesh
  81085. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  81086. if (submeshIndex > 0) {
  81087. this._reconstructedMesh.subMeshes = [];
  81088. submeshesArray.forEach(function (submesh) {
  81089. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  81090. });
  81091. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  81092. }
  81093. };
  81094. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  81095. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  81096. this._reconstructedMesh.material = this._mesh.material;
  81097. this._reconstructedMesh.parent = this._mesh.parent;
  81098. this._reconstructedMesh.isVisible = false;
  81099. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81100. };
  81101. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81102. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81103. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81104. if (t.deleted)
  81105. continue;
  81106. var s = this.references[vertex1.triangleStart + i].vertexId;
  81107. var v1 = t.vertices[(s + 1) % 3];
  81108. var v2 = t.vertices[(s + 2) % 3];
  81109. if ((v1 === vertex2 || v2 === vertex2)) {
  81110. deletedArray[i] = true;
  81111. delTr.push(t);
  81112. continue;
  81113. }
  81114. var d1 = v1.position.subtract(point);
  81115. d1 = d1.normalize();
  81116. var d2 = v2.position.subtract(point);
  81117. d2 = d2.normalize();
  81118. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81119. return true;
  81120. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81121. deletedArray[i] = false;
  81122. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81123. return true;
  81124. }
  81125. return false;
  81126. };
  81127. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81128. var newDeleted = deletedTriangles;
  81129. for (var i = 0; i < vertex.triangleCount; ++i) {
  81130. var ref = this.references[vertex.triangleStart + i];
  81131. var t = this.triangles[ref.triangleId];
  81132. if (t.deleted)
  81133. continue;
  81134. if (deletedArray[i] && t.deletePending) {
  81135. t.deleted = true;
  81136. newDeleted++;
  81137. continue;
  81138. }
  81139. t.vertices[ref.vertexId] = origVertex;
  81140. t.isDirty = true;
  81141. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81142. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81143. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81144. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81145. this.references.push(ref);
  81146. }
  81147. return newDeleted;
  81148. };
  81149. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81150. for (var i = 0; i < this.vertices.length; ++i) {
  81151. var vCount = [];
  81152. var vId = [];
  81153. var v = this.vertices[i];
  81154. var j;
  81155. for (j = 0; j < v.triangleCount; ++j) {
  81156. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81157. for (var ii = 0; ii < 3; ii++) {
  81158. var ofs = 0;
  81159. var vv = triangle.vertices[ii];
  81160. while (ofs < vCount.length) {
  81161. if (vId[ofs] === vv.id)
  81162. break;
  81163. ++ofs;
  81164. }
  81165. if (ofs === vCount.length) {
  81166. vCount.push(1);
  81167. vId.push(vv.id);
  81168. }
  81169. else {
  81170. vCount[ofs]++;
  81171. }
  81172. }
  81173. }
  81174. for (j = 0; j < vCount.length; ++j) {
  81175. if (vCount[j] === 1) {
  81176. this.vertices[vId[j]].isBorder = true;
  81177. }
  81178. else {
  81179. this.vertices[vId[j]].isBorder = false;
  81180. }
  81181. }
  81182. }
  81183. };
  81184. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81185. if (identifyBorders === void 0) { identifyBorders = false; }
  81186. var i;
  81187. if (!identifyBorders) {
  81188. var newTrianglesVector = [];
  81189. for (i = 0; i < this.triangles.length; ++i) {
  81190. if (!this.triangles[i].deleted) {
  81191. newTrianglesVector.push(this.triangles[i]);
  81192. }
  81193. }
  81194. this.triangles = newTrianglesVector;
  81195. }
  81196. for (i = 0; i < this.vertices.length; ++i) {
  81197. this.vertices[i].triangleCount = 0;
  81198. this.vertices[i].triangleStart = 0;
  81199. }
  81200. var t;
  81201. var j;
  81202. var v;
  81203. for (i = 0; i < this.triangles.length; ++i) {
  81204. t = this.triangles[i];
  81205. for (j = 0; j < 3; ++j) {
  81206. v = t.vertices[j];
  81207. v.triangleCount++;
  81208. }
  81209. }
  81210. var tStart = 0;
  81211. for (i = 0; i < this.vertices.length; ++i) {
  81212. this.vertices[i].triangleStart = tStart;
  81213. tStart += this.vertices[i].triangleCount;
  81214. this.vertices[i].triangleCount = 0;
  81215. }
  81216. var newReferences = new Array(this.triangles.length * 3);
  81217. for (i = 0; i < this.triangles.length; ++i) {
  81218. t = this.triangles[i];
  81219. for (j = 0; j < 3; ++j) {
  81220. v = t.vertices[j];
  81221. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81222. v.triangleCount++;
  81223. }
  81224. }
  81225. this.references = newReferences;
  81226. if (identifyBorders) {
  81227. this.identifyBorder();
  81228. }
  81229. };
  81230. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81231. var x = point.x;
  81232. var y = point.y;
  81233. var z = point.z;
  81234. 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
  81235. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81236. };
  81237. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81238. var q = vertex1.q.add(vertex2.q);
  81239. var border = vertex1.isBorder && vertex2.isBorder;
  81240. var error = 0;
  81241. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81242. if (qDet !== 0 && !border) {
  81243. if (!pointResult) {
  81244. pointResult = BABYLON.Vector3.Zero();
  81245. }
  81246. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81247. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81248. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81249. error = this.vertexError(q, pointResult);
  81250. }
  81251. else {
  81252. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81253. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81254. var error1 = this.vertexError(q, vertex1.position);
  81255. var error2 = this.vertexError(q, vertex2.position);
  81256. var error3 = this.vertexError(q, p3);
  81257. error = Math.min(error1, error2, error3);
  81258. if (error === error1) {
  81259. if (pointResult) {
  81260. pointResult.copyFrom(vertex1.position);
  81261. }
  81262. }
  81263. else if (error === error2) {
  81264. if (pointResult) {
  81265. pointResult.copyFrom(vertex2.position);
  81266. }
  81267. }
  81268. else {
  81269. if (pointResult) {
  81270. pointResult.copyFrom(p3);
  81271. }
  81272. }
  81273. }
  81274. return error;
  81275. };
  81276. return QuadraticErrorSimplification;
  81277. }());
  81278. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81279. })(BABYLON || (BABYLON = {}));
  81280. //# sourceMappingURL=babylon.meshSimplification.js.map
  81281. var BABYLON;
  81282. (function (BABYLON) {
  81283. var MeshLODLevel = /** @class */ (function () {
  81284. function MeshLODLevel(distance, mesh) {
  81285. this.distance = distance;
  81286. this.mesh = mesh;
  81287. }
  81288. return MeshLODLevel;
  81289. }());
  81290. BABYLON.MeshLODLevel = MeshLODLevel;
  81291. })(BABYLON || (BABYLON = {}));
  81292. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81293. var BABYLON;
  81294. (function (BABYLON) {
  81295. /**
  81296. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81297. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81298. */
  81299. var SceneOptimization = /** @class */ (function () {
  81300. /**
  81301. * Creates the SceneOptimization object
  81302. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81303. * @param desc defines the description associated with the optimization
  81304. */
  81305. function SceneOptimization(
  81306. /**
  81307. * Defines the priority of this optimization (0 by default which means first in the list)
  81308. */
  81309. priority) {
  81310. if (priority === void 0) { priority = 0; }
  81311. this.priority = priority;
  81312. }
  81313. /**
  81314. * Gets a string describing the action executed by the current optimization
  81315. * @returns description string
  81316. */
  81317. SceneOptimization.prototype.getDescription = function () {
  81318. return "";
  81319. };
  81320. /**
  81321. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81322. * @param scene defines the current scene where to apply this optimization
  81323. * @param optimizer defines the current optimizer
  81324. * @returns true if everything that can be done was applied
  81325. */
  81326. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81327. return true;
  81328. };
  81329. ;
  81330. return SceneOptimization;
  81331. }());
  81332. BABYLON.SceneOptimization = SceneOptimization;
  81333. /**
  81334. * Defines an optimization used to reduce the size of render target textures
  81335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81336. */
  81337. var TextureOptimization = /** @class */ (function (_super) {
  81338. __extends(TextureOptimization, _super);
  81339. /**
  81340. * Creates the TextureOptimization object
  81341. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81342. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  81343. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81344. */
  81345. function TextureOptimization(
  81346. /**
  81347. * Defines the priority of this optimization (0 by default which means first in the list)
  81348. */
  81349. priority,
  81350. /**
  81351. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  81352. */
  81353. maximumSize,
  81354. /**
  81355. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81356. */
  81357. step) {
  81358. if (priority === void 0) { priority = 0; }
  81359. if (maximumSize === void 0) { maximumSize = 1024; }
  81360. if (step === void 0) { step = 0.5; }
  81361. var _this = _super.call(this, priority) || this;
  81362. _this.priority = priority;
  81363. _this.maximumSize = maximumSize;
  81364. _this.step = step;
  81365. return _this;
  81366. }
  81367. /**
  81368. * Gets a string describing the action executed by the current optimization
  81369. * @returns description string
  81370. */
  81371. TextureOptimization.prototype.getDescription = function () {
  81372. return "Reducing render target texture size to " + this.maximumSize;
  81373. };
  81374. /**
  81375. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81376. * @param scene defines the current scene where to apply this optimization
  81377. * @param optimizer defines the current optimizer
  81378. * @returns true if everything that can be done was applied
  81379. */
  81380. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81381. var allDone = true;
  81382. for (var index = 0; index < scene.textures.length; index++) {
  81383. var texture = scene.textures[index];
  81384. if (!texture.canRescale || texture.getContext) {
  81385. continue;
  81386. }
  81387. var currentSize = texture.getSize();
  81388. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81389. if (maxDimension > this.maximumSize) {
  81390. texture.scale(this.step);
  81391. allDone = false;
  81392. }
  81393. }
  81394. return allDone;
  81395. };
  81396. return TextureOptimization;
  81397. }(SceneOptimization));
  81398. BABYLON.TextureOptimization = TextureOptimization;
  81399. /**
  81400. * Defines an optimization used to increase or decrease the rendering resolution
  81401. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81402. */
  81403. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81404. __extends(HardwareScalingOptimization, _super);
  81405. /**
  81406. * Creates the HardwareScalingOptimization object
  81407. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81408. * @param maximumScale defines the maximum scale to use (2 by default)
  81409. * @param step defines the step to use between two passes (0.5 by default)
  81410. */
  81411. function HardwareScalingOptimization(
  81412. /**
  81413. * Defines the priority of this optimization (0 by default which means first in the list)
  81414. */
  81415. priority,
  81416. /**
  81417. * Defines the maximum scale to use (2 by default)
  81418. */
  81419. maximumScale,
  81420. /**
  81421. * Defines the step to use between two passes (0.5 by default)
  81422. */
  81423. step) {
  81424. if (priority === void 0) { priority = 0; }
  81425. if (maximumScale === void 0) { maximumScale = 2; }
  81426. if (step === void 0) { step = 0.25; }
  81427. var _this = _super.call(this, priority) || this;
  81428. _this.priority = priority;
  81429. _this.maximumScale = maximumScale;
  81430. _this.step = step;
  81431. _this._currentScale = -1;
  81432. _this._directionOffset = 1;
  81433. return _this;
  81434. }
  81435. /**
  81436. * Gets a string describing the action executed by the current optimization
  81437. * @return description string
  81438. */
  81439. HardwareScalingOptimization.prototype.getDescription = function () {
  81440. return "Setting hardware scaling level to " + this._currentScale;
  81441. };
  81442. /**
  81443. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81444. * @param scene defines the current scene where to apply this optimization
  81445. * @param optimizer defines the current optimizer
  81446. * @returns true if everything that can be done was applied
  81447. */
  81448. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81449. if (this._currentScale === -1) {
  81450. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81451. if (this._currentScale > this.maximumScale) {
  81452. this._directionOffset = -1;
  81453. }
  81454. }
  81455. this._currentScale += this._directionOffset * this.step;
  81456. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81457. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81458. };
  81459. ;
  81460. return HardwareScalingOptimization;
  81461. }(SceneOptimization));
  81462. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81463. /**
  81464. * Defines an optimization used to remove shadows
  81465. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81466. */
  81467. var ShadowsOptimization = /** @class */ (function (_super) {
  81468. __extends(ShadowsOptimization, _super);
  81469. function ShadowsOptimization() {
  81470. return _super !== null && _super.apply(this, arguments) || this;
  81471. }
  81472. /**
  81473. * Gets a string describing the action executed by the current optimization
  81474. * @return description string
  81475. */
  81476. ShadowsOptimization.prototype.getDescription = function () {
  81477. return "Turning shadows on/off";
  81478. };
  81479. /**
  81480. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81481. * @param scene defines the current scene where to apply this optimization
  81482. * @param optimizer defines the current optimizer
  81483. * @returns true if everything that can be done was applied
  81484. */
  81485. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81486. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81487. return true;
  81488. };
  81489. ;
  81490. return ShadowsOptimization;
  81491. }(SceneOptimization));
  81492. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81493. /**
  81494. * Defines an optimization used to turn post-processes off
  81495. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81496. */
  81497. var PostProcessesOptimization = /** @class */ (function (_super) {
  81498. __extends(PostProcessesOptimization, _super);
  81499. function PostProcessesOptimization() {
  81500. return _super !== null && _super.apply(this, arguments) || this;
  81501. }
  81502. /**
  81503. * Gets a string describing the action executed by the current optimization
  81504. * @return description string
  81505. */
  81506. PostProcessesOptimization.prototype.getDescription = function () {
  81507. return "Turning post-processes on/off";
  81508. };
  81509. /**
  81510. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81511. * @param scene defines the current scene where to apply this optimization
  81512. * @param optimizer defines the current optimizer
  81513. * @returns true if everything that can be done was applied
  81514. */
  81515. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81516. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81517. return true;
  81518. };
  81519. ;
  81520. return PostProcessesOptimization;
  81521. }(SceneOptimization));
  81522. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81523. /**
  81524. * Defines an optimization used to turn lens flares off
  81525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81526. */
  81527. var LensFlaresOptimization = /** @class */ (function (_super) {
  81528. __extends(LensFlaresOptimization, _super);
  81529. function LensFlaresOptimization() {
  81530. return _super !== null && _super.apply(this, arguments) || this;
  81531. }
  81532. /**
  81533. * Gets a string describing the action executed by the current optimization
  81534. * @return description string
  81535. */
  81536. LensFlaresOptimization.prototype.getDescription = function () {
  81537. return "Turning lens flares on/off";
  81538. };
  81539. /**
  81540. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81541. * @param scene defines the current scene where to apply this optimization
  81542. * @param optimizer defines the current optimizer
  81543. * @returns true if everything that can be done was applied
  81544. */
  81545. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81546. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81547. return true;
  81548. };
  81549. ;
  81550. return LensFlaresOptimization;
  81551. }(SceneOptimization));
  81552. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81553. /**
  81554. * Defines an optimization based on user defined callback.
  81555. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81556. */
  81557. var CustomOptimization = /** @class */ (function (_super) {
  81558. __extends(CustomOptimization, _super);
  81559. function CustomOptimization() {
  81560. return _super !== null && _super.apply(this, arguments) || this;
  81561. }
  81562. /**
  81563. * Gets a string describing the action executed by the current optimization
  81564. * @returns description string
  81565. */
  81566. CustomOptimization.prototype.getDescription = function () {
  81567. if (this.onGetDescription) {
  81568. return this.onGetDescription();
  81569. }
  81570. return "Running user defined callback";
  81571. };
  81572. /**
  81573. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81574. * @param scene defines the current scene where to apply this optimization
  81575. * @param optimizer defines the current optimizer
  81576. * @returns true if everything that can be done was applied
  81577. */
  81578. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81579. if (this.onApply) {
  81580. return this.onApply(scene, optimizer);
  81581. }
  81582. return true;
  81583. };
  81584. ;
  81585. return CustomOptimization;
  81586. }(SceneOptimization));
  81587. BABYLON.CustomOptimization = CustomOptimization;
  81588. /**
  81589. * Defines an optimization used to turn particles off
  81590. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81591. */
  81592. var ParticlesOptimization = /** @class */ (function (_super) {
  81593. __extends(ParticlesOptimization, _super);
  81594. function ParticlesOptimization() {
  81595. return _super !== null && _super.apply(this, arguments) || this;
  81596. }
  81597. /**
  81598. * Gets a string describing the action executed by the current optimization
  81599. * @return description string
  81600. */
  81601. ParticlesOptimization.prototype.getDescription = function () {
  81602. return "Turning particles on/off";
  81603. };
  81604. /**
  81605. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81606. * @param scene defines the current scene where to apply this optimization
  81607. * @param optimizer defines the current optimizer
  81608. * @returns true if everything that can be done was applied
  81609. */
  81610. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81611. scene.particlesEnabled = optimizer.isInImprovementMode;
  81612. return true;
  81613. };
  81614. ;
  81615. return ParticlesOptimization;
  81616. }(SceneOptimization));
  81617. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81618. /**
  81619. * Defines an optimization used to turn render targets off
  81620. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81621. */
  81622. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81623. __extends(RenderTargetsOptimization, _super);
  81624. function RenderTargetsOptimization() {
  81625. return _super !== null && _super.apply(this, arguments) || this;
  81626. }
  81627. /**
  81628. * Gets a string describing the action executed by the current optimization
  81629. * @return description string
  81630. */
  81631. RenderTargetsOptimization.prototype.getDescription = function () {
  81632. return "Turning render targets off";
  81633. };
  81634. /**
  81635. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81636. * @param scene defines the current scene where to apply this optimization
  81637. * @param optimizer defines the current optimizer
  81638. * @returns true if everything that can be done was applied
  81639. */
  81640. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81641. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81642. return true;
  81643. };
  81644. ;
  81645. return RenderTargetsOptimization;
  81646. }(SceneOptimization));
  81647. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81648. /**
  81649. * Defines an optimization used to merge meshes with compatible materials
  81650. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81651. */
  81652. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81653. __extends(MergeMeshesOptimization, _super);
  81654. function MergeMeshesOptimization() {
  81655. var _this = _super !== null && _super.apply(this, arguments) || this;
  81656. _this._canBeMerged = function (abstractMesh) {
  81657. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81658. return false;
  81659. }
  81660. var mesh = abstractMesh;
  81661. if (!mesh.isVisible || !mesh.isEnabled()) {
  81662. return false;
  81663. }
  81664. if (mesh.instances.length > 0) {
  81665. return false;
  81666. }
  81667. if (mesh.skeleton || mesh.hasLODLevels) {
  81668. return false;
  81669. }
  81670. if (mesh.parent) {
  81671. return false;
  81672. }
  81673. return true;
  81674. };
  81675. return _this;
  81676. }
  81677. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81678. /**
  81679. * Gets or sets a boolean which defines if optimization octree has to be updated
  81680. */
  81681. get: function () {
  81682. return MergeMeshesOptimization._UpdateSelectionTree;
  81683. },
  81684. /**
  81685. * Gets or sets a boolean which defines if optimization octree has to be updated
  81686. */
  81687. set: function (value) {
  81688. MergeMeshesOptimization._UpdateSelectionTree = value;
  81689. },
  81690. enumerable: true,
  81691. configurable: true
  81692. });
  81693. /**
  81694. * Gets a string describing the action executed by the current optimization
  81695. * @return description string
  81696. */
  81697. MergeMeshesOptimization.prototype.getDescription = function () {
  81698. return "Merging similar meshes together";
  81699. };
  81700. /**
  81701. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81702. * @param scene defines the current scene where to apply this optimization
  81703. * @param optimizer defines the current optimizer
  81704. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81705. * @returns true if everything that can be done was applied
  81706. */
  81707. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81708. var globalPool = scene.meshes.slice(0);
  81709. var globalLength = globalPool.length;
  81710. for (var index = 0; index < globalLength; index++) {
  81711. var currentPool = new Array();
  81712. var current = globalPool[index];
  81713. // Checks
  81714. if (!this._canBeMerged(current)) {
  81715. continue;
  81716. }
  81717. currentPool.push(current);
  81718. // Find compatible meshes
  81719. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81720. var otherMesh = globalPool[subIndex];
  81721. if (!this._canBeMerged(otherMesh)) {
  81722. continue;
  81723. }
  81724. if (otherMesh.material !== current.material) {
  81725. continue;
  81726. }
  81727. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81728. continue;
  81729. }
  81730. currentPool.push(otherMesh);
  81731. globalLength--;
  81732. globalPool.splice(subIndex, 1);
  81733. subIndex--;
  81734. }
  81735. if (currentPool.length < 2) {
  81736. continue;
  81737. }
  81738. // Merge meshes
  81739. BABYLON.Mesh.MergeMeshes(currentPool);
  81740. }
  81741. if (updateSelectionTree != undefined) {
  81742. if (updateSelectionTree) {
  81743. scene.createOrUpdateSelectionOctree();
  81744. }
  81745. }
  81746. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81747. scene.createOrUpdateSelectionOctree();
  81748. }
  81749. return true;
  81750. };
  81751. ;
  81752. MergeMeshesOptimization._UpdateSelectionTree = false;
  81753. return MergeMeshesOptimization;
  81754. }(SceneOptimization));
  81755. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81756. /**
  81757. * Defines a list of options used by SceneOptimizer
  81758. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81759. */
  81760. var SceneOptimizerOptions = /** @class */ (function () {
  81761. /**
  81762. * Creates a new list of options used by SceneOptimizer
  81763. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81764. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81765. */
  81766. function SceneOptimizerOptions(
  81767. /**
  81768. * Defines the target frame rate to reach (60 by default)
  81769. */
  81770. targetFrameRate,
  81771. /**
  81772. * Defines the interval between two checkes (2000ms by default)
  81773. */
  81774. trackerDuration) {
  81775. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81776. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81777. this.targetFrameRate = targetFrameRate;
  81778. this.trackerDuration = trackerDuration;
  81779. /**
  81780. * Gets the list of optimizations to apply
  81781. */
  81782. this.optimizations = new Array();
  81783. }
  81784. /**
  81785. * Add a new optimization
  81786. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81787. * @returns the current SceneOptimizerOptions
  81788. */
  81789. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81790. this.optimizations.push(optimization);
  81791. return this;
  81792. };
  81793. /**
  81794. * Add a new custom optimization
  81795. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81796. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81797. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81798. * @returns the current SceneOptimizerOptions
  81799. */
  81800. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81801. if (priority === void 0) { priority = 0; }
  81802. var optimization = new CustomOptimization(priority);
  81803. optimization.onApply = onApply;
  81804. optimization.onGetDescription = onGetDescription;
  81805. this.optimizations.push(optimization);
  81806. return this;
  81807. };
  81808. /**
  81809. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81810. * @param targetFrameRate defines the target frame rate (60 by default)
  81811. * @returns a SceneOptimizerOptions object
  81812. */
  81813. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81814. var result = new SceneOptimizerOptions(targetFrameRate);
  81815. var priority = 0;
  81816. result.addOptimization(new MergeMeshesOptimization(priority));
  81817. result.addOptimization(new ShadowsOptimization(priority));
  81818. result.addOptimization(new LensFlaresOptimization(priority));
  81819. // Next priority
  81820. priority++;
  81821. result.addOptimization(new PostProcessesOptimization(priority));
  81822. result.addOptimization(new ParticlesOptimization(priority));
  81823. // Next priority
  81824. priority++;
  81825. result.addOptimization(new TextureOptimization(priority, 1024));
  81826. return result;
  81827. };
  81828. /**
  81829. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81830. * @param targetFrameRate defines the target frame rate (60 by default)
  81831. * @returns a SceneOptimizerOptions object
  81832. */
  81833. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81834. var result = new SceneOptimizerOptions(targetFrameRate);
  81835. var priority = 0;
  81836. result.addOptimization(new MergeMeshesOptimization(priority));
  81837. result.addOptimization(new ShadowsOptimization(priority));
  81838. result.addOptimization(new LensFlaresOptimization(priority));
  81839. // Next priority
  81840. priority++;
  81841. result.addOptimization(new PostProcessesOptimization(priority));
  81842. result.addOptimization(new ParticlesOptimization(priority));
  81843. // Next priority
  81844. priority++;
  81845. result.addOptimization(new TextureOptimization(priority, 512));
  81846. // Next priority
  81847. priority++;
  81848. result.addOptimization(new RenderTargetsOptimization(priority));
  81849. // Next priority
  81850. priority++;
  81851. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81852. return result;
  81853. };
  81854. /**
  81855. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81856. * @param targetFrameRate defines the target frame rate (60 by default)
  81857. * @returns a SceneOptimizerOptions object
  81858. */
  81859. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81860. var result = new SceneOptimizerOptions(targetFrameRate);
  81861. var priority = 0;
  81862. result.addOptimization(new MergeMeshesOptimization(priority));
  81863. result.addOptimization(new ShadowsOptimization(priority));
  81864. result.addOptimization(new LensFlaresOptimization(priority));
  81865. // Next priority
  81866. priority++;
  81867. result.addOptimization(new PostProcessesOptimization(priority));
  81868. result.addOptimization(new ParticlesOptimization(priority));
  81869. // Next priority
  81870. priority++;
  81871. result.addOptimization(new TextureOptimization(priority, 256));
  81872. // Next priority
  81873. priority++;
  81874. result.addOptimization(new RenderTargetsOptimization(priority));
  81875. // Next priority
  81876. priority++;
  81877. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81878. return result;
  81879. };
  81880. return SceneOptimizerOptions;
  81881. }());
  81882. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81883. /**
  81884. * Class used to run optimizations in order to reach a target frame rate
  81885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81886. */
  81887. var SceneOptimizer = /** @class */ (function () {
  81888. /**
  81889. * Creates a new SceneOptimizer
  81890. * @param scene defines the scene to work on
  81891. * @param options defines the options to use with the SceneOptimizer
  81892. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81893. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  81894. */
  81895. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81896. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81897. if (improvementMode === void 0) { improvementMode = false; }
  81898. var _this = this;
  81899. this._isRunning = false;
  81900. this._currentPriorityLevel = 0;
  81901. this._targetFrameRate = 60;
  81902. this._trackerDuration = 2000;
  81903. this._currentFrameRate = 0;
  81904. this._improvementMode = false;
  81905. /**
  81906. * Defines an observable called when the optimizer reaches the target frame rate
  81907. */
  81908. this.onSuccessObservable = new BABYLON.Observable();
  81909. /**
  81910. * Defines an observable called when the optimizer enables an optimization
  81911. */
  81912. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81913. /**
  81914. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81915. */
  81916. this.onFailureObservable = new BABYLON.Observable();
  81917. if (!options) {
  81918. this._options = new SceneOptimizerOptions();
  81919. }
  81920. else {
  81921. this._options = options;
  81922. }
  81923. if (this._options.targetFrameRate) {
  81924. this._targetFrameRate = this._options.targetFrameRate;
  81925. }
  81926. if (this._options.trackerDuration) {
  81927. this._trackerDuration = this._options.trackerDuration;
  81928. }
  81929. if (autoGeneratePriorities) {
  81930. var priority = 0;
  81931. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81932. var optim = _a[_i];
  81933. optim.priority = priority++;
  81934. }
  81935. }
  81936. this._improvementMode = improvementMode;
  81937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81938. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81939. _this._sceneDisposeObserver = null;
  81940. _this.dispose();
  81941. });
  81942. }
  81943. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81944. /**
  81945. * Gets a boolean indicating if the optimizer is in improvement mode
  81946. */
  81947. get: function () {
  81948. return this._improvementMode;
  81949. },
  81950. enumerable: true,
  81951. configurable: true
  81952. });
  81953. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81954. /**
  81955. * Gets the current priority level (0 at start)
  81956. */
  81957. get: function () {
  81958. return this._currentPriorityLevel;
  81959. },
  81960. enumerable: true,
  81961. configurable: true
  81962. });
  81963. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81964. /**
  81965. * Gets the current frame rate checked by the SceneOptimizer
  81966. */
  81967. get: function () {
  81968. return this._currentFrameRate;
  81969. },
  81970. enumerable: true,
  81971. configurable: true
  81972. });
  81973. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81974. /**
  81975. * Gets or sets the current target frame rate (60 by default)
  81976. */
  81977. get: function () {
  81978. return this._targetFrameRate;
  81979. },
  81980. /**
  81981. * Gets or sets the current target frame rate (60 by default)
  81982. */
  81983. set: function (value) {
  81984. this._targetFrameRate = value;
  81985. },
  81986. enumerable: true,
  81987. configurable: true
  81988. });
  81989. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81990. /**
  81991. * Gets or sets the current interval between two checks (every 2000ms by default)
  81992. */
  81993. get: function () {
  81994. return this._trackerDuration;
  81995. },
  81996. /**
  81997. * Gets or sets the current interval between two checks (every 2000ms by default)
  81998. */
  81999. set: function (value) {
  82000. this._trackerDuration = value;
  82001. },
  82002. enumerable: true,
  82003. configurable: true
  82004. });
  82005. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  82006. /**
  82007. * Gets the list of active optimizations
  82008. */
  82009. get: function () {
  82010. return this._options.optimizations;
  82011. },
  82012. enumerable: true,
  82013. configurable: true
  82014. });
  82015. /**
  82016. * Stops the current optimizer
  82017. */
  82018. SceneOptimizer.prototype.stop = function () {
  82019. this._isRunning = false;
  82020. };
  82021. /**
  82022. * Reset the optimizer to initial step (current priority level = 0)
  82023. */
  82024. SceneOptimizer.prototype.reset = function () {
  82025. this._currentPriorityLevel = 0;
  82026. };
  82027. /**
  82028. * Start the optimizer. By default it will try to reach a specific framerate
  82029. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  82030. */
  82031. SceneOptimizer.prototype.start = function () {
  82032. var _this = this;
  82033. if (this._isRunning) {
  82034. return;
  82035. }
  82036. this._isRunning = true;
  82037. // Let's wait for the scene to be ready before running our check
  82038. this._scene.executeWhenReady(function () {
  82039. setTimeout(function () {
  82040. _this._checkCurrentState();
  82041. }, _this._trackerDuration);
  82042. });
  82043. };
  82044. SceneOptimizer.prototype._checkCurrentState = function () {
  82045. var _this = this;
  82046. if (!this._isRunning) {
  82047. return;
  82048. }
  82049. var scene = this._scene;
  82050. var options = this._options;
  82051. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  82052. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  82053. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  82054. this._isRunning = false;
  82055. this.onSuccessObservable.notifyObservers(this);
  82056. return;
  82057. }
  82058. // Apply current level of optimizations
  82059. var allDone = true;
  82060. var noOptimizationApplied = true;
  82061. for (var index = 0; index < options.optimizations.length; index++) {
  82062. var optimization = options.optimizations[index];
  82063. if (optimization.priority === this._currentPriorityLevel) {
  82064. noOptimizationApplied = false;
  82065. allDone = allDone && optimization.apply(scene, this);
  82066. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  82067. }
  82068. }
  82069. // If no optimization was applied, this is a failure :(
  82070. if (noOptimizationApplied) {
  82071. this._isRunning = false;
  82072. this.onFailureObservable.notifyObservers(this);
  82073. return;
  82074. }
  82075. // If all optimizations were done, move to next level
  82076. if (allDone) {
  82077. this._currentPriorityLevel++;
  82078. }
  82079. // Let's the system running for a specific amount of time before checking FPS
  82080. scene.executeWhenReady(function () {
  82081. setTimeout(function () {
  82082. _this._checkCurrentState();
  82083. }, _this._trackerDuration);
  82084. });
  82085. };
  82086. /**
  82087. * Release all resources
  82088. */
  82089. SceneOptimizer.prototype.dispose = function () {
  82090. this.stop();
  82091. this.onSuccessObservable.clear();
  82092. this.onFailureObservable.clear();
  82093. this.onNewOptimizationAppliedObservable.clear();
  82094. if (this._sceneDisposeObserver) {
  82095. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  82096. }
  82097. };
  82098. /**
  82099. * Helper function to create a SceneOptimizer with one single line of code
  82100. * @param scene defines the scene to work on
  82101. * @param options defines the options to use with the SceneOptimizer
  82102. * @param onSuccess defines a callback to call on success
  82103. * @param onFailure defines a callback to call on failure
  82104. * @returns the new SceneOptimizer object
  82105. */
  82106. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82107. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82108. if (onSuccess) {
  82109. optimizer.onSuccessObservable.add(function () {
  82110. onSuccess();
  82111. });
  82112. }
  82113. if (onFailure) {
  82114. optimizer.onFailureObservable.add(function () {
  82115. onFailure();
  82116. });
  82117. }
  82118. optimizer.start();
  82119. return optimizer;
  82120. };
  82121. return SceneOptimizer;
  82122. }());
  82123. BABYLON.SceneOptimizer = SceneOptimizer;
  82124. })(BABYLON || (BABYLON = {}));
  82125. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82126. var BABYLON;
  82127. (function (BABYLON) {
  82128. var OutlineRenderer = /** @class */ (function () {
  82129. function OutlineRenderer(scene) {
  82130. this.zOffset = 1;
  82131. this._scene = scene;
  82132. }
  82133. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82134. var _this = this;
  82135. if (useOverlay === void 0) { useOverlay = false; }
  82136. var scene = this._scene;
  82137. var engine = this._scene.getEngine();
  82138. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82139. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82140. return;
  82141. }
  82142. var mesh = subMesh.getRenderingMesh();
  82143. var material = subMesh.getMaterial();
  82144. if (!material || !scene.activeCamera) {
  82145. return;
  82146. }
  82147. engine.enableEffect(this._effect);
  82148. // Logarithmic depth
  82149. if (material.useLogarithmicDepth) {
  82150. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82151. }
  82152. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82153. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82154. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82155. // Bones
  82156. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82157. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82158. }
  82159. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82160. // Alpha test
  82161. if (material && material.needAlphaTesting()) {
  82162. var alphaTexture = material.getAlphaTestTexture();
  82163. if (alphaTexture) {
  82164. this._effect.setTexture("diffuseSampler", alphaTexture);
  82165. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82166. }
  82167. }
  82168. engine.setZOffset(-this.zOffset);
  82169. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82170. engine.setZOffset(0);
  82171. };
  82172. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82173. var defines = [];
  82174. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82175. var mesh = subMesh.getMesh();
  82176. var material = subMesh.getMaterial();
  82177. if (material) {
  82178. // Alpha test
  82179. if (material.needAlphaTesting()) {
  82180. defines.push("#define ALPHATEST");
  82181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82182. attribs.push(BABYLON.VertexBuffer.UVKind);
  82183. defines.push("#define UV1");
  82184. }
  82185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82186. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82187. defines.push("#define UV2");
  82188. }
  82189. }
  82190. //Logarithmic depth
  82191. if (material.useLogarithmicDepth) {
  82192. defines.push("#define LOGARITHMICDEPTH");
  82193. }
  82194. }
  82195. // Bones
  82196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82199. if (mesh.numBoneInfluencers > 4) {
  82200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82202. }
  82203. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82204. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82205. }
  82206. else {
  82207. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82208. }
  82209. // Instances
  82210. if (useInstances) {
  82211. defines.push("#define INSTANCES");
  82212. attribs.push("world0");
  82213. attribs.push("world1");
  82214. attribs.push("world2");
  82215. attribs.push("world3");
  82216. }
  82217. // Get correct effect
  82218. var join = defines.join("\n");
  82219. if (this._cachedDefines !== join) {
  82220. this._cachedDefines = join;
  82221. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82222. }
  82223. return this._effect.isReady();
  82224. };
  82225. return OutlineRenderer;
  82226. }());
  82227. BABYLON.OutlineRenderer = OutlineRenderer;
  82228. })(BABYLON || (BABYLON = {}));
  82229. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82230. var BABYLON;
  82231. (function (BABYLON) {
  82232. var FaceAdjacencies = /** @class */ (function () {
  82233. function FaceAdjacencies() {
  82234. this.edges = new Array();
  82235. this.edgesConnectedCount = 0;
  82236. }
  82237. return FaceAdjacencies;
  82238. }());
  82239. var EdgesRenderer = /** @class */ (function () {
  82240. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82241. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82242. if (epsilon === void 0) { epsilon = 0.95; }
  82243. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82244. this.edgesWidthScalerForOrthographic = 1000.0;
  82245. this.edgesWidthScalerForPerspective = 50.0;
  82246. this._linesPositions = new Array();
  82247. this._linesNormals = new Array();
  82248. this._linesIndices = new Array();
  82249. this._buffers = {};
  82250. this._checkVerticesInsteadOfIndices = false;
  82251. this._source = source;
  82252. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82253. this._epsilon = epsilon;
  82254. this._prepareRessources();
  82255. this._generateEdgesLines();
  82256. }
  82257. EdgesRenderer.prototype._prepareRessources = function () {
  82258. if (this._lineShader) {
  82259. return;
  82260. }
  82261. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82262. attributes: ["position", "normal"],
  82263. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82264. });
  82265. this._lineShader.disableDepthWrite = true;
  82266. this._lineShader.backFaceCulling = false;
  82267. };
  82268. EdgesRenderer.prototype._rebuild = function () {
  82269. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82270. if (buffer) {
  82271. buffer._rebuild();
  82272. }
  82273. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82274. if (buffer) {
  82275. buffer._rebuild();
  82276. }
  82277. var scene = this._source.getScene();
  82278. var engine = scene.getEngine();
  82279. this._ib = engine.createIndexBuffer(this._linesIndices);
  82280. };
  82281. EdgesRenderer.prototype.dispose = function () {
  82282. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82283. if (buffer) {
  82284. buffer.dispose();
  82285. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82286. }
  82287. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82288. if (buffer) {
  82289. buffer.dispose();
  82290. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82291. }
  82292. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82293. this._lineShader.dispose();
  82294. };
  82295. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82296. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82297. return 0;
  82298. }
  82299. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82300. return 1;
  82301. }
  82302. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82303. return 2;
  82304. }
  82305. return -1;
  82306. };
  82307. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82308. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82309. return 0;
  82310. }
  82311. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82312. return 1;
  82313. }
  82314. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82315. return 2;
  82316. }
  82317. return -1;
  82318. };
  82319. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82320. var needToCreateLine;
  82321. if (edge === undefined) {
  82322. needToCreateLine = true;
  82323. }
  82324. else {
  82325. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82326. needToCreateLine = dotProduct < this._epsilon;
  82327. }
  82328. if (needToCreateLine) {
  82329. var offset = this._linesPositions.length / 3;
  82330. var normal = p0.subtract(p1);
  82331. normal.normalize();
  82332. // Positions
  82333. this._linesPositions.push(p0.x);
  82334. this._linesPositions.push(p0.y);
  82335. this._linesPositions.push(p0.z);
  82336. this._linesPositions.push(p0.x);
  82337. this._linesPositions.push(p0.y);
  82338. this._linesPositions.push(p0.z);
  82339. this._linesPositions.push(p1.x);
  82340. this._linesPositions.push(p1.y);
  82341. this._linesPositions.push(p1.z);
  82342. this._linesPositions.push(p1.x);
  82343. this._linesPositions.push(p1.y);
  82344. this._linesPositions.push(p1.z);
  82345. // Normals
  82346. this._linesNormals.push(p1.x);
  82347. this._linesNormals.push(p1.y);
  82348. this._linesNormals.push(p1.z);
  82349. this._linesNormals.push(-1);
  82350. this._linesNormals.push(p1.x);
  82351. this._linesNormals.push(p1.y);
  82352. this._linesNormals.push(p1.z);
  82353. this._linesNormals.push(1);
  82354. this._linesNormals.push(p0.x);
  82355. this._linesNormals.push(p0.y);
  82356. this._linesNormals.push(p0.z);
  82357. this._linesNormals.push(-1);
  82358. this._linesNormals.push(p0.x);
  82359. this._linesNormals.push(p0.y);
  82360. this._linesNormals.push(p0.z);
  82361. this._linesNormals.push(1);
  82362. // Indices
  82363. this._linesIndices.push(offset);
  82364. this._linesIndices.push(offset + 1);
  82365. this._linesIndices.push(offset + 2);
  82366. this._linesIndices.push(offset);
  82367. this._linesIndices.push(offset + 2);
  82368. this._linesIndices.push(offset + 3);
  82369. }
  82370. };
  82371. EdgesRenderer.prototype._generateEdgesLines = function () {
  82372. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82373. var indices = this._source.getIndices();
  82374. if (!indices || !positions) {
  82375. return;
  82376. }
  82377. // First let's find adjacencies
  82378. var adjacencies = new Array();
  82379. var faceNormals = new Array();
  82380. var index;
  82381. var faceAdjacencies;
  82382. // Prepare faces
  82383. for (index = 0; index < indices.length; index += 3) {
  82384. faceAdjacencies = new FaceAdjacencies();
  82385. var p0Index = indices[index];
  82386. var p1Index = indices[index + 1];
  82387. var p2Index = indices[index + 2];
  82388. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82389. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82390. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82391. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82392. faceNormal.normalize();
  82393. faceNormals.push(faceNormal);
  82394. adjacencies.push(faceAdjacencies);
  82395. }
  82396. // Scan
  82397. for (index = 0; index < adjacencies.length; index++) {
  82398. faceAdjacencies = adjacencies[index];
  82399. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82400. var otherFaceAdjacencies = adjacencies[otherIndex];
  82401. if (faceAdjacencies.edgesConnectedCount === 3) {
  82402. break;
  82403. }
  82404. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82405. continue;
  82406. }
  82407. var otherP0 = indices[otherIndex * 3];
  82408. var otherP1 = indices[otherIndex * 3 + 1];
  82409. var otherP2 = indices[otherIndex * 3 + 2];
  82410. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82411. var otherEdgeIndex = 0;
  82412. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82413. continue;
  82414. }
  82415. switch (edgeIndex) {
  82416. case 0:
  82417. if (this._checkVerticesInsteadOfIndices) {
  82418. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82419. }
  82420. else {
  82421. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82422. }
  82423. break;
  82424. case 1:
  82425. if (this._checkVerticesInsteadOfIndices) {
  82426. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82427. }
  82428. else {
  82429. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82430. }
  82431. break;
  82432. case 2:
  82433. if (this._checkVerticesInsteadOfIndices) {
  82434. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82435. }
  82436. else {
  82437. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82438. }
  82439. break;
  82440. }
  82441. if (otherEdgeIndex === -1) {
  82442. continue;
  82443. }
  82444. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82445. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82446. faceAdjacencies.edgesConnectedCount++;
  82447. otherFaceAdjacencies.edgesConnectedCount++;
  82448. if (faceAdjacencies.edgesConnectedCount === 3) {
  82449. break;
  82450. }
  82451. }
  82452. }
  82453. }
  82454. // Create lines
  82455. for (index = 0; index < adjacencies.length; index++) {
  82456. // 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
  82457. var current = adjacencies[index];
  82458. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82459. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82460. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82461. }
  82462. // Merge into a single mesh
  82463. var engine = this._source.getScene().getEngine();
  82464. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82465. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82466. this._ib = engine.createIndexBuffer(this._linesIndices);
  82467. this._indicesCount = this._linesIndices.length;
  82468. };
  82469. EdgesRenderer.prototype.render = function () {
  82470. var scene = this._source.getScene();
  82471. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82472. return;
  82473. }
  82474. var engine = scene.getEngine();
  82475. this._lineShader._preBind();
  82476. // VBOs
  82477. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82478. scene.resetCachedMaterial();
  82479. this._lineShader.setColor4("color", this._source.edgesColor);
  82480. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82481. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82482. }
  82483. else {
  82484. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82485. }
  82486. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82487. this._lineShader.bind(this._source.getWorldMatrix());
  82488. // Draw order
  82489. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82490. this._lineShader.unbind();
  82491. engine.setDepthWrite(true);
  82492. };
  82493. return EdgesRenderer;
  82494. }());
  82495. BABYLON.EdgesRenderer = EdgesRenderer;
  82496. })(BABYLON || (BABYLON = {}));
  82497. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82498. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82499. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82500. s = arguments[i];
  82501. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82502. t[p] = s[p];
  82503. }
  82504. return t;
  82505. };
  82506. var BABYLON;
  82507. (function (BABYLON) {
  82508. /**
  82509. * The effect layer Helps adding post process effect blended with the main pass.
  82510. *
  82511. * This can be for instance use to generate glow or higlight effects on the scene.
  82512. *
  82513. * The effect layer class can not be used directly and is intented to inherited from to be
  82514. * customized per effects.
  82515. */
  82516. var EffectLayer = /** @class */ (function () {
  82517. /**
  82518. * Instantiates a new effect Layer and references it in the scene.
  82519. * @param name The name of the layer
  82520. * @param scene The scene to use the layer in
  82521. */
  82522. function EffectLayer(
  82523. /** The Friendly of the effect in the scene */
  82524. name, scene) {
  82525. this.name = name;
  82526. this._vertexBuffers = {};
  82527. this._maxSize = 0;
  82528. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82529. this._shouldRender = true;
  82530. this._postProcesses = [];
  82531. this._textures = [];
  82532. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82533. /**
  82534. * The clear color of the texture used to generate the glow map.
  82535. */
  82536. this.neutralColor = new BABYLON.Color4();
  82537. /**
  82538. * Specifies wether the highlight layer is enabled or not.
  82539. */
  82540. this.isEnabled = true;
  82541. /**
  82542. * An event triggered when the effect layer has been disposed.
  82543. */
  82544. this.onDisposeObservable = new BABYLON.Observable();
  82545. /**
  82546. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82547. */
  82548. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82549. /**
  82550. * An event triggered when the generated texture is being merged in the scene.
  82551. */
  82552. this.onBeforeComposeObservable = new BABYLON.Observable();
  82553. /**
  82554. * An event triggered when the generated texture has been merged in the scene.
  82555. */
  82556. this.onAfterComposeObservable = new BABYLON.Observable();
  82557. /**
  82558. * An event triggered when the efffect layer changes its size.
  82559. */
  82560. this.onSizeChangedObservable = new BABYLON.Observable();
  82561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82562. this._engine = scene.getEngine();
  82563. this._maxSize = this._engine.getCaps().maxTextureSize;
  82564. this._scene.effectLayers.push(this);
  82565. // Generate Buffers
  82566. this._generateIndexBuffer();
  82567. this._genrateVertexBuffer();
  82568. }
  82569. Object.defineProperty(EffectLayer.prototype, "camera", {
  82570. /**
  82571. * Gets the camera attached to the layer.
  82572. */
  82573. get: function () {
  82574. return this._effectLayerOptions.camera;
  82575. },
  82576. enumerable: true,
  82577. configurable: true
  82578. });
  82579. /**
  82580. * Initializes the effect layer with the required options.
  82581. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82582. */
  82583. EffectLayer.prototype._init = function (options) {
  82584. // Adapt options
  82585. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82586. this._setMainTextureSize();
  82587. this._createMainTexture();
  82588. this._createTextureAndPostProcesses();
  82589. this._mergeEffect = this._createMergeEffect();
  82590. };
  82591. /**
  82592. * Generates the index buffer of the full screen quad blending to the main canvas.
  82593. */
  82594. EffectLayer.prototype._generateIndexBuffer = function () {
  82595. // Indices
  82596. var indices = [];
  82597. indices.push(0);
  82598. indices.push(1);
  82599. indices.push(2);
  82600. indices.push(0);
  82601. indices.push(2);
  82602. indices.push(3);
  82603. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82604. };
  82605. /**
  82606. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82607. */
  82608. EffectLayer.prototype._genrateVertexBuffer = function () {
  82609. // VBO
  82610. var vertices = [];
  82611. vertices.push(1, 1);
  82612. vertices.push(-1, 1);
  82613. vertices.push(-1, -1);
  82614. vertices.push(1, -1);
  82615. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82616. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82617. };
  82618. /**
  82619. * Sets the main texture desired size which is the closest power of two
  82620. * of the engine canvas size.
  82621. */
  82622. EffectLayer.prototype._setMainTextureSize = function () {
  82623. if (this._effectLayerOptions.mainTextureFixedSize) {
  82624. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82625. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82626. }
  82627. else {
  82628. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82629. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82630. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82631. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82632. }
  82633. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82634. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82635. };
  82636. /**
  82637. * Creates the main texture for the effect layer.
  82638. */
  82639. EffectLayer.prototype._createMainTexture = function () {
  82640. var _this = this;
  82641. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82642. width: this._mainTextureDesiredSize.width,
  82643. height: this._mainTextureDesiredSize.height
  82644. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82645. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82646. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82647. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82648. this._mainTexture.anisotropicFilteringLevel = 1;
  82649. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82650. this._mainTexture.renderParticles = false;
  82651. this._mainTexture.renderList = null;
  82652. this._mainTexture.ignoreCameraViewport = true;
  82653. // Custom render function
  82654. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82655. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82656. var index;
  82657. var engine = _this._scene.getEngine();
  82658. if (depthOnlySubMeshes.length) {
  82659. engine.setColorWrite(false);
  82660. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82661. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82662. }
  82663. engine.setColorWrite(true);
  82664. }
  82665. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82666. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82667. }
  82668. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82669. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82670. }
  82671. for (index = 0; index < transparentSubMeshes.length; index++) {
  82672. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82673. }
  82674. };
  82675. this._mainTexture.onClearObservable.add(function (engine) {
  82676. engine.clear(_this.neutralColor, true, true, true);
  82677. });
  82678. };
  82679. /**
  82680. * Checks for the readiness of the element composing the layer.
  82681. * @param subMesh the mesh to check for
  82682. * @param useInstances specify wether or not to use instances to render the mesh
  82683. * @param emissiveTexture the associated emissive texture used to generate the glow
  82684. * @return true if ready otherwise, false
  82685. */
  82686. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82687. var material = subMesh.getMaterial();
  82688. if (!material) {
  82689. return false;
  82690. }
  82691. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82692. return false;
  82693. }
  82694. var defines = [];
  82695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82696. var mesh = subMesh.getMesh();
  82697. var uv1 = false;
  82698. var uv2 = false;
  82699. // Alpha test
  82700. if (material && material.needAlphaTesting()) {
  82701. var alphaTexture = material.getAlphaTestTexture();
  82702. if (alphaTexture) {
  82703. defines.push("#define ALPHATEST");
  82704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82705. alphaTexture.coordinatesIndex === 1) {
  82706. defines.push("#define DIFFUSEUV2");
  82707. uv2 = true;
  82708. }
  82709. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82710. defines.push("#define DIFFUSEUV1");
  82711. uv1 = true;
  82712. }
  82713. }
  82714. }
  82715. // Emissive
  82716. if (emissiveTexture) {
  82717. defines.push("#define EMISSIVE");
  82718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82719. emissiveTexture.coordinatesIndex === 1) {
  82720. defines.push("#define EMISSIVEUV2");
  82721. uv2 = true;
  82722. }
  82723. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82724. defines.push("#define EMISSIVEUV1");
  82725. uv1 = true;
  82726. }
  82727. }
  82728. if (uv1) {
  82729. attribs.push(BABYLON.VertexBuffer.UVKind);
  82730. defines.push("#define UV1");
  82731. }
  82732. if (uv2) {
  82733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82734. defines.push("#define UV2");
  82735. }
  82736. // Bones
  82737. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82738. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82739. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82740. if (mesh.numBoneInfluencers > 4) {
  82741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82743. }
  82744. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82745. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82746. }
  82747. else {
  82748. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82749. }
  82750. // Instances
  82751. if (useInstances) {
  82752. defines.push("#define INSTANCES");
  82753. attribs.push("world0");
  82754. attribs.push("world1");
  82755. attribs.push("world2");
  82756. attribs.push("world3");
  82757. }
  82758. // Get correct effect
  82759. var join = defines.join("\n");
  82760. if (this._cachedDefines !== join) {
  82761. this._cachedDefines = join;
  82762. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82763. }
  82764. return this._effectLayerMapGenerationEffect.isReady();
  82765. };
  82766. /**
  82767. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82768. */
  82769. EffectLayer.prototype.render = function () {
  82770. var currentEffect = this._mergeEffect;
  82771. // Check
  82772. if (!currentEffect.isReady())
  82773. return;
  82774. for (var i = 0; i < this._postProcesses.length; i++) {
  82775. if (!this._postProcesses[i].isReady()) {
  82776. return;
  82777. }
  82778. }
  82779. var engine = this._scene.getEngine();
  82780. this.onBeforeComposeObservable.notifyObservers(this);
  82781. // Render
  82782. engine.enableEffect(currentEffect);
  82783. engine.setState(false);
  82784. // VBOs
  82785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82786. // Cache
  82787. var previousAlphaMode = engine.getAlphaMode();
  82788. // Go Blend.
  82789. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82790. // Blends the map on the main canvas.
  82791. this._internalRender(currentEffect);
  82792. // Restore Alpha
  82793. engine.setAlphaMode(previousAlphaMode);
  82794. this.onAfterComposeObservable.notifyObservers(this);
  82795. // Handle size changes.
  82796. var size = this._mainTexture.getSize();
  82797. this._setMainTextureSize();
  82798. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82799. // Recreate RTT and post processes on size change.
  82800. this.onSizeChangedObservable.notifyObservers(this);
  82801. this._disposeTextureAndPostProcesses();
  82802. this._createMainTexture();
  82803. this._createTextureAndPostProcesses();
  82804. }
  82805. };
  82806. /**
  82807. * Determine if a given mesh will be used in the current effect.
  82808. * @param mesh mesh to test
  82809. * @returns true if the mesh will be used
  82810. */
  82811. EffectLayer.prototype.hasMesh = function (mesh) {
  82812. return true;
  82813. };
  82814. /**
  82815. * Returns true if the layer contains information to display, otherwise false.
  82816. * @returns true if the glow layer should be rendered
  82817. */
  82818. EffectLayer.prototype.shouldRender = function () {
  82819. return this.isEnabled && this._shouldRender;
  82820. };
  82821. /**
  82822. * Returns true if the mesh should render, otherwise false.
  82823. * @param mesh The mesh to render
  82824. * @returns true if it should render otherwise false
  82825. */
  82826. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82827. return true;
  82828. };
  82829. /**
  82830. * Returns true if the mesh should render, otherwise false.
  82831. * @param mesh The mesh to render
  82832. * @returns true if it should render otherwise false
  82833. */
  82834. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82835. return true;
  82836. };
  82837. /**
  82838. * Renders the submesh passed in parameter to the generation map.
  82839. */
  82840. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82841. var _this = this;
  82842. if (!this.shouldRender()) {
  82843. return;
  82844. }
  82845. var material = subMesh.getMaterial();
  82846. var mesh = subMesh.getRenderingMesh();
  82847. var scene = this._scene;
  82848. var engine = scene.getEngine();
  82849. if (!material) {
  82850. return;
  82851. }
  82852. // Do not block in blend mode.
  82853. if (material.needAlphaBlendingForMesh(mesh)) {
  82854. return;
  82855. }
  82856. // Culling
  82857. engine.setState(material.backFaceCulling);
  82858. // Managing instances
  82859. var batch = mesh._getInstancesRenderList(subMesh._id);
  82860. if (batch.mustReturn) {
  82861. return;
  82862. }
  82863. // Early Exit per mesh
  82864. if (!this._shouldRenderMesh(mesh)) {
  82865. return;
  82866. }
  82867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82868. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82869. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82870. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82871. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82872. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82873. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82874. // Alpha test
  82875. if (material && material.needAlphaTesting()) {
  82876. var alphaTexture = material.getAlphaTestTexture();
  82877. if (alphaTexture) {
  82878. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82879. var textureMatrix = alphaTexture.getTextureMatrix();
  82880. if (textureMatrix) {
  82881. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82882. }
  82883. }
  82884. }
  82885. // Glow emissive only
  82886. if (this._emissiveTextureAndColor.texture) {
  82887. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82888. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82889. }
  82890. // Bones
  82891. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82892. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82893. }
  82894. // Draw
  82895. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82896. }
  82897. else {
  82898. // Need to reset refresh rate of the shadowMap
  82899. this._mainTexture.resetRefreshCounter();
  82900. }
  82901. };
  82902. /**
  82903. * Rebuild the required buffers.
  82904. * @ignore Internal use only.
  82905. */
  82906. EffectLayer.prototype._rebuild = function () {
  82907. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82908. if (vb) {
  82909. vb._rebuild();
  82910. }
  82911. this._generateIndexBuffer();
  82912. };
  82913. /**
  82914. * Dispose only the render target textures and post process.
  82915. */
  82916. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82917. this._mainTexture.dispose();
  82918. for (var i = 0; i < this._postProcesses.length; i++) {
  82919. if (this._postProcesses[i]) {
  82920. this._postProcesses[i].dispose();
  82921. }
  82922. }
  82923. this._postProcesses = [];
  82924. for (var i = 0; i < this._textures.length; i++) {
  82925. if (this._textures[i]) {
  82926. this._textures[i].dispose();
  82927. }
  82928. }
  82929. this._textures = [];
  82930. };
  82931. /**
  82932. * Dispose the highlight layer and free resources.
  82933. */
  82934. EffectLayer.prototype.dispose = function () {
  82935. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82936. if (vertexBuffer) {
  82937. vertexBuffer.dispose();
  82938. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82939. }
  82940. if (this._indexBuffer) {
  82941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82942. this._indexBuffer = null;
  82943. }
  82944. // Clean textures and post processes
  82945. this._disposeTextureAndPostProcesses();
  82946. // Remove from scene
  82947. var index = this._scene.effectLayers.indexOf(this, 0);
  82948. if (index > -1) {
  82949. this._scene.effectLayers.splice(index, 1);
  82950. }
  82951. // Callback
  82952. this.onDisposeObservable.notifyObservers(this);
  82953. this.onDisposeObservable.clear();
  82954. this.onBeforeRenderMainTextureObservable.clear();
  82955. this.onBeforeComposeObservable.clear();
  82956. this.onAfterComposeObservable.clear();
  82957. this.onSizeChangedObservable.clear();
  82958. };
  82959. return EffectLayer;
  82960. }());
  82961. BABYLON.EffectLayer = EffectLayer;
  82962. })(BABYLON || (BABYLON = {}));
  82963. //# sourceMappingURL=babylon.effectLayer.js.map
  82964. var BABYLON;
  82965. (function (BABYLON) {
  82966. /**
  82967. * Special Glow Blur post process only blurring the alpha channel
  82968. * It enforces keeping the most luminous color in the color channel.
  82969. */
  82970. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82971. __extends(GlowBlurPostProcess, _super);
  82972. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82974. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82975. _this.direction = direction;
  82976. _this.kernel = kernel;
  82977. _this.onApplyObservable.add(function (effect) {
  82978. effect.setFloat2("screenSize", _this.width, _this.height);
  82979. effect.setVector2("direction", _this.direction);
  82980. effect.setFloat("blurWidth", _this.kernel);
  82981. });
  82982. return _this;
  82983. }
  82984. return GlowBlurPostProcess;
  82985. }(BABYLON.PostProcess));
  82986. /**
  82987. * The highlight layer Helps adding a glow effect around a mesh.
  82988. *
  82989. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82990. * glowy meshes to your scene.
  82991. *
  82992. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82993. */
  82994. var HighlightLayer = /** @class */ (function (_super) {
  82995. __extends(HighlightLayer, _super);
  82996. /**
  82997. * Instantiates a new highlight Layer and references it to the scene..
  82998. * @param name The name of the layer
  82999. * @param scene The scene to use the layer in
  83000. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  83001. */
  83002. function HighlightLayer(name, scene, options) {
  83003. var _this = _super.call(this, name, scene) || this;
  83004. _this.name = name;
  83005. /**
  83006. * Specifies whether or not the inner glow is ACTIVE in the layer.
  83007. */
  83008. _this.innerGlow = true;
  83009. /**
  83010. * Specifies whether or not the outer glow is ACTIVE in the layer.
  83011. */
  83012. _this.outerGlow = true;
  83013. /**
  83014. * An event triggered when the highlight layer is being blurred.
  83015. */
  83016. _this.onBeforeBlurObservable = new BABYLON.Observable();
  83017. /**
  83018. * An event triggered when the highlight layer has been blurred.
  83019. */
  83020. _this.onAfterBlurObservable = new BABYLON.Observable();
  83021. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  83022. _this._meshes = {};
  83023. _this._excludedMeshes = {};
  83024. _this.neutralColor = HighlightLayer.NeutralColor;
  83025. // Warn on stencil
  83026. if (!_this._engine.isStencilEnable) {
  83027. 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 }");
  83028. }
  83029. // Adapt options
  83030. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83031. // Initialize the layer
  83032. _this._init({
  83033. alphaBlendingMode: _this._options.alphaBlendingMode,
  83034. camera: _this._options.camera,
  83035. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83036. mainTextureRatio: _this._options.mainTextureRatio
  83037. });
  83038. // Do not render as long as no meshes have been added
  83039. _this._shouldRender = false;
  83040. return _this;
  83041. }
  83042. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  83043. /**
  83044. * Gets the horizontal size of the blur.
  83045. */
  83046. get: function () {
  83047. return this._horizontalBlurPostprocess.kernel;
  83048. },
  83049. /**
  83050. * Specifies the horizontal size of the blur.
  83051. */
  83052. set: function (value) {
  83053. this._horizontalBlurPostprocess.kernel = value;
  83054. },
  83055. enumerable: true,
  83056. configurable: true
  83057. });
  83058. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  83059. /**
  83060. * Gets the vertical size of the blur.
  83061. */
  83062. get: function () {
  83063. return this._verticalBlurPostprocess.kernel;
  83064. },
  83065. /**
  83066. * Specifies the vertical size of the blur.
  83067. */
  83068. set: function (value) {
  83069. this._verticalBlurPostprocess.kernel = value;
  83070. },
  83071. enumerable: true,
  83072. configurable: true
  83073. });
  83074. /**
  83075. * Get the effect name of the layer.
  83076. * @return The effect name
  83077. */
  83078. HighlightLayer.prototype.getEffectName = function () {
  83079. return HighlightLayer.EffectName;
  83080. };
  83081. /**
  83082. * Create the merge effect. This is the shader use to blit the information back
  83083. * to the main canvas at the end of the scene rendering.
  83084. */
  83085. HighlightLayer.prototype._createMergeEffect = function () {
  83086. // Effect
  83087. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  83088. };
  83089. /**
  83090. * Creates the render target textures and post processes used in the highlight layer.
  83091. */
  83092. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  83093. var _this = this;
  83094. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  83095. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  83096. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83097. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83098. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  83099. width: blurTextureWidth,
  83100. height: blurTextureHeight
  83101. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83102. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83103. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83104. this._blurTexture.anisotropicFilteringLevel = 16;
  83105. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83106. this._blurTexture.renderParticles = false;
  83107. this._blurTexture.ignoreCameraViewport = true;
  83108. this._textures = [this._blurTexture];
  83109. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83110. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83111. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83112. effect.setTexture("textureSampler", _this._mainTexture);
  83113. });
  83114. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83115. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83116. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83117. });
  83118. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83119. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83120. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83121. });
  83122. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83123. }
  83124. else {
  83125. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83126. width: blurTextureWidth,
  83127. height: blurTextureHeight
  83128. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83129. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83130. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83131. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83132. effect.setTexture("textureSampler", _this._mainTexture);
  83133. });
  83134. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83135. width: blurTextureWidth,
  83136. height: blurTextureHeight
  83137. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83138. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83139. }
  83140. this._mainTexture.onAfterUnbindObservable.add(function () {
  83141. _this.onBeforeBlurObservable.notifyObservers(_this);
  83142. var internalTexture = _this._blurTexture.getInternalTexture();
  83143. if (internalTexture) {
  83144. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83145. }
  83146. _this.onAfterBlurObservable.notifyObservers(_this);
  83147. });
  83148. // Prevent autoClear.
  83149. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83150. };
  83151. /**
  83152. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83153. */
  83154. HighlightLayer.prototype.needStencil = function () {
  83155. return true;
  83156. };
  83157. /**
  83158. * Checks for the readiness of the element composing the layer.
  83159. * @param subMesh the mesh to check for
  83160. * @param useInstances specify wether or not to use instances to render the mesh
  83161. * @param emissiveTexture the associated emissive texture used to generate the glow
  83162. * @return true if ready otherwise, false
  83163. */
  83164. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83165. var material = subMesh.getMaterial();
  83166. var mesh = subMesh.getRenderingMesh();
  83167. if (!material || !mesh || !this._meshes) {
  83168. return false;
  83169. }
  83170. var emissiveTexture = null;
  83171. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83172. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83173. emissiveTexture = material.emissiveTexture;
  83174. }
  83175. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83176. };
  83177. /**
  83178. * Implementation specific of rendering the generating effect on the main canvas.
  83179. * @param effect The effect used to render through
  83180. */
  83181. HighlightLayer.prototype._internalRender = function (effect) {
  83182. // Texture
  83183. effect.setTexture("textureSampler", this._blurTexture);
  83184. // Cache
  83185. var engine = this._engine;
  83186. var previousStencilBuffer = engine.getStencilBuffer();
  83187. var previousStencilFunction = engine.getStencilFunction();
  83188. var previousStencilMask = engine.getStencilMask();
  83189. var previousStencilOperationPass = engine.getStencilOperationPass();
  83190. var previousStencilOperationFail = engine.getStencilOperationFail();
  83191. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83192. var previousStencilReference = engine.getStencilFunctionReference();
  83193. // Stencil operations
  83194. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83195. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83196. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83197. // Draw order
  83198. engine.setStencilMask(0x00);
  83199. engine.setStencilBuffer(true);
  83200. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83201. // 2 passes inner outer
  83202. if (this.outerGlow) {
  83203. effect.setFloat("offset", 0);
  83204. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83205. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83206. }
  83207. if (this.innerGlow) {
  83208. effect.setFloat("offset", 1);
  83209. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83210. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83211. }
  83212. // Restore Cache
  83213. engine.setStencilFunction(previousStencilFunction);
  83214. engine.setStencilMask(previousStencilMask);
  83215. engine.setStencilBuffer(previousStencilBuffer);
  83216. engine.setStencilOperationPass(previousStencilOperationPass);
  83217. engine.setStencilOperationFail(previousStencilOperationFail);
  83218. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83219. engine.setStencilFunctionReference(previousStencilReference);
  83220. };
  83221. /**
  83222. * Returns true if the layer contains information to display, otherwise false.
  83223. */
  83224. HighlightLayer.prototype.shouldRender = function () {
  83225. if (_super.prototype.shouldRender.call(this)) {
  83226. return this._meshes ? true : false;
  83227. }
  83228. return false;
  83229. };
  83230. /**
  83231. * Returns true if the mesh should render, otherwise false.
  83232. * @param mesh The mesh to render
  83233. * @returns true if it should render otherwise false
  83234. */
  83235. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83236. // Excluded Mesh
  83237. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83238. return false;
  83239. }
  83240. ;
  83241. return true;
  83242. };
  83243. /**
  83244. * Sets the required values for both the emissive texture and and the main color.
  83245. */
  83246. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83247. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83248. if (highlightLayerMesh) {
  83249. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83250. }
  83251. else {
  83252. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83253. }
  83254. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83255. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83256. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83257. }
  83258. else {
  83259. this._emissiveTextureAndColor.texture = null;
  83260. }
  83261. };
  83262. /**
  83263. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83264. * @param mesh The mesh to exclude from the highlight layer
  83265. */
  83266. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83267. if (!this._excludedMeshes) {
  83268. return;
  83269. }
  83270. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83271. if (!meshExcluded) {
  83272. this._excludedMeshes[mesh.uniqueId] = {
  83273. mesh: mesh,
  83274. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83275. mesh.getEngine().setStencilBuffer(false);
  83276. }),
  83277. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83278. mesh.getEngine().setStencilBuffer(true);
  83279. }),
  83280. };
  83281. }
  83282. };
  83283. /**
  83284. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83285. * @param mesh The mesh to highlight
  83286. */
  83287. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83288. if (!this._excludedMeshes) {
  83289. return;
  83290. }
  83291. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83292. if (meshExcluded) {
  83293. if (meshExcluded.beforeRender) {
  83294. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83295. }
  83296. if (meshExcluded.afterRender) {
  83297. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83298. }
  83299. }
  83300. this._excludedMeshes[mesh.uniqueId] = null;
  83301. };
  83302. /**
  83303. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83304. * @param mesh mesh to test
  83305. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83306. */
  83307. HighlightLayer.prototype.hasMesh = function (mesh) {
  83308. if (!this._meshes) {
  83309. return false;
  83310. }
  83311. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83312. };
  83313. /**
  83314. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83315. * @param mesh The mesh to highlight
  83316. * @param color The color of the highlight
  83317. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83318. */
  83319. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83320. var _this = this;
  83321. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83322. if (!this._meshes) {
  83323. return;
  83324. }
  83325. var meshHighlight = this._meshes[mesh.uniqueId];
  83326. if (meshHighlight) {
  83327. meshHighlight.color = color;
  83328. }
  83329. else {
  83330. this._meshes[mesh.uniqueId] = {
  83331. mesh: mesh,
  83332. color: color,
  83333. // Lambda required for capture due to Observable this context
  83334. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83335. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83336. _this._defaultStencilReference(mesh);
  83337. }
  83338. else {
  83339. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83340. }
  83341. }),
  83342. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83343. glowEmissiveOnly: glowEmissiveOnly
  83344. };
  83345. }
  83346. this._shouldRender = true;
  83347. };
  83348. /**
  83349. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83350. * @param mesh The mesh to highlight
  83351. */
  83352. HighlightLayer.prototype.removeMesh = function (mesh) {
  83353. if (!this._meshes) {
  83354. return;
  83355. }
  83356. var meshHighlight = this._meshes[mesh.uniqueId];
  83357. if (meshHighlight) {
  83358. if (meshHighlight.observerHighlight) {
  83359. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83360. }
  83361. if (meshHighlight.observerDefault) {
  83362. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83363. }
  83364. delete this._meshes[mesh.uniqueId];
  83365. }
  83366. this._shouldRender = false;
  83367. for (var meshHighlightToCheck in this._meshes) {
  83368. if (this._meshes[meshHighlightToCheck]) {
  83369. this._shouldRender = true;
  83370. break;
  83371. }
  83372. }
  83373. };
  83374. /**
  83375. * Force the stencil to the normal expected value for none glowing parts
  83376. */
  83377. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83378. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83379. };
  83380. /**
  83381. * Free any resources and references associated to a mesh.
  83382. * Internal use
  83383. * @param mesh The mesh to free.
  83384. */
  83385. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83386. this.removeMesh(mesh);
  83387. this.removeExcludedMesh(mesh);
  83388. };
  83389. /**
  83390. * Dispose the highlight layer and free resources.
  83391. */
  83392. HighlightLayer.prototype.dispose = function () {
  83393. if (this._meshes) {
  83394. // Clean mesh references
  83395. for (var id in this._meshes) {
  83396. var meshHighlight = this._meshes[id];
  83397. if (meshHighlight && meshHighlight.mesh) {
  83398. if (meshHighlight.observerHighlight) {
  83399. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83400. }
  83401. if (meshHighlight.observerDefault) {
  83402. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83403. }
  83404. }
  83405. }
  83406. this._meshes = null;
  83407. }
  83408. if (this._excludedMeshes) {
  83409. for (var id in this._excludedMeshes) {
  83410. var meshHighlight = this._excludedMeshes[id];
  83411. if (meshHighlight) {
  83412. if (meshHighlight.beforeRender) {
  83413. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83414. }
  83415. if (meshHighlight.afterRender) {
  83416. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83417. }
  83418. }
  83419. }
  83420. this._excludedMeshes = null;
  83421. }
  83422. _super.prototype.dispose.call(this);
  83423. };
  83424. /**
  83425. * Effect Name of the highlight layer.
  83426. */
  83427. HighlightLayer.EffectName = "HighlightLayer";
  83428. /**
  83429. * The neutral color used during the preparation of the glow effect.
  83430. * This is black by default as the blend operation is a blend operation.
  83431. */
  83432. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83433. /**
  83434. * Stencil value used for glowing meshes.
  83435. */
  83436. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83437. /**
  83438. * Stencil value used for the other meshes in the scene.
  83439. */
  83440. HighlightLayer.NormalMeshStencilReference = 0x01;
  83441. return HighlightLayer;
  83442. }(BABYLON.EffectLayer));
  83443. BABYLON.HighlightLayer = HighlightLayer;
  83444. })(BABYLON || (BABYLON = {}));
  83445. //# sourceMappingURL=babylon.highlightLayer.js.map
  83446. var BABYLON;
  83447. (function (BABYLON) {
  83448. /**
  83449. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83450. *
  83451. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83452. * glowy meshes to your scene.
  83453. *
  83454. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83455. */
  83456. var GlowLayer = /** @class */ (function (_super) {
  83457. __extends(GlowLayer, _super);
  83458. /**
  83459. * Instantiates a new glow Layer and references it to the scene.
  83460. * @param name The name of the layer
  83461. * @param scene The scene to use the layer in
  83462. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83463. */
  83464. function GlowLayer(name, scene, options) {
  83465. var _this = _super.call(this, name, scene) || this;
  83466. _this.name = name;
  83467. _this._intensity = 1.0;
  83468. _this._includedOnlyMeshes = [];
  83469. _this._excludedMeshes = [];
  83470. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83471. // Adapt options
  83472. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83473. // Initialize the layer
  83474. _this._init({
  83475. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83476. camera: _this._options.camera,
  83477. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83478. mainTextureRatio: _this._options.mainTextureRatio
  83479. });
  83480. return _this;
  83481. }
  83482. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83483. /**
  83484. * Gets the kernel size of the blur.
  83485. */
  83486. get: function () {
  83487. return this._horizontalBlurPostprocess1.kernel;
  83488. },
  83489. /**
  83490. * Sets the kernel size of the blur.
  83491. */
  83492. set: function (value) {
  83493. this._horizontalBlurPostprocess1.kernel = value;
  83494. this._verticalBlurPostprocess1.kernel = value;
  83495. this._horizontalBlurPostprocess2.kernel = value;
  83496. this._verticalBlurPostprocess2.kernel = value;
  83497. },
  83498. enumerable: true,
  83499. configurable: true
  83500. });
  83501. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83502. /**
  83503. * Gets the glow intensity.
  83504. */
  83505. get: function () {
  83506. return this._intensity;
  83507. },
  83508. /**
  83509. * Sets the glow intensity.
  83510. */
  83511. set: function (value) {
  83512. this._intensity = value;
  83513. },
  83514. enumerable: true,
  83515. configurable: true
  83516. });
  83517. /**
  83518. * Get the effect name of the layer.
  83519. * @return The effect name
  83520. */
  83521. GlowLayer.prototype.getEffectName = function () {
  83522. return GlowLayer.EffectName;
  83523. };
  83524. /**
  83525. * Create the merge effect. This is the shader use to blit the information back
  83526. * to the main canvas at the end of the scene rendering.
  83527. */
  83528. GlowLayer.prototype._createMergeEffect = function () {
  83529. // Effect
  83530. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83531. };
  83532. /**
  83533. * Creates the render target textures and post processes used in the glow layer.
  83534. */
  83535. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83536. var _this = this;
  83537. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83538. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83539. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83540. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83541. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83542. width: blurTextureWidth,
  83543. height: blurTextureHeight
  83544. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83545. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83546. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83547. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83548. this._blurTexture1.renderParticles = false;
  83549. this._blurTexture1.ignoreCameraViewport = true;
  83550. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83551. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83552. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83553. width: blurTextureWidth2,
  83554. height: blurTextureHeight2
  83555. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83556. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83557. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83558. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83559. this._blurTexture2.renderParticles = false;
  83560. this._blurTexture2.ignoreCameraViewport = true;
  83561. this._textures = [this._blurTexture1, this._blurTexture2];
  83562. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83563. width: blurTextureWidth,
  83564. height: blurTextureHeight
  83565. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83566. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83567. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83568. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83569. effect.setTexture("textureSampler", _this._mainTexture);
  83570. });
  83571. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83572. width: blurTextureWidth,
  83573. height: blurTextureHeight
  83574. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83575. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83576. width: blurTextureWidth2,
  83577. height: blurTextureHeight2
  83578. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83579. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83580. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83581. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83582. effect.setTexture("textureSampler", _this._blurTexture1);
  83583. });
  83584. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83585. width: blurTextureWidth2,
  83586. height: blurTextureHeight2
  83587. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83588. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83589. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83590. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83591. this._mainTexture.samples = this._options.mainTextureSamples;
  83592. this._mainTexture.onAfterUnbindObservable.add(function () {
  83593. var internalTexture = _this._blurTexture1.getInternalTexture();
  83594. if (internalTexture) {
  83595. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83596. internalTexture = _this._blurTexture2.getInternalTexture();
  83597. if (internalTexture) {
  83598. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83599. }
  83600. }
  83601. });
  83602. // Prevent autoClear.
  83603. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83604. };
  83605. /**
  83606. * Checks for the readiness of the element composing the layer.
  83607. * @param subMesh the mesh to check for
  83608. * @param useInstances specify wether or not to use instances to render the mesh
  83609. * @param emissiveTexture the associated emissive texture used to generate the glow
  83610. * @return true if ready otherwise, false
  83611. */
  83612. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83613. var material = subMesh.getMaterial();
  83614. var mesh = subMesh.getRenderingMesh();
  83615. if (!material || !mesh) {
  83616. return false;
  83617. }
  83618. var emissiveTexture = material.emissiveTexture;
  83619. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83620. };
  83621. /**
  83622. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83623. */
  83624. GlowLayer.prototype.needStencil = function () {
  83625. return false;
  83626. };
  83627. /**
  83628. * Implementation specific of rendering the generating effect on the main canvas.
  83629. * @param effect The effect used to render through
  83630. */
  83631. GlowLayer.prototype._internalRender = function (effect) {
  83632. // Texture
  83633. effect.setTexture("textureSampler", this._blurTexture1);
  83634. effect.setTexture("textureSampler2", this._blurTexture2);
  83635. effect.setFloat("offset", this._intensity);
  83636. // Cache
  83637. var engine = this._engine;
  83638. var previousStencilBuffer = engine.getStencilBuffer();
  83639. // Draw order
  83640. engine.setStencilBuffer(false);
  83641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83642. // Draw order
  83643. engine.setStencilBuffer(previousStencilBuffer);
  83644. };
  83645. /**
  83646. * Sets the required values for both the emissive texture and and the main color.
  83647. */
  83648. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83649. var textureLevel = 1.0;
  83650. if (this.customEmissiveTextureSelector) {
  83651. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83652. }
  83653. else {
  83654. if (material) {
  83655. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83656. if (this._emissiveTextureAndColor.texture) {
  83657. textureLevel = this._emissiveTextureAndColor.texture.level;
  83658. }
  83659. }
  83660. else {
  83661. this._emissiveTextureAndColor.texture = null;
  83662. }
  83663. }
  83664. if (this.customEmissiveColorSelector) {
  83665. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83666. }
  83667. else {
  83668. if (material.emissiveColor) {
  83669. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83670. }
  83671. else {
  83672. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83673. }
  83674. }
  83675. };
  83676. /**
  83677. * Returns true if the mesh should render, otherwise false.
  83678. * @param mesh The mesh to render
  83679. * @returns true if it should render otherwise false
  83680. */
  83681. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83682. return this.hasMesh(mesh);
  83683. };
  83684. /**
  83685. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83686. * @param mesh The mesh to exclude from the glow layer
  83687. */
  83688. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83689. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83690. this._excludedMeshes.push(mesh.uniqueId);
  83691. }
  83692. };
  83693. /**
  83694. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83695. * @param mesh The mesh to remove
  83696. */
  83697. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83698. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83699. if (index !== -1) {
  83700. this._excludedMeshes.splice(index, 1);
  83701. }
  83702. };
  83703. /**
  83704. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83705. * @param mesh The mesh to include in the glow layer
  83706. */
  83707. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83708. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83709. this._includedOnlyMeshes.push(mesh.uniqueId);
  83710. }
  83711. };
  83712. /**
  83713. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83714. * @param mesh The mesh to remove
  83715. */
  83716. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83717. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83718. if (index !== -1) {
  83719. this._includedOnlyMeshes.splice(index, 1);
  83720. }
  83721. };
  83722. /**
  83723. * Determine if a given mesh will be used in the glow layer
  83724. * @param mesh The mesh to test
  83725. * @returns true if the mesh will be highlighted by the current glow layer
  83726. */
  83727. GlowLayer.prototype.hasMesh = function (mesh) {
  83728. // Included Mesh
  83729. if (this._includedOnlyMeshes.length) {
  83730. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83731. }
  83732. ;
  83733. // Excluded Mesh
  83734. if (this._excludedMeshes.length) {
  83735. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83736. }
  83737. ;
  83738. return true;
  83739. };
  83740. /**
  83741. * Free any resources and references associated to a mesh.
  83742. * Internal use
  83743. * @param mesh The mesh to free.
  83744. */
  83745. GlowLayer.prototype._disposeMesh = function (mesh) {
  83746. this.removeIncludedOnlyMesh(mesh);
  83747. this.removeExcludedMesh(mesh);
  83748. };
  83749. /**
  83750. * Effect Name of the layer.
  83751. */
  83752. GlowLayer.EffectName = "GlowLayer";
  83753. /**
  83754. * The default blur kernel size used for the glow.
  83755. */
  83756. GlowLayer.DefaultBlurKernelSize = 32;
  83757. /**
  83758. * The default texture size ratio used for the glow.
  83759. */
  83760. GlowLayer.DefaultTextureRatio = 0.5;
  83761. return GlowLayer;
  83762. }(BABYLON.EffectLayer));
  83763. BABYLON.GlowLayer = GlowLayer;
  83764. })(BABYLON || (BABYLON = {}));
  83765. //# sourceMappingURL=babylon.glowLayer.js.map
  83766. var BABYLON;
  83767. (function (BABYLON) {
  83768. /**
  83769. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83770. */
  83771. var AssetTaskState;
  83772. (function (AssetTaskState) {
  83773. /**
  83774. * Initialization
  83775. */
  83776. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83777. /**
  83778. * Running
  83779. */
  83780. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83781. /**
  83782. * Done
  83783. */
  83784. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83785. /**
  83786. * Error
  83787. */
  83788. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83789. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83790. /**
  83791. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83792. */
  83793. var AbstractAssetTask = /** @class */ (function () {
  83794. /**
  83795. * Creates a new {BABYLON.AssetsManager}
  83796. * @param name defines the name of the task
  83797. */
  83798. function AbstractAssetTask(
  83799. /**
  83800. * Task name
  83801. */ name) {
  83802. this.name = name;
  83803. this._isCompleted = false;
  83804. this._taskState = AssetTaskState.INIT;
  83805. }
  83806. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83807. /**
  83808. * Get if the task is completed
  83809. */
  83810. get: function () {
  83811. return this._isCompleted;
  83812. },
  83813. enumerable: true,
  83814. configurable: true
  83815. });
  83816. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83817. /**
  83818. * Gets the current state of the task
  83819. */
  83820. get: function () {
  83821. return this._taskState;
  83822. },
  83823. enumerable: true,
  83824. configurable: true
  83825. });
  83826. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83827. /**
  83828. * Gets the current error object (if task is in error)
  83829. */
  83830. get: function () {
  83831. return this._errorObject;
  83832. },
  83833. enumerable: true,
  83834. configurable: true
  83835. });
  83836. /**
  83837. * Internal only
  83838. * @ignore
  83839. */
  83840. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83841. if (this._errorObject) {
  83842. return;
  83843. }
  83844. this._errorObject = {
  83845. message: message,
  83846. exception: exception
  83847. };
  83848. };
  83849. /**
  83850. * Execute the current task
  83851. * @param scene defines the scene where you want your assets to be loaded
  83852. * @param onSuccess is a callback called when the task is successfully executed
  83853. * @param onError is a callback called if an error occurs
  83854. */
  83855. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83856. var _this = this;
  83857. this._taskState = AssetTaskState.RUNNING;
  83858. this.runTask(scene, function () {
  83859. _this.onDoneCallback(onSuccess, onError);
  83860. }, function (msg, exception) {
  83861. _this.onErrorCallback(onError, msg, exception);
  83862. });
  83863. };
  83864. /**
  83865. * Execute the current task
  83866. * @param scene defines the scene where you want your assets to be loaded
  83867. * @param onSuccess is a callback called when the task is successfully executed
  83868. * @param onError is a callback called if an error occurs
  83869. */
  83870. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83871. throw new Error("runTask is not implemented");
  83872. };
  83873. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83874. this._taskState = AssetTaskState.ERROR;
  83875. this._errorObject = {
  83876. message: message,
  83877. exception: exception
  83878. };
  83879. if (this.onError) {
  83880. this.onError(this, message, exception);
  83881. }
  83882. onError();
  83883. };
  83884. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83885. try {
  83886. this._taskState = AssetTaskState.DONE;
  83887. this._isCompleted = true;
  83888. if (this.onSuccess) {
  83889. this.onSuccess(this);
  83890. }
  83891. onSuccess();
  83892. }
  83893. catch (e) {
  83894. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83895. }
  83896. };
  83897. return AbstractAssetTask;
  83898. }());
  83899. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83900. /**
  83901. * Class used to share progress information about assets loading
  83902. */
  83903. var AssetsProgressEvent = /** @class */ (function () {
  83904. /**
  83905. * Creates a {BABYLON.AssetsProgressEvent}
  83906. * @param remainingCount defines the number of remaining tasks to process
  83907. * @param totalCount defines the total number of tasks
  83908. * @param task defines the task that was just processed
  83909. */
  83910. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83911. this.remainingCount = remainingCount;
  83912. this.totalCount = totalCount;
  83913. this.task = task;
  83914. }
  83915. return AssetsProgressEvent;
  83916. }());
  83917. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83918. /**
  83919. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83920. */
  83921. var MeshAssetTask = /** @class */ (function (_super) {
  83922. __extends(MeshAssetTask, _super);
  83923. /**
  83924. * Creates a new {BABYLON.MeshAssetTask}
  83925. * @param name defines the name of the task
  83926. * @param meshesNames defines the list of mesh's names you want to load
  83927. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83928. * @param sceneFilename defines the filename of the scene to load from
  83929. */
  83930. function MeshAssetTask(
  83931. /**
  83932. * Defines the name of the task
  83933. */
  83934. name,
  83935. /**
  83936. * Defines the list of mesh's names you want to load
  83937. */
  83938. meshesNames,
  83939. /**
  83940. * Defines the root url to use as a base to load your meshes and associated resources
  83941. */
  83942. rootUrl,
  83943. /**
  83944. * Defines the filename of the scene to load from
  83945. */
  83946. sceneFilename) {
  83947. var _this = _super.call(this, name) || this;
  83948. _this.name = name;
  83949. _this.meshesNames = meshesNames;
  83950. _this.rootUrl = rootUrl;
  83951. _this.sceneFilename = sceneFilename;
  83952. return _this;
  83953. }
  83954. /**
  83955. * Execute the current task
  83956. * @param scene defines the scene where you want your assets to be loaded
  83957. * @param onSuccess is a callback called when the task is successfully executed
  83958. * @param onError is a callback called if an error occurs
  83959. */
  83960. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83961. var _this = this;
  83962. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83963. _this.loadedMeshes = meshes;
  83964. _this.loadedParticleSystems = particleSystems;
  83965. _this.loadedSkeletons = skeletons;
  83966. onSuccess();
  83967. }, null, function (scene, message, exception) {
  83968. onError(message, exception);
  83969. });
  83970. };
  83971. return MeshAssetTask;
  83972. }(AbstractAssetTask));
  83973. BABYLON.MeshAssetTask = MeshAssetTask;
  83974. /**
  83975. * Define a task used by {BABYLON.AssetsManager} to load text content
  83976. */
  83977. var TextFileAssetTask = /** @class */ (function (_super) {
  83978. __extends(TextFileAssetTask, _super);
  83979. /**
  83980. * Creates a new TextFileAssetTask object
  83981. * @param name defines the name of the task
  83982. * @param url defines the location of the file to load
  83983. */
  83984. function TextFileAssetTask(
  83985. /**
  83986. * Defines the name of the task
  83987. */
  83988. name,
  83989. /**
  83990. * Defines the location of the file to load
  83991. */
  83992. url) {
  83993. var _this = _super.call(this, name) || this;
  83994. _this.name = name;
  83995. _this.url = url;
  83996. return _this;
  83997. }
  83998. /**
  83999. * Execute the current task
  84000. * @param scene defines the scene where you want your assets to be loaded
  84001. * @param onSuccess is a callback called when the task is successfully executed
  84002. * @param onError is a callback called if an error occurs
  84003. */
  84004. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84005. var _this = this;
  84006. scene._loadFile(this.url, function (data) {
  84007. _this.text = data;
  84008. onSuccess();
  84009. }, undefined, false, false, function (request, exception) {
  84010. if (request) {
  84011. onError(request.status + " " + request.statusText, exception);
  84012. }
  84013. });
  84014. };
  84015. return TextFileAssetTask;
  84016. }(AbstractAssetTask));
  84017. BABYLON.TextFileAssetTask = TextFileAssetTask;
  84018. /**
  84019. * Define a task used by {BABYLON.AssetsManager} to load binary data
  84020. */
  84021. var BinaryFileAssetTask = /** @class */ (function (_super) {
  84022. __extends(BinaryFileAssetTask, _super);
  84023. /**
  84024. * Creates a new BinaryFileAssetTask object
  84025. * @param name defines the name of the new task
  84026. * @param url defines the location of the file to load
  84027. */
  84028. function BinaryFileAssetTask(
  84029. /**
  84030. * Defines the name of the task
  84031. */
  84032. name,
  84033. /**
  84034. * Defines the location of the file to load
  84035. */
  84036. url) {
  84037. var _this = _super.call(this, name) || this;
  84038. _this.name = name;
  84039. _this.url = url;
  84040. return _this;
  84041. }
  84042. /**
  84043. * Execute the current task
  84044. * @param scene defines the scene where you want your assets to be loaded
  84045. * @param onSuccess is a callback called when the task is successfully executed
  84046. * @param onError is a callback called if an error occurs
  84047. */
  84048. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84049. var _this = this;
  84050. scene._loadFile(this.url, function (data) {
  84051. _this.data = data;
  84052. onSuccess();
  84053. }, undefined, true, true, function (request, exception) {
  84054. if (request) {
  84055. onError(request.status + " " + request.statusText, exception);
  84056. }
  84057. });
  84058. };
  84059. return BinaryFileAssetTask;
  84060. }(AbstractAssetTask));
  84061. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  84062. /**
  84063. * Define a task used by {BABYLON.AssetsManager} to load images
  84064. */
  84065. var ImageAssetTask = /** @class */ (function (_super) {
  84066. __extends(ImageAssetTask, _super);
  84067. /**
  84068. * Creates a new ImageAssetTask
  84069. * @param name defines the name of the task
  84070. * @param url defines the location of the image to load
  84071. */
  84072. function ImageAssetTask(
  84073. /**
  84074. * Defines the name of the task
  84075. */
  84076. name,
  84077. /**
  84078. * Defines the location of the image to load
  84079. */
  84080. url) {
  84081. var _this = _super.call(this, name) || this;
  84082. _this.name = name;
  84083. _this.url = url;
  84084. return _this;
  84085. }
  84086. /**
  84087. * Execute the current task
  84088. * @param scene defines the scene where you want your assets to be loaded
  84089. * @param onSuccess is a callback called when the task is successfully executed
  84090. * @param onError is a callback called if an error occurs
  84091. */
  84092. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84093. var _this = this;
  84094. var img = new Image();
  84095. BABYLON.Tools.SetCorsBehavior(this.url, img);
  84096. img.onload = function () {
  84097. _this.image = img;
  84098. onSuccess();
  84099. };
  84100. img.onerror = function (err) {
  84101. onError("Error loading image", err);
  84102. };
  84103. img.src = this.url;
  84104. };
  84105. return ImageAssetTask;
  84106. }(AbstractAssetTask));
  84107. BABYLON.ImageAssetTask = ImageAssetTask;
  84108. /**
  84109. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84110. */
  84111. var TextureAssetTask = /** @class */ (function (_super) {
  84112. __extends(TextureAssetTask, _super);
  84113. /**
  84114. * Creates a new TextureAssetTask object
  84115. * @param name defines the name of the task
  84116. * @param url defines the location of the file to load
  84117. * @param noMipmap defines if mipmap should not be generated (default is false)
  84118. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84119. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84120. */
  84121. function TextureAssetTask(
  84122. /**
  84123. * Defines the name of the task
  84124. */
  84125. name,
  84126. /**
  84127. * Defines the location of the file to load
  84128. */
  84129. url,
  84130. /**
  84131. * Defines if mipmap should not be generated (default is false)
  84132. */
  84133. noMipmap,
  84134. /**
  84135. * Defines if texture must be inverted on Y axis (default is false)
  84136. */
  84137. invertY,
  84138. /**
  84139. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84140. */
  84141. samplingMode) {
  84142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84143. var _this = _super.call(this, name) || this;
  84144. _this.name = name;
  84145. _this.url = url;
  84146. _this.noMipmap = noMipmap;
  84147. _this.invertY = invertY;
  84148. _this.samplingMode = samplingMode;
  84149. return _this;
  84150. }
  84151. /**
  84152. * Execute the current task
  84153. * @param scene defines the scene where you want your assets to be loaded
  84154. * @param onSuccess is a callback called when the task is successfully executed
  84155. * @param onError is a callback called if an error occurs
  84156. */
  84157. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84158. var onload = function () {
  84159. onSuccess();
  84160. };
  84161. var onerror = function (message, exception) {
  84162. onError(message, exception);
  84163. };
  84164. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84165. };
  84166. return TextureAssetTask;
  84167. }(AbstractAssetTask));
  84168. BABYLON.TextureAssetTask = TextureAssetTask;
  84169. /**
  84170. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84171. */
  84172. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84173. __extends(CubeTextureAssetTask, _super);
  84174. /**
  84175. * Creates a new CubeTextureAssetTask
  84176. * @param name defines the name of the task
  84177. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84178. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84179. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84180. * @param files defines the explicit list of files (undefined by default)
  84181. */
  84182. function CubeTextureAssetTask(
  84183. /**
  84184. * Defines the name of the task
  84185. */
  84186. name,
  84187. /**
  84188. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84189. */
  84190. url,
  84191. /**
  84192. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84193. */
  84194. extensions,
  84195. /**
  84196. * Defines if mipmaps should not be generated (default is false)
  84197. */
  84198. noMipmap,
  84199. /**
  84200. * Defines the explicit list of files (undefined by default)
  84201. */
  84202. files) {
  84203. var _this = _super.call(this, name) || this;
  84204. _this.name = name;
  84205. _this.url = url;
  84206. _this.extensions = extensions;
  84207. _this.noMipmap = noMipmap;
  84208. _this.files = files;
  84209. return _this;
  84210. }
  84211. /**
  84212. * Execute the current task
  84213. * @param scene defines the scene where you want your assets to be loaded
  84214. * @param onSuccess is a callback called when the task is successfully executed
  84215. * @param onError is a callback called if an error occurs
  84216. */
  84217. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84218. var onload = function () {
  84219. onSuccess();
  84220. };
  84221. var onerror = function (message, exception) {
  84222. onError(message, exception);
  84223. };
  84224. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84225. };
  84226. return CubeTextureAssetTask;
  84227. }(AbstractAssetTask));
  84228. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84229. /**
  84230. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84231. */
  84232. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84233. __extends(HDRCubeTextureAssetTask, _super);
  84234. /**
  84235. * Creates a new HDRCubeTextureAssetTask object
  84236. * @param name defines the name of the task
  84237. * @param url defines the location of the file to load
  84238. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  84239. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84240. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84241. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  84242. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84243. */
  84244. function HDRCubeTextureAssetTask(
  84245. /**
  84246. * Defines the name of the task
  84247. */
  84248. name,
  84249. /**
  84250. * Defines the location of the file to load
  84251. */
  84252. url,
  84253. /**
  84254. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  84255. */
  84256. size,
  84257. /**
  84258. * Defines if mipmaps should not be generated (default is false)
  84259. */
  84260. noMipmap,
  84261. /**
  84262. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84263. */
  84264. generateHarmonics,
  84265. /**
  84266. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  84267. */
  84268. useInGammaSpace,
  84269. /**
  84270. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84271. */
  84272. usePMREMGenerator) {
  84273. if (noMipmap === void 0) { noMipmap = false; }
  84274. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84275. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84276. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84277. var _this = _super.call(this, name) || this;
  84278. _this.name = name;
  84279. _this.url = url;
  84280. _this.size = size;
  84281. _this.noMipmap = noMipmap;
  84282. _this.generateHarmonics = generateHarmonics;
  84283. _this.useInGammaSpace = useInGammaSpace;
  84284. _this.usePMREMGenerator = usePMREMGenerator;
  84285. return _this;
  84286. }
  84287. /**
  84288. * Execute the current task
  84289. * @param scene defines the scene where you want your assets to be loaded
  84290. * @param onSuccess is a callback called when the task is successfully executed
  84291. * @param onError is a callback called if an error occurs
  84292. */
  84293. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84294. var onload = function () {
  84295. onSuccess();
  84296. };
  84297. var onerror = function (message, exception) {
  84298. onError(message, exception);
  84299. };
  84300. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84301. };
  84302. return HDRCubeTextureAssetTask;
  84303. }(AbstractAssetTask));
  84304. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84305. /**
  84306. * This class can be used to easily import assets into a scene
  84307. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84308. */
  84309. var AssetsManager = /** @class */ (function () {
  84310. /**
  84311. * Creates a new AssetsManager
  84312. * @param scene defines the scene to work on
  84313. */
  84314. function AssetsManager(scene) {
  84315. this._isLoading = false;
  84316. this._tasks = new Array();
  84317. this._waitingTasksCount = 0;
  84318. this._totalTasksCount = 0;
  84319. /**
  84320. * Observable called when all tasks are processed
  84321. */
  84322. this.onTaskSuccessObservable = new BABYLON.Observable();
  84323. /**
  84324. * Observable called when a task had an error
  84325. */
  84326. this.onTaskErrorObservable = new BABYLON.Observable();
  84327. /**
  84328. * Observable called when a task is successful
  84329. */
  84330. this.onTasksDoneObservable = new BABYLON.Observable();
  84331. /**
  84332. * Observable called when a task is done (whatever the result is)
  84333. */
  84334. this.onProgressObservable = new BABYLON.Observable();
  84335. /**
  84336. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84337. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84338. */
  84339. this.useDefaultLoadingScreen = true;
  84340. this._scene = scene;
  84341. }
  84342. /**
  84343. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84344. * @param taskName defines the name of the new task
  84345. * @param meshesNames defines the name of meshes to load
  84346. * @param rootUrl defines the root url to use to locate files
  84347. * @param sceneFilename defines the filename of the scene file
  84348. * @returns a new {BABYLON.MeshAssetTask} object
  84349. */
  84350. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84351. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84352. this._tasks.push(task);
  84353. return task;
  84354. };
  84355. /**
  84356. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84357. * @param taskName defines the name of the new task
  84358. * @param url defines the url of the file to load
  84359. * @returns a new {BABYLON.TextFileAssetTask} object
  84360. */
  84361. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84362. var task = new TextFileAssetTask(taskName, url);
  84363. this._tasks.push(task);
  84364. return task;
  84365. };
  84366. /**
  84367. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84368. * @param taskName defines the name of the new task
  84369. * @param url defines the url of the file to load
  84370. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84371. */
  84372. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84373. var task = new BinaryFileAssetTask(taskName, url);
  84374. this._tasks.push(task);
  84375. return task;
  84376. };
  84377. /**
  84378. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84379. * @param taskName defines the name of the new task
  84380. * @param url defines the url of the file to load
  84381. * @returns a new {BABYLON.ImageAssetTask} object
  84382. */
  84383. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84384. var task = new ImageAssetTask(taskName, url);
  84385. this._tasks.push(task);
  84386. return task;
  84387. };
  84388. /**
  84389. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84390. * @param taskName defines the name of the new task
  84391. * @param url defines the url of the file to load
  84392. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84393. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84394. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84395. * @returns a new {BABYLON.TextureAssetTask} object
  84396. */
  84397. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84399. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84400. this._tasks.push(task);
  84401. return task;
  84402. };
  84403. /**
  84404. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84405. * @param taskName defines the name of the new task
  84406. * @param url defines the url of the file to load
  84407. * @param extensions defines the extension to use to load the cube map (can be null)
  84408. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84409. * @param files defines the list of files to load (can be null)
  84410. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84411. */
  84412. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84413. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84414. this._tasks.push(task);
  84415. return task;
  84416. };
  84417. /**
  84418. *
  84419. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84420. * @param taskName defines the name of the new task
  84421. * @param url defines the url of the file to load
  84422. * @param size defines the size you want for the cubemap (can be null)
  84423. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84424. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84425. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84426. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84427. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84428. */
  84429. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84430. if (noMipmap === void 0) { noMipmap = false; }
  84431. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84432. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84433. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84434. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84435. this._tasks.push(task);
  84436. return task;
  84437. };
  84438. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84439. var _this = this;
  84440. this._waitingTasksCount--;
  84441. try {
  84442. if (task.taskState === AssetTaskState.DONE) {
  84443. // Let's remove successfull tasks
  84444. BABYLON.Tools.SetImmediate(function () {
  84445. var index = _this._tasks.indexOf(task);
  84446. if (index > -1) {
  84447. _this._tasks.splice(index, 1);
  84448. }
  84449. });
  84450. }
  84451. if (this.onProgress) {
  84452. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84453. }
  84454. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84455. }
  84456. catch (e) {
  84457. BABYLON.Tools.Error("Error running progress callbacks.");
  84458. console.log(e);
  84459. }
  84460. if (this._waitingTasksCount === 0) {
  84461. try {
  84462. if (this.onFinish) {
  84463. this.onFinish(this._tasks);
  84464. }
  84465. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84466. }
  84467. catch (e) {
  84468. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84469. console.log(e);
  84470. }
  84471. this._isLoading = false;
  84472. this._scene.getEngine().hideLoadingUI();
  84473. }
  84474. };
  84475. AssetsManager.prototype._runTask = function (task) {
  84476. var _this = this;
  84477. var done = function () {
  84478. try {
  84479. if (_this.onTaskSuccess) {
  84480. _this.onTaskSuccess(task);
  84481. }
  84482. _this.onTaskSuccessObservable.notifyObservers(task);
  84483. _this._decreaseWaitingTasksCount(task);
  84484. }
  84485. catch (e) {
  84486. error("Error executing task success callbacks", e);
  84487. }
  84488. };
  84489. var error = function (message, exception) {
  84490. task._setErrorObject(message, exception);
  84491. if (_this.onTaskError) {
  84492. _this.onTaskError(task);
  84493. }
  84494. _this.onTaskErrorObservable.notifyObservers(task);
  84495. _this._decreaseWaitingTasksCount(task);
  84496. };
  84497. task.run(this._scene, done, error);
  84498. };
  84499. /**
  84500. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84501. * @return the current instance of the {BABYLON.AssetsManager}
  84502. */
  84503. AssetsManager.prototype.reset = function () {
  84504. this._isLoading = false;
  84505. this._tasks = new Array();
  84506. return this;
  84507. };
  84508. /**
  84509. * Start the loading process
  84510. * @return the current instance of the {BABYLON.AssetsManager}
  84511. */
  84512. AssetsManager.prototype.load = function () {
  84513. if (this._isLoading) {
  84514. return this;
  84515. }
  84516. this._isLoading = true;
  84517. this._waitingTasksCount = this._tasks.length;
  84518. this._totalTasksCount = this._tasks.length;
  84519. if (this._waitingTasksCount === 0) {
  84520. this._isLoading = false;
  84521. if (this.onFinish) {
  84522. this.onFinish(this._tasks);
  84523. }
  84524. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84525. return this;
  84526. }
  84527. if (this.useDefaultLoadingScreen) {
  84528. this._scene.getEngine().displayLoadingUI();
  84529. }
  84530. for (var index = 0; index < this._tasks.length; index++) {
  84531. var task = this._tasks[index];
  84532. this._runTask(task);
  84533. }
  84534. return this;
  84535. };
  84536. return AssetsManager;
  84537. }());
  84538. BABYLON.AssetsManager = AssetsManager;
  84539. })(BABYLON || (BABYLON = {}));
  84540. //# sourceMappingURL=babylon.assetsManager.js.map
  84541. var BABYLON;
  84542. (function (BABYLON) {
  84543. var serializedGeometries = [];
  84544. var serializeGeometry = function (geometry, serializationGeometries) {
  84545. if (serializedGeometries[geometry.id]) {
  84546. return;
  84547. }
  84548. if (geometry.doNotSerialize) {
  84549. return;
  84550. }
  84551. if (geometry instanceof BABYLON.BoxGeometry) {
  84552. serializationGeometries.boxes.push(geometry.serialize());
  84553. }
  84554. else if (geometry instanceof BABYLON.SphereGeometry) {
  84555. serializationGeometries.spheres.push(geometry.serialize());
  84556. }
  84557. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84558. serializationGeometries.cylinders.push(geometry.serialize());
  84559. }
  84560. else if (geometry instanceof BABYLON.TorusGeometry) {
  84561. serializationGeometries.toruses.push(geometry.serialize());
  84562. }
  84563. else if (geometry instanceof BABYLON.GroundGeometry) {
  84564. serializationGeometries.grounds.push(geometry.serialize());
  84565. }
  84566. else if (geometry instanceof BABYLON.Plane) {
  84567. serializationGeometries.planes.push(geometry.serialize());
  84568. }
  84569. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84570. serializationGeometries.torusKnots.push(geometry.serialize());
  84571. }
  84572. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84573. throw new Error("Unknown primitive type");
  84574. }
  84575. else {
  84576. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84577. }
  84578. serializedGeometries[geometry.id] = true;
  84579. };
  84580. var serializeMesh = function (mesh, serializationScene) {
  84581. var serializationObject = {};
  84582. // Geometry
  84583. var geometry = mesh._geometry;
  84584. if (geometry) {
  84585. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84586. // 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
  84587. serializeGeometry(geometry, serializationScene.geometries);
  84588. }
  84589. }
  84590. // Custom
  84591. if (mesh.serialize) {
  84592. mesh.serialize(serializationObject);
  84593. }
  84594. return serializationObject;
  84595. };
  84596. var finalizeSingleMesh = function (mesh, serializationObject) {
  84597. //only works if the mesh is already loaded
  84598. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84599. //serialize material
  84600. if (mesh.material) {
  84601. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84602. serializationObject.materials = serializationObject.materials || [];
  84603. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84604. serializationObject.materials.push(mesh.material.serialize());
  84605. }
  84606. }
  84607. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84608. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84609. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84610. serializationObject.multiMaterials.push(mesh.material.serialize());
  84611. }
  84612. }
  84613. }
  84614. //serialize geometry
  84615. var geometry = mesh._geometry;
  84616. if (geometry) {
  84617. if (!serializationObject.geometries) {
  84618. serializationObject.geometries = {};
  84619. serializationObject.geometries.boxes = [];
  84620. serializationObject.geometries.spheres = [];
  84621. serializationObject.geometries.cylinders = [];
  84622. serializationObject.geometries.toruses = [];
  84623. serializationObject.geometries.grounds = [];
  84624. serializationObject.geometries.planes = [];
  84625. serializationObject.geometries.torusKnots = [];
  84626. serializationObject.geometries.vertexData = [];
  84627. }
  84628. serializeGeometry(geometry, serializationObject.geometries);
  84629. }
  84630. // Skeletons
  84631. if (mesh.skeleton) {
  84632. serializationObject.skeletons = serializationObject.skeletons || [];
  84633. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84634. }
  84635. //serialize the actual mesh
  84636. serializationObject.meshes = serializationObject.meshes || [];
  84637. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84638. }
  84639. };
  84640. var SceneSerializer = /** @class */ (function () {
  84641. function SceneSerializer() {
  84642. }
  84643. SceneSerializer.ClearCache = function () {
  84644. serializedGeometries = [];
  84645. };
  84646. SceneSerializer.Serialize = function (scene) {
  84647. var serializationObject = {};
  84648. SceneSerializer.ClearCache();
  84649. // Scene
  84650. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84651. serializationObject.autoClear = scene.autoClear;
  84652. serializationObject.clearColor = scene.clearColor.asArray();
  84653. serializationObject.ambientColor = scene.ambientColor.asArray();
  84654. serializationObject.gravity = scene.gravity.asArray();
  84655. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84656. serializationObject.workerCollisions = scene.workerCollisions;
  84657. // Fog
  84658. if (scene.fogMode && scene.fogMode !== 0) {
  84659. serializationObject.fogMode = scene.fogMode;
  84660. serializationObject.fogColor = scene.fogColor.asArray();
  84661. serializationObject.fogStart = scene.fogStart;
  84662. serializationObject.fogEnd = scene.fogEnd;
  84663. serializationObject.fogDensity = scene.fogDensity;
  84664. }
  84665. //Physics
  84666. if (scene.isPhysicsEnabled()) {
  84667. var physicEngine = scene.getPhysicsEngine();
  84668. if (physicEngine) {
  84669. serializationObject.physicsEnabled = true;
  84670. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84671. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84672. }
  84673. }
  84674. // Metadata
  84675. if (scene.metadata) {
  84676. serializationObject.metadata = scene.metadata;
  84677. }
  84678. // Morph targets
  84679. serializationObject.morphTargetManagers = [];
  84680. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84681. var abstractMesh = _a[_i];
  84682. var manager = abstractMesh.morphTargetManager;
  84683. if (manager) {
  84684. serializationObject.morphTargetManagers.push(manager.serialize());
  84685. }
  84686. }
  84687. // Lights
  84688. serializationObject.lights = [];
  84689. var index;
  84690. var light;
  84691. for (index = 0; index < scene.lights.length; index++) {
  84692. light = scene.lights[index];
  84693. if (!light.doNotSerialize) {
  84694. serializationObject.lights.push(light.serialize());
  84695. }
  84696. }
  84697. // Cameras
  84698. serializationObject.cameras = [];
  84699. for (index = 0; index < scene.cameras.length; index++) {
  84700. var camera = scene.cameras[index];
  84701. if (!camera.doNotSerialize) {
  84702. serializationObject.cameras.push(camera.serialize());
  84703. }
  84704. }
  84705. if (scene.activeCamera) {
  84706. serializationObject.activeCameraID = scene.activeCamera.id;
  84707. }
  84708. // Animations
  84709. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84710. // Materials
  84711. serializationObject.materials = [];
  84712. serializationObject.multiMaterials = [];
  84713. var material;
  84714. for (index = 0; index < scene.materials.length; index++) {
  84715. material = scene.materials[index];
  84716. if (!material.doNotSerialize) {
  84717. serializationObject.materials.push(material.serialize());
  84718. }
  84719. }
  84720. // MultiMaterials
  84721. serializationObject.multiMaterials = [];
  84722. for (index = 0; index < scene.multiMaterials.length; index++) {
  84723. var multiMaterial = scene.multiMaterials[index];
  84724. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84725. }
  84726. // Environment texture
  84727. if (scene.environmentTexture) {
  84728. serializationObject.environmentTexture = scene.environmentTexture.name;
  84729. }
  84730. // Skeletons
  84731. serializationObject.skeletons = [];
  84732. for (index = 0; index < scene.skeletons.length; index++) {
  84733. var skeleton = scene.skeletons[index];
  84734. if (!skeleton.doNotSerialize) {
  84735. serializationObject.skeletons.push(skeleton.serialize());
  84736. }
  84737. }
  84738. // Transform nodes
  84739. serializationObject.transformNodes = [];
  84740. for (index = 0; index < scene.transformNodes.length; index++) {
  84741. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84742. }
  84743. // Geometries
  84744. serializationObject.geometries = {};
  84745. serializationObject.geometries.boxes = [];
  84746. serializationObject.geometries.spheres = [];
  84747. serializationObject.geometries.cylinders = [];
  84748. serializationObject.geometries.toruses = [];
  84749. serializationObject.geometries.grounds = [];
  84750. serializationObject.geometries.planes = [];
  84751. serializationObject.geometries.torusKnots = [];
  84752. serializationObject.geometries.vertexData = [];
  84753. serializedGeometries = [];
  84754. var geometries = scene.getGeometries();
  84755. for (index = 0; index < geometries.length; index++) {
  84756. var geometry = geometries[index];
  84757. if (geometry.isReady()) {
  84758. serializeGeometry(geometry, serializationObject.geometries);
  84759. }
  84760. }
  84761. // Meshes
  84762. serializationObject.meshes = [];
  84763. for (index = 0; index < scene.meshes.length; index++) {
  84764. var abstractMesh = scene.meshes[index];
  84765. if (abstractMesh instanceof BABYLON.Mesh) {
  84766. var mesh = abstractMesh;
  84767. if (!mesh.doNotSerialize) {
  84768. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84769. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84770. }
  84771. }
  84772. }
  84773. }
  84774. // Particles Systems
  84775. serializationObject.particleSystems = [];
  84776. for (index = 0; index < scene.particleSystems.length; index++) {
  84777. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84778. }
  84779. // Lens flares
  84780. serializationObject.lensFlareSystems = [];
  84781. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84782. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84783. }
  84784. // Shadows
  84785. serializationObject.shadowGenerators = [];
  84786. for (index = 0; index < scene.lights.length; index++) {
  84787. light = scene.lights[index];
  84788. var shadowGenerator = light.getShadowGenerator();
  84789. if (shadowGenerator) {
  84790. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84791. }
  84792. }
  84793. // Action Manager
  84794. if (scene.actionManager) {
  84795. serializationObject.actions = scene.actionManager.serialize("scene");
  84796. }
  84797. // Audio
  84798. serializationObject.sounds = [];
  84799. for (index = 0; index < scene.soundTracks.length; index++) {
  84800. var soundtrack = scene.soundTracks[index];
  84801. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84802. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84803. }
  84804. }
  84805. return serializationObject;
  84806. };
  84807. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84808. if (withParents === void 0) { withParents = false; }
  84809. if (withChildren === void 0) { withChildren = false; }
  84810. var serializationObject = {};
  84811. SceneSerializer.ClearCache();
  84812. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84813. if (withParents || withChildren) {
  84814. //deliberate for loop! not for each, appended should be processed as well.
  84815. for (var i = 0; i < toSerialize.length; ++i) {
  84816. if (withChildren) {
  84817. toSerialize[i].getDescendants().forEach(function (node) {
  84818. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84819. toSerialize.push(node);
  84820. }
  84821. });
  84822. }
  84823. //make sure the array doesn't contain the object already
  84824. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84825. toSerialize.push(toSerialize[i].parent);
  84826. }
  84827. }
  84828. }
  84829. toSerialize.forEach(function (mesh) {
  84830. finalizeSingleMesh(mesh, serializationObject);
  84831. });
  84832. return serializationObject;
  84833. };
  84834. return SceneSerializer;
  84835. }());
  84836. BABYLON.SceneSerializer = SceneSerializer;
  84837. })(BABYLON || (BABYLON = {}));
  84838. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84839. var BABYLON;
  84840. (function (BABYLON) {
  84841. var ReflectionProbe = /** @class */ (function () {
  84842. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84843. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84844. var _this = this;
  84845. this.name = name;
  84846. this._viewMatrix = BABYLON.Matrix.Identity();
  84847. this._target = BABYLON.Vector3.Zero();
  84848. this._add = BABYLON.Vector3.Zero();
  84849. this.invertYAxis = false;
  84850. this.position = BABYLON.Vector3.Zero();
  84851. this._scene = scene;
  84852. this._scene.reflectionProbes.push(this);
  84853. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84854. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84855. switch (faceIndex) {
  84856. case 0:
  84857. _this._add.copyFromFloats(1, 0, 0);
  84858. break;
  84859. case 1:
  84860. _this._add.copyFromFloats(-1, 0, 0);
  84861. break;
  84862. case 2:
  84863. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84864. break;
  84865. case 3:
  84866. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84867. break;
  84868. case 4:
  84869. _this._add.copyFromFloats(0, 0, 1);
  84870. break;
  84871. case 5:
  84872. _this._add.copyFromFloats(0, 0, -1);
  84873. break;
  84874. }
  84875. if (_this._attachedMesh) {
  84876. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84877. }
  84878. _this.position.addToRef(_this._add, _this._target);
  84879. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84880. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84881. scene._forcedViewPosition = _this.position;
  84882. });
  84883. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84884. scene._forcedViewPosition = null;
  84885. scene.updateTransformMatrix(true);
  84886. });
  84887. if (scene.activeCamera) {
  84888. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84889. }
  84890. }
  84891. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84892. get: function () {
  84893. return this._renderTargetTexture.samples;
  84894. },
  84895. set: function (value) {
  84896. this._renderTargetTexture.samples = value;
  84897. },
  84898. enumerable: true,
  84899. configurable: true
  84900. });
  84901. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84902. get: function () {
  84903. return this._renderTargetTexture.refreshRate;
  84904. },
  84905. set: function (value) {
  84906. this._renderTargetTexture.refreshRate = value;
  84907. },
  84908. enumerable: true,
  84909. configurable: true
  84910. });
  84911. ReflectionProbe.prototype.getScene = function () {
  84912. return this._scene;
  84913. };
  84914. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84915. get: function () {
  84916. return this._renderTargetTexture;
  84917. },
  84918. enumerable: true,
  84919. configurable: true
  84920. });
  84921. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84922. get: function () {
  84923. return this._renderTargetTexture.renderList;
  84924. },
  84925. enumerable: true,
  84926. configurable: true
  84927. });
  84928. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84929. this._attachedMesh = mesh;
  84930. };
  84931. /**
  84932. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84933. *
  84934. * @param renderingGroupId The rendering group id corresponding to its index
  84935. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84936. */
  84937. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84938. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84939. };
  84940. ReflectionProbe.prototype.dispose = function () {
  84941. var index = this._scene.reflectionProbes.indexOf(this);
  84942. if (index !== -1) {
  84943. // Remove from the scene if found
  84944. this._scene.reflectionProbes.splice(index, 1);
  84945. }
  84946. if (this._renderTargetTexture) {
  84947. this._renderTargetTexture.dispose();
  84948. this._renderTargetTexture = null;
  84949. }
  84950. };
  84951. return ReflectionProbe;
  84952. }());
  84953. BABYLON.ReflectionProbe = ReflectionProbe;
  84954. })(BABYLON || (BABYLON = {}));
  84955. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84956. var BABYLON;
  84957. (function (BABYLON) {
  84958. var Layer = /** @class */ (function () {
  84959. function Layer(name, imgUrl, scene, isBackground, color) {
  84960. this.name = name;
  84961. this.scale = new BABYLON.Vector2(1, 1);
  84962. this.offset = new BABYLON.Vector2(0, 0);
  84963. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84964. this.layerMask = 0x0FFFFFFF;
  84965. this._vertexBuffers = {};
  84966. // Events
  84967. /**
  84968. * An event triggered when the layer is disposed.
  84969. * @type {BABYLON.Observable}
  84970. */
  84971. this.onDisposeObservable = new BABYLON.Observable();
  84972. /**
  84973. * An event triggered before rendering the scene
  84974. * @type {BABYLON.Observable}
  84975. */
  84976. this.onBeforeRenderObservable = new BABYLON.Observable();
  84977. /**
  84978. * An event triggered after rendering the scene
  84979. * @type {BABYLON.Observable}
  84980. */
  84981. this.onAfterRenderObservable = new BABYLON.Observable();
  84982. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84983. this.isBackground = isBackground === undefined ? true : isBackground;
  84984. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84985. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84986. this._scene.layers.push(this);
  84987. var engine = this._scene.getEngine();
  84988. // VBO
  84989. var vertices = [];
  84990. vertices.push(1, 1);
  84991. vertices.push(-1, 1);
  84992. vertices.push(-1, -1);
  84993. vertices.push(1, -1);
  84994. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84995. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84996. this._createIndexBuffer();
  84997. // Effects
  84998. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84999. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  85000. }
  85001. Object.defineProperty(Layer.prototype, "onDispose", {
  85002. set: function (callback) {
  85003. if (this._onDisposeObserver) {
  85004. this.onDisposeObservable.remove(this._onDisposeObserver);
  85005. }
  85006. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85007. },
  85008. enumerable: true,
  85009. configurable: true
  85010. });
  85011. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  85012. set: function (callback) {
  85013. if (this._onBeforeRenderObserver) {
  85014. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  85015. }
  85016. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  85017. },
  85018. enumerable: true,
  85019. configurable: true
  85020. });
  85021. Object.defineProperty(Layer.prototype, "onAfterRender", {
  85022. set: function (callback) {
  85023. if (this._onAfterRenderObserver) {
  85024. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85025. }
  85026. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  85027. },
  85028. enumerable: true,
  85029. configurable: true
  85030. });
  85031. Layer.prototype._createIndexBuffer = function () {
  85032. var engine = this._scene.getEngine();
  85033. // Indices
  85034. var indices = [];
  85035. indices.push(0);
  85036. indices.push(1);
  85037. indices.push(2);
  85038. indices.push(0);
  85039. indices.push(2);
  85040. indices.push(3);
  85041. this._indexBuffer = engine.createIndexBuffer(indices);
  85042. };
  85043. Layer.prototype._rebuild = function () {
  85044. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85045. if (vb) {
  85046. vb._rebuild();
  85047. }
  85048. this._createIndexBuffer();
  85049. };
  85050. Layer.prototype.render = function () {
  85051. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  85052. // Check
  85053. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  85054. return;
  85055. var engine = this._scene.getEngine();
  85056. this.onBeforeRenderObservable.notifyObservers(this);
  85057. // Render
  85058. engine.enableEffect(currentEffect);
  85059. engine.setState(false);
  85060. // Texture
  85061. currentEffect.setTexture("textureSampler", this.texture);
  85062. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  85063. // Color
  85064. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  85065. // Scale / offset
  85066. currentEffect.setVector2("offset", this.offset);
  85067. currentEffect.setVector2("scale", this.scale);
  85068. // VBOs
  85069. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85070. // Draw order
  85071. if (!this.alphaTest) {
  85072. engine.setAlphaMode(this.alphaBlendingMode);
  85073. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85075. }
  85076. else {
  85077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85078. }
  85079. this.onAfterRenderObservable.notifyObservers(this);
  85080. };
  85081. Layer.prototype.dispose = function () {
  85082. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85083. if (vertexBuffer) {
  85084. vertexBuffer.dispose();
  85085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85086. }
  85087. if (this._indexBuffer) {
  85088. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85089. this._indexBuffer = null;
  85090. }
  85091. if (this.texture) {
  85092. this.texture.dispose();
  85093. this.texture = null;
  85094. }
  85095. // Remove from scene
  85096. var index = this._scene.layers.indexOf(this);
  85097. this._scene.layers.splice(index, 1);
  85098. // Callback
  85099. this.onDisposeObservable.notifyObservers(this);
  85100. this.onDisposeObservable.clear();
  85101. this.onAfterRenderObservable.clear();
  85102. this.onBeforeRenderObservable.clear();
  85103. };
  85104. return Layer;
  85105. }());
  85106. BABYLON.Layer = Layer;
  85107. })(BABYLON || (BABYLON = {}));
  85108. //# sourceMappingURL=babylon.layer.js.map
  85109. var BABYLON;
  85110. (function (BABYLON) {
  85111. var TextureTools = /** @class */ (function () {
  85112. function TextureTools() {
  85113. }
  85114. /**
  85115. * Uses the GPU to create a copy texture rescaled at a given size
  85116. * @param texture Texture to copy from
  85117. * @param width Desired width
  85118. * @param height Desired height
  85119. * @return Generated texture
  85120. */
  85121. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85122. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85123. var scene = texture.getScene();
  85124. var engine = scene.getEngine();
  85125. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85126. rtt.wrapU = texture.wrapU;
  85127. rtt.wrapV = texture.wrapV;
  85128. rtt.uOffset = texture.uOffset;
  85129. rtt.vOffset = texture.vOffset;
  85130. rtt.uScale = texture.uScale;
  85131. rtt.vScale = texture.vScale;
  85132. rtt.uAng = texture.uAng;
  85133. rtt.vAng = texture.vAng;
  85134. rtt.wAng = texture.wAng;
  85135. rtt.coordinatesIndex = texture.coordinatesIndex;
  85136. rtt.level = texture.level;
  85137. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85138. rtt._texture.isReady = false;
  85139. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85140. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85141. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85142. passPostProcess.getEffect().executeWhenCompiled(function () {
  85143. passPostProcess.onApply = function (effect) {
  85144. effect.setTexture("textureSampler", texture);
  85145. };
  85146. var internalTexture = rtt.getInternalTexture();
  85147. if (internalTexture) {
  85148. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85149. engine.unBindFramebuffer(internalTexture);
  85150. rtt.disposeFramebufferObjects();
  85151. passPostProcess.dispose();
  85152. internalTexture.isReady = true;
  85153. }
  85154. });
  85155. return rtt;
  85156. };
  85157. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85158. if (!scene._environmentBRDFTexture) {
  85159. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85160. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85161. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85162. scene._environmentBRDFTexture = texture;
  85163. }
  85164. return scene._environmentBRDFTexture;
  85165. };
  85166. 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=";
  85167. return TextureTools;
  85168. }());
  85169. BABYLON.TextureTools = TextureTools;
  85170. })(BABYLON || (BABYLON = {}));
  85171. //# sourceMappingURL=babylon.textureTools.js.map
  85172. var BABYLON;
  85173. (function (BABYLON) {
  85174. var FramingBehavior = /** @class */ (function () {
  85175. function FramingBehavior() {
  85176. this._mode = FramingBehavior.FitFrustumSidesMode;
  85177. this._radiusScale = 1.0;
  85178. this._positionScale = 0.5;
  85179. this._defaultElevation = 0.3;
  85180. this._elevationReturnTime = 1500;
  85181. this._elevationReturnWaitTime = 1000;
  85182. this._zoomStopsAnimation = false;
  85183. this._framingTime = 1500;
  85184. this._isPointerDown = false;
  85185. this._lastInteractionTime = -Infinity;
  85186. // Framing control
  85187. this._animatables = new Array();
  85188. this._betaIsAnimating = false;
  85189. }
  85190. Object.defineProperty(FramingBehavior.prototype, "name", {
  85191. get: function () {
  85192. return "Framing";
  85193. },
  85194. enumerable: true,
  85195. configurable: true
  85196. });
  85197. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85198. /**
  85199. * Gets current mode used by the behavior.
  85200. */
  85201. get: function () {
  85202. return this._mode;
  85203. },
  85204. /**
  85205. * Sets the current mode used by the behavior
  85206. */
  85207. set: function (mode) {
  85208. this._mode = mode;
  85209. },
  85210. enumerable: true,
  85211. configurable: true
  85212. });
  85213. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85214. /**
  85215. * Gets the scale applied to the radius
  85216. */
  85217. get: function () {
  85218. return this._radiusScale;
  85219. },
  85220. /**
  85221. * Sets the scale applied to the radius (1 by default)
  85222. */
  85223. set: function (radius) {
  85224. this._radiusScale = radius;
  85225. },
  85226. enumerable: true,
  85227. configurable: true
  85228. });
  85229. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85230. /**
  85231. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85232. */
  85233. get: function () {
  85234. return this._positionScale;
  85235. },
  85236. /**
  85237. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85238. */
  85239. set: function (scale) {
  85240. this._positionScale = scale;
  85241. },
  85242. enumerable: true,
  85243. configurable: true
  85244. });
  85245. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85246. /**
  85247. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85248. * behaviour is triggered, in radians.
  85249. */
  85250. get: function () {
  85251. return this._defaultElevation;
  85252. },
  85253. /**
  85254. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85255. * behaviour is triggered, in radians.
  85256. */
  85257. set: function (elevation) {
  85258. this._defaultElevation = elevation;
  85259. },
  85260. enumerable: true,
  85261. configurable: true
  85262. });
  85263. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85264. /**
  85265. * Gets the time (in milliseconds) taken to return to the default beta position.
  85266. * Negative value indicates camera should not return to default.
  85267. */
  85268. get: function () {
  85269. return this._elevationReturnTime;
  85270. },
  85271. /**
  85272. * Sets the time (in milliseconds) taken to return to the default beta position.
  85273. * Negative value indicates camera should not return to default.
  85274. */
  85275. set: function (speed) {
  85276. this._elevationReturnTime = speed;
  85277. },
  85278. enumerable: true,
  85279. configurable: true
  85280. });
  85281. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85282. /**
  85283. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85284. */
  85285. get: function () {
  85286. return this._elevationReturnWaitTime;
  85287. },
  85288. /**
  85289. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85290. */
  85291. set: function (time) {
  85292. this._elevationReturnWaitTime = time;
  85293. },
  85294. enumerable: true,
  85295. configurable: true
  85296. });
  85297. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85298. /**
  85299. * Gets the flag that indicates if user zooming should stop animation.
  85300. */
  85301. get: function () {
  85302. return this._zoomStopsAnimation;
  85303. },
  85304. /**
  85305. * Sets the flag that indicates if user zooming should stop animation.
  85306. */
  85307. set: function (flag) {
  85308. this._zoomStopsAnimation = flag;
  85309. },
  85310. enumerable: true,
  85311. configurable: true
  85312. });
  85313. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85314. /**
  85315. * Gets the transition time when framing the mesh, in milliseconds
  85316. */
  85317. get: function () {
  85318. return this._framingTime;
  85319. },
  85320. /**
  85321. * Sets the transition time when framing the mesh, in milliseconds
  85322. */
  85323. set: function (time) {
  85324. this._framingTime = time;
  85325. },
  85326. enumerable: true,
  85327. configurable: true
  85328. });
  85329. FramingBehavior.prototype.init = function () {
  85330. // Do notihng
  85331. };
  85332. FramingBehavior.prototype.attach = function (camera) {
  85333. var _this = this;
  85334. this._attachedCamera = camera;
  85335. var scene = this._attachedCamera.getScene();
  85336. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85337. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85338. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85339. _this._isPointerDown = true;
  85340. return;
  85341. }
  85342. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85343. _this._isPointerDown = false;
  85344. }
  85345. });
  85346. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85347. if (mesh) {
  85348. _this.zoomOnMesh(mesh);
  85349. }
  85350. });
  85351. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85352. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85353. _this._applyUserInteraction();
  85354. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85355. // back to the default position after a given timeout
  85356. _this._maintainCameraAboveGround();
  85357. });
  85358. };
  85359. FramingBehavior.prototype.detach = function () {
  85360. if (!this._attachedCamera) {
  85361. return;
  85362. }
  85363. var scene = this._attachedCamera.getScene();
  85364. if (this._onPrePointerObservableObserver) {
  85365. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85366. }
  85367. if (this._onAfterCheckInputsObserver) {
  85368. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85369. }
  85370. if (this._onMeshTargetChangedObserver) {
  85371. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85372. }
  85373. this._attachedCamera = null;
  85374. };
  85375. /**
  85376. * Targets the given mesh and updates zoom level accordingly.
  85377. * @param mesh The mesh to target.
  85378. * @param radius Optional. If a cached radius position already exists, overrides default.
  85379. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85380. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85381. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85382. */
  85383. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85384. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85385. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85386. mesh.computeWorldMatrix(true);
  85387. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85388. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85389. };
  85390. /**
  85391. * Targets the given mesh with its children and updates zoom level accordingly.
  85392. * @param mesh The mesh to target.
  85393. * @param radius Optional. If a cached radius position already exists, overrides default.
  85394. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85395. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85396. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85397. */
  85398. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85399. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85400. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85401. mesh.computeWorldMatrix(true);
  85402. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85403. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85404. };
  85405. /**
  85406. * Targets the given meshes with their children and updates zoom level accordingly.
  85407. * @param meshes The mesh to target.
  85408. * @param radius Optional. If a cached radius position already exists, overrides default.
  85409. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85410. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85411. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85412. */
  85413. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85414. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85415. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85416. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85417. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85418. for (var i = 0; i < meshes.length; i++) {
  85419. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85420. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85421. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85422. }
  85423. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85424. };
  85425. /**
  85426. * Targets the given mesh and updates zoom level accordingly.
  85427. * @param mesh The mesh to target.
  85428. * @param radius Optional. If a cached radius position already exists, overrides default.
  85429. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85430. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85431. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85432. */
  85433. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85434. var _this = this;
  85435. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85436. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85437. var zoomTarget;
  85438. if (!this._attachedCamera) {
  85439. return;
  85440. }
  85441. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85442. var bottom = minimumWorld.y;
  85443. var top = maximumWorld.y;
  85444. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85445. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85446. if (focusOnOriginXZ) {
  85447. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85448. }
  85449. else {
  85450. var centerWorld = minimumWorld.add(radiusWorld);
  85451. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85452. }
  85453. if (!this._vectorTransition) {
  85454. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85455. }
  85456. this._betaIsAnimating = true;
  85457. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85458. if (animatable) {
  85459. this._animatables.push(animatable);
  85460. }
  85461. // sets the radius and lower radius bounds
  85462. // Small delta ensures camera is not always at lower zoom limit.
  85463. var radius = 0;
  85464. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85465. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85466. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85467. radius = position;
  85468. }
  85469. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85470. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85471. if (this._attachedCamera.lowerRadiusLimit === null) {
  85472. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85473. }
  85474. }
  85475. // Set sensibilities
  85476. var extend = maximumWorld.subtract(minimumWorld).length();
  85477. this._attachedCamera.panningSensibility = 5000 / extend;
  85478. this._attachedCamera.wheelPrecision = 100 / radius;
  85479. // transition to new radius
  85480. if (!this._radiusTransition) {
  85481. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85482. }
  85483. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85484. if (onAnimationEnd) {
  85485. onAnimationEnd();
  85486. }
  85487. if (_this._attachedCamera) {
  85488. _this._attachedCamera.storeState();
  85489. }
  85490. });
  85491. if (animatable) {
  85492. this._animatables.push(animatable);
  85493. }
  85494. };
  85495. /**
  85496. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85497. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85498. * frustum width.
  85499. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85500. * to fully enclose the mesh in the viewing frustum.
  85501. */
  85502. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85503. var size = maximumWorld.subtract(minimumWorld);
  85504. var boxVectorGlobalDiagonal = size.length();
  85505. var frustumSlope = this._getFrustumSlope();
  85506. // Formula for setting distance
  85507. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85508. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85509. // Horizon distance
  85510. var radius = radiusWithoutFraming * this._radiusScale;
  85511. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85512. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85513. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85514. var camera = this._attachedCamera;
  85515. if (!camera) {
  85516. return 0;
  85517. }
  85518. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85519. // Don't exceed the requested limit
  85520. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85521. }
  85522. // Don't exceed the upper radius limit
  85523. if (camera.upperRadiusLimit) {
  85524. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85525. }
  85526. return distance;
  85527. };
  85528. /**
  85529. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85530. * is automatically returned to its default position (expected to be above ground plane).
  85531. */
  85532. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85533. var _this = this;
  85534. if (this._elevationReturnTime < 0) {
  85535. return;
  85536. }
  85537. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85538. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85539. var limitBeta = Math.PI * 0.5;
  85540. // Bring the camera back up if below the ground plane
  85541. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85542. this._betaIsAnimating = true;
  85543. //Transition to new position
  85544. this.stopAllAnimations();
  85545. if (!this._betaTransition) {
  85546. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85547. }
  85548. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85549. _this._clearAnimationLocks();
  85550. _this.stopAllAnimations();
  85551. });
  85552. if (animatabe) {
  85553. this._animatables.push(animatabe);
  85554. }
  85555. }
  85556. };
  85557. /**
  85558. * Returns the frustum slope based on the canvas ratio and camera FOV
  85559. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85560. */
  85561. FramingBehavior.prototype._getFrustumSlope = function () {
  85562. // Calculate the viewport ratio
  85563. // Aspect Ratio is Height/Width.
  85564. var camera = this._attachedCamera;
  85565. if (!camera) {
  85566. return BABYLON.Vector2.Zero();
  85567. }
  85568. var engine = camera.getScene().getEngine();
  85569. var aspectRatio = engine.getAspectRatio(camera);
  85570. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85571. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85572. var frustumSlopeY = Math.tan(camera.fov / 2);
  85573. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85574. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85575. // along the forward vector.
  85576. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85577. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85578. };
  85579. /**
  85580. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85581. */
  85582. FramingBehavior.prototype._clearAnimationLocks = function () {
  85583. this._betaIsAnimating = false;
  85584. };
  85585. /**
  85586. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85587. */
  85588. FramingBehavior.prototype._applyUserInteraction = function () {
  85589. if (this.isUserIsMoving) {
  85590. this._lastInteractionTime = BABYLON.Tools.Now;
  85591. this.stopAllAnimations();
  85592. this._clearAnimationLocks();
  85593. }
  85594. };
  85595. /**
  85596. * Stops and removes all animations that have been applied to the camera
  85597. */
  85598. FramingBehavior.prototype.stopAllAnimations = function () {
  85599. if (this._attachedCamera) {
  85600. this._attachedCamera.animations = [];
  85601. }
  85602. while (this._animatables.length) {
  85603. if (this._animatables[0]) {
  85604. this._animatables[0].onAnimationEnd = null;
  85605. this._animatables[0].stop();
  85606. }
  85607. this._animatables.shift();
  85608. }
  85609. };
  85610. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85611. /**
  85612. * Gets a value indicating if the user is moving the camera
  85613. */
  85614. get: function () {
  85615. if (!this._attachedCamera) {
  85616. return false;
  85617. }
  85618. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85619. this._attachedCamera.inertialBetaOffset !== 0 ||
  85620. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85621. this._attachedCamera.inertialPanningX !== 0 ||
  85622. this._attachedCamera.inertialPanningY !== 0 ||
  85623. this._isPointerDown;
  85624. },
  85625. enumerable: true,
  85626. configurable: true
  85627. });
  85628. /**
  85629. * The easing function used by animations
  85630. */
  85631. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85632. /**
  85633. * The easing mode used by animations
  85634. */
  85635. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85636. // Statics
  85637. /**
  85638. * The camera can move all the way towards the mesh.
  85639. */
  85640. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85641. /**
  85642. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85643. */
  85644. FramingBehavior.FitFrustumSidesMode = 1;
  85645. return FramingBehavior;
  85646. }());
  85647. BABYLON.FramingBehavior = FramingBehavior;
  85648. })(BABYLON || (BABYLON = {}));
  85649. //# sourceMappingURL=babylon.framingBehavior.js.map
  85650. var BABYLON;
  85651. (function (BABYLON) {
  85652. /**
  85653. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85654. */
  85655. var BouncingBehavior = /** @class */ (function () {
  85656. function BouncingBehavior() {
  85657. /**
  85658. * The duration of the animation, in milliseconds
  85659. */
  85660. this.transitionDuration = 450;
  85661. /**
  85662. * Length of the distance animated by the transition when lower radius is reached
  85663. */
  85664. this.lowerRadiusTransitionRange = 2;
  85665. /**
  85666. * Length of the distance animated by the transition when upper radius is reached
  85667. */
  85668. this.upperRadiusTransitionRange = -2;
  85669. this._autoTransitionRange = false;
  85670. // Animations
  85671. this._radiusIsAnimating = false;
  85672. this._radiusBounceTransition = null;
  85673. this._animatables = new Array();
  85674. }
  85675. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85676. get: function () {
  85677. return "Bouncing";
  85678. },
  85679. enumerable: true,
  85680. configurable: true
  85681. });
  85682. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85683. /**
  85684. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85685. */
  85686. get: function () {
  85687. return this._autoTransitionRange;
  85688. },
  85689. /**
  85690. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85691. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85692. */
  85693. set: function (value) {
  85694. var _this = this;
  85695. if (this._autoTransitionRange === value) {
  85696. return;
  85697. }
  85698. this._autoTransitionRange = value;
  85699. var camera = this._attachedCamera;
  85700. if (!camera) {
  85701. return;
  85702. }
  85703. if (value) {
  85704. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85705. if (!mesh) {
  85706. return;
  85707. }
  85708. mesh.computeWorldMatrix(true);
  85709. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85710. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85711. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85712. });
  85713. }
  85714. else if (this._onMeshTargetChangedObserver) {
  85715. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85716. }
  85717. },
  85718. enumerable: true,
  85719. configurable: true
  85720. });
  85721. BouncingBehavior.prototype.init = function () {
  85722. // Do notihng
  85723. };
  85724. BouncingBehavior.prototype.attach = function (camera) {
  85725. var _this = this;
  85726. this._attachedCamera = camera;
  85727. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85728. if (!_this._attachedCamera) {
  85729. return;
  85730. }
  85731. // Add the bounce animation to the lower radius limit
  85732. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85733. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85734. }
  85735. // Add the bounce animation to the upper radius limit
  85736. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85737. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85738. }
  85739. });
  85740. };
  85741. BouncingBehavior.prototype.detach = function () {
  85742. if (!this._attachedCamera) {
  85743. return;
  85744. }
  85745. if (this._onAfterCheckInputsObserver) {
  85746. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85747. }
  85748. if (this._onMeshTargetChangedObserver) {
  85749. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85750. }
  85751. this._attachedCamera = null;
  85752. };
  85753. /**
  85754. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85755. * @param radiusLimit The limit to check against.
  85756. * @return Bool to indicate if at limit.
  85757. */
  85758. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85759. if (!this._attachedCamera) {
  85760. return false;
  85761. }
  85762. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85763. return true;
  85764. }
  85765. return false;
  85766. };
  85767. /**
  85768. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85769. * @param radiusDelta The delta by which to animate to. Can be negative.
  85770. */
  85771. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85772. var _this = this;
  85773. if (!this._attachedCamera) {
  85774. return;
  85775. }
  85776. if (!this._radiusBounceTransition) {
  85777. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85778. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85779. }
  85780. // Prevent zoom until bounce has completed
  85781. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85782. this._attachedCamera.wheelPrecision = Infinity;
  85783. this._attachedCamera.inertialRadiusOffset = 0;
  85784. // Animate to the radius limit
  85785. this.stopAllAnimations();
  85786. this._radiusIsAnimating = true;
  85787. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85788. if (animatable) {
  85789. this._animatables.push(animatable);
  85790. }
  85791. };
  85792. /**
  85793. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85794. */
  85795. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85796. this._radiusIsAnimating = false;
  85797. if (this._attachedCamera) {
  85798. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85799. }
  85800. };
  85801. /**
  85802. * Stops and removes all animations that have been applied to the camera
  85803. */
  85804. BouncingBehavior.prototype.stopAllAnimations = function () {
  85805. if (this._attachedCamera) {
  85806. this._attachedCamera.animations = [];
  85807. }
  85808. while (this._animatables.length) {
  85809. this._animatables[0].onAnimationEnd = null;
  85810. this._animatables[0].stop();
  85811. this._animatables.shift();
  85812. }
  85813. };
  85814. /**
  85815. * The easing function used by animations
  85816. */
  85817. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85818. /**
  85819. * The easing mode used by animations
  85820. */
  85821. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85822. return BouncingBehavior;
  85823. }());
  85824. BABYLON.BouncingBehavior = BouncingBehavior;
  85825. })(BABYLON || (BABYLON = {}));
  85826. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85827. var BABYLON;
  85828. (function (BABYLON) {
  85829. var AutoRotationBehavior = /** @class */ (function () {
  85830. function AutoRotationBehavior() {
  85831. this._zoomStopsAnimation = false;
  85832. this._idleRotationSpeed = 0.05;
  85833. this._idleRotationWaitTime = 2000;
  85834. this._idleRotationSpinupTime = 2000;
  85835. this._isPointerDown = false;
  85836. this._lastFrameTime = null;
  85837. this._lastInteractionTime = -Infinity;
  85838. this._cameraRotationSpeed = 0;
  85839. this._lastFrameRadius = 0;
  85840. }
  85841. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85842. get: function () {
  85843. return "AutoRotation";
  85844. },
  85845. enumerable: true,
  85846. configurable: true
  85847. });
  85848. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85849. /**
  85850. * Gets the flag that indicates if user zooming should stop animation.
  85851. */
  85852. get: function () {
  85853. return this._zoomStopsAnimation;
  85854. },
  85855. /**
  85856. * Sets the flag that indicates if user zooming should stop animation.
  85857. */
  85858. set: function (flag) {
  85859. this._zoomStopsAnimation = flag;
  85860. },
  85861. enumerable: true,
  85862. configurable: true
  85863. });
  85864. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85865. /**
  85866. * Gets the default speed at which the camera rotates around the model.
  85867. */
  85868. get: function () {
  85869. return this._idleRotationSpeed;
  85870. },
  85871. /**
  85872. * Sets the default speed at which the camera rotates around the model.
  85873. */
  85874. set: function (speed) {
  85875. this._idleRotationSpeed = speed;
  85876. },
  85877. enumerable: true,
  85878. configurable: true
  85879. });
  85880. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85881. /**
  85882. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85883. */
  85884. get: function () {
  85885. return this._idleRotationWaitTime;
  85886. },
  85887. /**
  85888. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85889. */
  85890. set: function (time) {
  85891. this._idleRotationWaitTime = time;
  85892. },
  85893. enumerable: true,
  85894. configurable: true
  85895. });
  85896. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85897. /**
  85898. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85899. */
  85900. get: function () {
  85901. return this._idleRotationSpinupTime;
  85902. },
  85903. /**
  85904. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85905. */
  85906. set: function (time) {
  85907. this._idleRotationSpinupTime = time;
  85908. },
  85909. enumerable: true,
  85910. configurable: true
  85911. });
  85912. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85913. /**
  85914. * Gets a value indicating if the camera is currently rotating because of this behavior
  85915. */
  85916. get: function () {
  85917. return Math.abs(this._cameraRotationSpeed) > 0;
  85918. },
  85919. enumerable: true,
  85920. configurable: true
  85921. });
  85922. AutoRotationBehavior.prototype.init = function () {
  85923. // Do notihng
  85924. };
  85925. AutoRotationBehavior.prototype.attach = function (camera) {
  85926. var _this = this;
  85927. this._attachedCamera = camera;
  85928. var scene = this._attachedCamera.getScene();
  85929. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85930. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85931. _this._isPointerDown = true;
  85932. return;
  85933. }
  85934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85935. _this._isPointerDown = false;
  85936. }
  85937. });
  85938. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85939. var now = BABYLON.Tools.Now;
  85940. var dt = 0;
  85941. if (_this._lastFrameTime != null) {
  85942. dt = now - _this._lastFrameTime;
  85943. }
  85944. _this._lastFrameTime = now;
  85945. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85946. _this._applyUserInteraction();
  85947. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85948. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85949. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85950. // Step camera rotation by rotation speed
  85951. if (_this._attachedCamera) {
  85952. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85953. }
  85954. });
  85955. };
  85956. AutoRotationBehavior.prototype.detach = function () {
  85957. if (!this._attachedCamera) {
  85958. return;
  85959. }
  85960. var scene = this._attachedCamera.getScene();
  85961. if (this._onPrePointerObservableObserver) {
  85962. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85963. }
  85964. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85965. this._attachedCamera = null;
  85966. };
  85967. /**
  85968. * Returns true if user is scrolling.
  85969. * @return true if user is scrolling.
  85970. */
  85971. AutoRotationBehavior.prototype._userIsZooming = function () {
  85972. if (!this._attachedCamera) {
  85973. return false;
  85974. }
  85975. return this._attachedCamera.inertialRadiusOffset !== 0;
  85976. };
  85977. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85978. if (!this._attachedCamera) {
  85979. return false;
  85980. }
  85981. var zoomHasHitLimit = false;
  85982. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85983. zoomHasHitLimit = true;
  85984. }
  85985. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85986. this._lastFrameRadius = this._attachedCamera.radius;
  85987. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85988. };
  85989. /**
  85990. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85991. */
  85992. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85993. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85994. this._lastInteractionTime = BABYLON.Tools.Now;
  85995. }
  85996. };
  85997. // Tools
  85998. AutoRotationBehavior.prototype._userIsMoving = function () {
  85999. if (!this._attachedCamera) {
  86000. return false;
  86001. }
  86002. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86003. this._attachedCamera.inertialBetaOffset !== 0 ||
  86004. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86005. this._attachedCamera.inertialPanningX !== 0 ||
  86006. this._attachedCamera.inertialPanningY !== 0 ||
  86007. this._isPointerDown;
  86008. };
  86009. return AutoRotationBehavior;
  86010. }());
  86011. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  86012. })(BABYLON || (BABYLON = {}));
  86013. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  86014. var BABYLON;
  86015. (function (BABYLON) {
  86016. /**
  86017. * This class can be used to get instrumentation data from a Babylon engine
  86018. */
  86019. var EngineInstrumentation = /** @class */ (function () {
  86020. function EngineInstrumentation(engine) {
  86021. this.engine = engine;
  86022. this._captureGPUFrameTime = false;
  86023. this._gpuFrameTime = new BABYLON.PerfCounter();
  86024. this._captureShaderCompilationTime = false;
  86025. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86026. // Observers
  86027. this._onBeginFrameObserver = null;
  86028. this._onEndFrameObserver = null;
  86029. this._onBeforeShaderCompilationObserver = null;
  86030. this._onAfterShaderCompilationObserver = null;
  86031. }
  86032. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86033. // Properties
  86034. /**
  86035. * Gets the perf counter used for GPU frame time
  86036. */
  86037. get: function () {
  86038. return this._gpuFrameTime;
  86039. },
  86040. enumerable: true,
  86041. configurable: true
  86042. });
  86043. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86044. /**
  86045. * Gets the GPU frame time capture status
  86046. */
  86047. get: function () {
  86048. return this._captureGPUFrameTime;
  86049. },
  86050. /**
  86051. * Enable or disable the GPU frame time capture
  86052. */
  86053. set: function (value) {
  86054. var _this = this;
  86055. if (value === this._captureGPUFrameTime) {
  86056. return;
  86057. }
  86058. this._captureGPUFrameTime = value;
  86059. if (value) {
  86060. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86061. if (!_this._gpuFrameTimeToken) {
  86062. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86063. }
  86064. });
  86065. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86066. if (!_this._gpuFrameTimeToken) {
  86067. return;
  86068. }
  86069. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86070. if (time > -1) {
  86071. _this._gpuFrameTimeToken = null;
  86072. _this._gpuFrameTime.fetchNewFrame();
  86073. _this._gpuFrameTime.addCount(time, true);
  86074. }
  86075. });
  86076. }
  86077. else {
  86078. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86079. this._onBeginFrameObserver = null;
  86080. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86081. this._onEndFrameObserver = null;
  86082. }
  86083. },
  86084. enumerable: true,
  86085. configurable: true
  86086. });
  86087. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86088. /**
  86089. * Gets the perf counter used for shader compilation time
  86090. */
  86091. get: function () {
  86092. return this._shaderCompilationTime;
  86093. },
  86094. enumerable: true,
  86095. configurable: true
  86096. });
  86097. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86098. /**
  86099. * Gets the shader compilation time capture status
  86100. */
  86101. get: function () {
  86102. return this._captureShaderCompilationTime;
  86103. },
  86104. /**
  86105. * Enable or disable the shader compilation time capture
  86106. */
  86107. set: function (value) {
  86108. var _this = this;
  86109. if (value === this._captureShaderCompilationTime) {
  86110. return;
  86111. }
  86112. this._captureShaderCompilationTime = value;
  86113. if (value) {
  86114. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86115. _this._shaderCompilationTime.fetchNewFrame();
  86116. _this._shaderCompilationTime.beginMonitoring();
  86117. });
  86118. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86119. _this._shaderCompilationTime.endMonitoring();
  86120. });
  86121. }
  86122. else {
  86123. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86124. this._onBeforeShaderCompilationObserver = null;
  86125. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86126. this._onAfterShaderCompilationObserver = null;
  86127. }
  86128. },
  86129. enumerable: true,
  86130. configurable: true
  86131. });
  86132. EngineInstrumentation.prototype.dispose = function () {
  86133. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86134. this._onBeginFrameObserver = null;
  86135. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86136. this._onEndFrameObserver = null;
  86137. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86138. this._onBeforeShaderCompilationObserver = null;
  86139. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86140. this._onAfterShaderCompilationObserver = null;
  86141. this.engine = null;
  86142. };
  86143. return EngineInstrumentation;
  86144. }());
  86145. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86146. })(BABYLON || (BABYLON = {}));
  86147. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86148. var BABYLON;
  86149. (function (BABYLON) {
  86150. /**
  86151. * This class can be used to get instrumentation data from a Babylon engine
  86152. */
  86153. var SceneInstrumentation = /** @class */ (function () {
  86154. function SceneInstrumentation(scene) {
  86155. var _this = this;
  86156. this.scene = scene;
  86157. this._captureActiveMeshesEvaluationTime = false;
  86158. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86159. this._captureRenderTargetsRenderTime = false;
  86160. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86161. this._captureFrameTime = false;
  86162. this._frameTime = new BABYLON.PerfCounter();
  86163. this._captureRenderTime = false;
  86164. this._renderTime = new BABYLON.PerfCounter();
  86165. this._captureInterFrameTime = false;
  86166. this._interFrameTime = new BABYLON.PerfCounter();
  86167. this._captureParticlesRenderTime = false;
  86168. this._particlesRenderTime = new BABYLON.PerfCounter();
  86169. this._captureSpritesRenderTime = false;
  86170. this._spritesRenderTime = new BABYLON.PerfCounter();
  86171. this._capturePhysicsTime = false;
  86172. this._physicsTime = new BABYLON.PerfCounter();
  86173. this._captureAnimationsTime = false;
  86174. this._animationsTime = new BABYLON.PerfCounter();
  86175. // Observers
  86176. this._onBeforeActiveMeshesEvaluationObserver = null;
  86177. this._onAfterActiveMeshesEvaluationObserver = null;
  86178. this._onBeforeRenderTargetsRenderObserver = null;
  86179. this._onAfterRenderTargetsRenderObserver = null;
  86180. this._onAfterRenderObserver = null;
  86181. this._onBeforeDrawPhaseObserver = null;
  86182. this._onAfterDrawPhaseObserver = null;
  86183. this._onBeforeAnimationsObserver = null;
  86184. this._onBeforeParticlesRenderingObserver = null;
  86185. this._onAfterParticlesRenderingObserver = null;
  86186. this._onBeforeSpritesRenderingObserver = null;
  86187. this._onAfterSpritesRenderingObserver = null;
  86188. this._onBeforePhysicsObserver = null;
  86189. this._onAfterPhysicsObserver = null;
  86190. this._onAfterAnimationsObserver = null;
  86191. // Before render
  86192. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86193. if (_this._captureActiveMeshesEvaluationTime) {
  86194. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86195. }
  86196. if (_this._captureRenderTargetsRenderTime) {
  86197. _this._renderTargetsRenderTime.fetchNewFrame();
  86198. }
  86199. if (_this._captureFrameTime) {
  86200. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  86201. _this._frameTime.beginMonitoring();
  86202. }
  86203. if (_this._captureInterFrameTime) {
  86204. _this._interFrameTime.endMonitoring();
  86205. }
  86206. if (_this._captureParticlesRenderTime) {
  86207. _this._particlesRenderTime.fetchNewFrame();
  86208. }
  86209. if (_this._captureSpritesRenderTime) {
  86210. _this._spritesRenderTime.fetchNewFrame();
  86211. }
  86212. if (_this._captureAnimationsTime) {
  86213. _this._animationsTime.beginMonitoring();
  86214. }
  86215. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  86216. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  86217. });
  86218. // After render
  86219. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  86220. if (_this._captureFrameTime) {
  86221. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  86222. _this._frameTime.endMonitoring();
  86223. }
  86224. if (_this._captureRenderTime) {
  86225. _this._renderTime.endMonitoring(false);
  86226. }
  86227. if (_this._captureInterFrameTime) {
  86228. _this._interFrameTime.beginMonitoring();
  86229. }
  86230. });
  86231. }
  86232. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86233. // Properties
  86234. /**
  86235. * Gets the perf counter used for active meshes evaluation time
  86236. */
  86237. get: function () {
  86238. return this._activeMeshesEvaluationTime;
  86239. },
  86240. enumerable: true,
  86241. configurable: true
  86242. });
  86243. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86244. /**
  86245. * Gets the active meshes evaluation time capture status
  86246. */
  86247. get: function () {
  86248. return this._captureActiveMeshesEvaluationTime;
  86249. },
  86250. /**
  86251. * Enable or disable the active meshes evaluation time capture
  86252. */
  86253. set: function (value) {
  86254. var _this = this;
  86255. if (value === this._captureActiveMeshesEvaluationTime) {
  86256. return;
  86257. }
  86258. this._captureActiveMeshesEvaluationTime = value;
  86259. if (value) {
  86260. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86261. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86262. _this._activeMeshesEvaluationTime.beginMonitoring();
  86263. });
  86264. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86265. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86266. _this._activeMeshesEvaluationTime.endMonitoring();
  86267. });
  86268. }
  86269. else {
  86270. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86271. this._onBeforeActiveMeshesEvaluationObserver = null;
  86272. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86273. this._onAfterActiveMeshesEvaluationObserver = null;
  86274. }
  86275. },
  86276. enumerable: true,
  86277. configurable: true
  86278. });
  86279. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86280. /**
  86281. * Gets the perf counter used for render targets render time
  86282. */
  86283. get: function () {
  86284. return this._renderTargetsRenderTime;
  86285. },
  86286. enumerable: true,
  86287. configurable: true
  86288. });
  86289. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86290. /**
  86291. * Gets the render targets render time capture status
  86292. */
  86293. get: function () {
  86294. return this._captureRenderTargetsRenderTime;
  86295. },
  86296. /**
  86297. * Enable or disable the render targets render time capture
  86298. */
  86299. set: function (value) {
  86300. var _this = this;
  86301. if (value === this._captureRenderTargetsRenderTime) {
  86302. return;
  86303. }
  86304. this._captureRenderTargetsRenderTime = value;
  86305. if (value) {
  86306. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86307. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86308. _this._renderTargetsRenderTime.beginMonitoring();
  86309. });
  86310. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86311. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86312. _this._renderTargetsRenderTime.endMonitoring(false);
  86313. });
  86314. }
  86315. else {
  86316. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86317. this._onBeforeRenderTargetsRenderObserver = null;
  86318. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86319. this._onAfterRenderTargetsRenderObserver = null;
  86320. }
  86321. },
  86322. enumerable: true,
  86323. configurable: true
  86324. });
  86325. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86326. /**
  86327. * Gets the perf counter used for particles render time
  86328. */
  86329. get: function () {
  86330. return this._particlesRenderTime;
  86331. },
  86332. enumerable: true,
  86333. configurable: true
  86334. });
  86335. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86336. /**
  86337. * Gets the particles render time capture status
  86338. */
  86339. get: function () {
  86340. return this._captureParticlesRenderTime;
  86341. },
  86342. /**
  86343. * Enable or disable the particles render time capture
  86344. */
  86345. set: function (value) {
  86346. var _this = this;
  86347. if (value === this._captureParticlesRenderTime) {
  86348. return;
  86349. }
  86350. this._captureParticlesRenderTime = value;
  86351. if (value) {
  86352. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86353. BABYLON.Tools.StartPerformanceCounter("Particles");
  86354. _this._particlesRenderTime.beginMonitoring();
  86355. });
  86356. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86357. BABYLON.Tools.EndPerformanceCounter("Particles");
  86358. _this._particlesRenderTime.endMonitoring(false);
  86359. });
  86360. }
  86361. else {
  86362. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86363. this._onBeforeParticlesRenderingObserver = null;
  86364. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86365. this._onAfterParticlesRenderingObserver = null;
  86366. }
  86367. },
  86368. enumerable: true,
  86369. configurable: true
  86370. });
  86371. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86372. /**
  86373. * Gets the perf counter used for sprites render time
  86374. */
  86375. get: function () {
  86376. return this._spritesRenderTime;
  86377. },
  86378. enumerable: true,
  86379. configurable: true
  86380. });
  86381. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86382. /**
  86383. * Gets the sprites render time capture status
  86384. */
  86385. get: function () {
  86386. return this._captureSpritesRenderTime;
  86387. },
  86388. /**
  86389. * Enable or disable the sprites render time capture
  86390. */
  86391. set: function (value) {
  86392. var _this = this;
  86393. if (value === this._captureSpritesRenderTime) {
  86394. return;
  86395. }
  86396. this._captureSpritesRenderTime = value;
  86397. if (value) {
  86398. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86399. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86400. _this._spritesRenderTime.beginMonitoring();
  86401. });
  86402. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86403. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86404. _this._spritesRenderTime.endMonitoring(false);
  86405. });
  86406. }
  86407. else {
  86408. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86409. this._onBeforeSpritesRenderingObserver = null;
  86410. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86411. this._onAfterSpritesRenderingObserver = null;
  86412. }
  86413. },
  86414. enumerable: true,
  86415. configurable: true
  86416. });
  86417. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86418. /**
  86419. * Gets the perf counter used for physics time
  86420. */
  86421. get: function () {
  86422. return this._physicsTime;
  86423. },
  86424. enumerable: true,
  86425. configurable: true
  86426. });
  86427. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86428. /**
  86429. * Gets the physics time capture status
  86430. */
  86431. get: function () {
  86432. return this._capturePhysicsTime;
  86433. },
  86434. /**
  86435. * Enable or disable the physics time capture
  86436. */
  86437. set: function (value) {
  86438. var _this = this;
  86439. if (value === this._capturePhysicsTime) {
  86440. return;
  86441. }
  86442. this._capturePhysicsTime = value;
  86443. if (value) {
  86444. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86445. BABYLON.Tools.StartPerformanceCounter("Physics");
  86446. _this._physicsTime.beginMonitoring();
  86447. });
  86448. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86449. BABYLON.Tools.EndPerformanceCounter("Physics");
  86450. _this._physicsTime.endMonitoring();
  86451. });
  86452. }
  86453. else {
  86454. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86455. this._onBeforePhysicsObserver = null;
  86456. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86457. this._onAfterPhysicsObserver = null;
  86458. }
  86459. },
  86460. enumerable: true,
  86461. configurable: true
  86462. });
  86463. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86464. /**
  86465. * Gets the perf counter used for animations time
  86466. */
  86467. get: function () {
  86468. return this._animationsTime;
  86469. },
  86470. enumerable: true,
  86471. configurable: true
  86472. });
  86473. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86474. /**
  86475. * Gets the animations time capture status
  86476. */
  86477. get: function () {
  86478. return this._captureAnimationsTime;
  86479. },
  86480. /**
  86481. * Enable or disable the animations time capture
  86482. */
  86483. set: function (value) {
  86484. var _this = this;
  86485. if (value === this._captureAnimationsTime) {
  86486. return;
  86487. }
  86488. this._captureAnimationsTime = value;
  86489. if (value) {
  86490. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86491. _this._animationsTime.endMonitoring();
  86492. });
  86493. }
  86494. else {
  86495. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86496. this._onAfterAnimationsObserver = null;
  86497. }
  86498. },
  86499. enumerable: true,
  86500. configurable: true
  86501. });
  86502. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86503. /**
  86504. * Gets the perf counter used for frame time capture
  86505. */
  86506. get: function () {
  86507. return this._frameTime;
  86508. },
  86509. enumerable: true,
  86510. configurable: true
  86511. });
  86512. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86513. /**
  86514. * Gets the frame time capture status
  86515. */
  86516. get: function () {
  86517. return this._captureFrameTime;
  86518. },
  86519. /**
  86520. * Enable or disable the frame time capture
  86521. */
  86522. set: function (value) {
  86523. this._captureFrameTime = value;
  86524. },
  86525. enumerable: true,
  86526. configurable: true
  86527. });
  86528. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86529. /**
  86530. * Gets the perf counter used for inter-frames time capture
  86531. */
  86532. get: function () {
  86533. return this._interFrameTime;
  86534. },
  86535. enumerable: true,
  86536. configurable: true
  86537. });
  86538. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86539. /**
  86540. * Gets the inter-frames time capture status
  86541. */
  86542. get: function () {
  86543. return this._captureInterFrameTime;
  86544. },
  86545. /**
  86546. * Enable or disable the inter-frames time capture
  86547. */
  86548. set: function (value) {
  86549. this._captureInterFrameTime = value;
  86550. },
  86551. enumerable: true,
  86552. configurable: true
  86553. });
  86554. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86555. /**
  86556. * Gets the perf counter used for render time capture
  86557. */
  86558. get: function () {
  86559. return this._renderTime;
  86560. },
  86561. enumerable: true,
  86562. configurable: true
  86563. });
  86564. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86565. /**
  86566. * Gets the render time capture status
  86567. */
  86568. get: function () {
  86569. return this._captureRenderTime;
  86570. },
  86571. /**
  86572. * Enable or disable the render time capture
  86573. */
  86574. set: function (value) {
  86575. var _this = this;
  86576. if (value === this._captureRenderTime) {
  86577. return;
  86578. }
  86579. this._captureRenderTime = value;
  86580. if (value) {
  86581. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86582. _this._renderTime.beginMonitoring();
  86583. BABYLON.Tools.StartPerformanceCounter("Main render");
  86584. });
  86585. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86586. _this._renderTime.endMonitoring(false);
  86587. BABYLON.Tools.EndPerformanceCounter("Main render");
  86588. });
  86589. }
  86590. else {
  86591. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86592. this._onBeforeDrawPhaseObserver = null;
  86593. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86594. this._onAfterDrawPhaseObserver = null;
  86595. }
  86596. },
  86597. enumerable: true,
  86598. configurable: true
  86599. });
  86600. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86601. /**
  86602. * Gets the perf counter used for draw calls
  86603. */
  86604. get: function () {
  86605. return this.scene.getEngine()._drawCalls;
  86606. },
  86607. enumerable: true,
  86608. configurable: true
  86609. });
  86610. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86611. /**
  86612. * Gets the perf counter used for texture collisions
  86613. */
  86614. get: function () {
  86615. return this.scene.getEngine()._textureCollisions;
  86616. },
  86617. enumerable: true,
  86618. configurable: true
  86619. });
  86620. SceneInstrumentation.prototype.dispose = function () {
  86621. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86622. this._onAfterRenderObserver = null;
  86623. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86624. this._onBeforeActiveMeshesEvaluationObserver = null;
  86625. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86626. this._onAfterActiveMeshesEvaluationObserver = null;
  86627. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86628. this._onBeforeRenderTargetsRenderObserver = null;
  86629. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86630. this._onAfterRenderTargetsRenderObserver = null;
  86631. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86632. this._onBeforeAnimationsObserver = null;
  86633. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86634. this._onBeforeParticlesRenderingObserver = null;
  86635. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86636. this._onAfterParticlesRenderingObserver = null;
  86637. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86638. this._onBeforeSpritesRenderingObserver = null;
  86639. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86640. this._onAfterSpritesRenderingObserver = null;
  86641. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86642. this._onBeforeDrawPhaseObserver = null;
  86643. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86644. this._onAfterDrawPhaseObserver = null;
  86645. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86646. this._onBeforePhysicsObserver = null;
  86647. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86648. this._onAfterPhysicsObserver = null;
  86649. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86650. this._onAfterAnimationsObserver = null;
  86651. this.scene = null;
  86652. };
  86653. return SceneInstrumentation;
  86654. }());
  86655. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86656. })(BABYLON || (BABYLON = {}));
  86657. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86658. var BABYLON;
  86659. (function (BABYLON) {
  86660. var _TimeToken = /** @class */ (function () {
  86661. function _TimeToken() {
  86662. this._timeElapsedQueryEnded = false;
  86663. }
  86664. return _TimeToken;
  86665. }());
  86666. BABYLON._TimeToken = _TimeToken;
  86667. })(BABYLON || (BABYLON = {}));
  86668. //# sourceMappingURL=babylon.timeToken.js.map
  86669. var BABYLON;
  86670. (function (BABYLON) {
  86671. /**
  86672. * Background material defines definition.
  86673. * @ignore Mainly internal Use
  86674. */
  86675. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86676. __extends(BackgroundMaterialDefines, _super);
  86677. /**
  86678. * Constructor of the defines.
  86679. */
  86680. function BackgroundMaterialDefines() {
  86681. var _this = _super.call(this) || this;
  86682. /**
  86683. * True if the diffuse texture is in use.
  86684. */
  86685. _this.DIFFUSE = false;
  86686. /**
  86687. * The direct UV channel to use.
  86688. */
  86689. _this.DIFFUSEDIRECTUV = 0;
  86690. /**
  86691. * True if the diffuse texture is in gamma space.
  86692. */
  86693. _this.GAMMADIFFUSE = false;
  86694. /**
  86695. * True if the diffuse texture has opacity in the alpha channel.
  86696. */
  86697. _this.DIFFUSEHASALPHA = false;
  86698. /**
  86699. * True if you want the material to fade to transparent at grazing angle.
  86700. */
  86701. _this.OPACITYFRESNEL = false;
  86702. /**
  86703. * True if an extra blur needs to be added in the reflection.
  86704. */
  86705. _this.REFLECTIONBLUR = false;
  86706. /**
  86707. * True if you want the material to fade to reflection at grazing angle.
  86708. */
  86709. _this.REFLECTIONFRESNEL = false;
  86710. /**
  86711. * True if you want the material to falloff as far as you move away from the scene center.
  86712. */
  86713. _this.REFLECTIONFALLOFF = false;
  86714. /**
  86715. * False if the current Webgl implementation does not support the texture lod extension.
  86716. */
  86717. _this.TEXTURELODSUPPORT = false;
  86718. /**
  86719. * True to ensure the data are premultiplied.
  86720. */
  86721. _this.PREMULTIPLYALPHA = false;
  86722. /**
  86723. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86724. */
  86725. _this.USERGBCOLOR = false;
  86726. /**
  86727. * True to add noise in order to reduce the banding effect.
  86728. */
  86729. _this.NOISE = false;
  86730. // Image Processing Configuration.
  86731. _this.IMAGEPROCESSING = false;
  86732. _this.VIGNETTE = false;
  86733. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86734. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86735. _this.TONEMAPPING = false;
  86736. _this.CONTRAST = false;
  86737. _this.COLORCURVES = false;
  86738. _this.COLORGRADING = false;
  86739. _this.COLORGRADING3D = false;
  86740. _this.SAMPLER3DGREENDEPTH = false;
  86741. _this.SAMPLER3DBGRMAP = false;
  86742. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86743. _this.EXPOSURE = false;
  86744. // Reflection.
  86745. _this.REFLECTION = false;
  86746. _this.REFLECTIONMAP_3D = false;
  86747. _this.REFLECTIONMAP_SPHERICAL = false;
  86748. _this.REFLECTIONMAP_PLANAR = false;
  86749. _this.REFLECTIONMAP_CUBIC = false;
  86750. _this.REFLECTIONMAP_PROJECTION = false;
  86751. _this.REFLECTIONMAP_SKYBOX = false;
  86752. _this.REFLECTIONMAP_EXPLICIT = false;
  86753. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86754. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86755. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86756. _this.INVERTCUBICMAP = false;
  86757. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86758. _this.LODINREFLECTIONALPHA = false;
  86759. _this.GAMMAREFLECTION = false;
  86760. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86761. // Default BJS.
  86762. _this.MAINUV1 = false;
  86763. _this.MAINUV2 = false;
  86764. _this.UV1 = false;
  86765. _this.UV2 = false;
  86766. _this.CLIPPLANE = false;
  86767. _this.POINTSIZE = false;
  86768. _this.FOG = false;
  86769. _this.NORMAL = false;
  86770. _this.NUM_BONE_INFLUENCERS = 0;
  86771. _this.BonesPerMesh = 0;
  86772. _this.INSTANCES = false;
  86773. _this.SHADOWFLOAT = false;
  86774. _this.rebuild();
  86775. return _this;
  86776. }
  86777. return BackgroundMaterialDefines;
  86778. }(BABYLON.MaterialDefines));
  86779. /**
  86780. * Background material used to create an efficient environement around your scene.
  86781. */
  86782. var BackgroundMaterial = /** @class */ (function (_super) {
  86783. __extends(BackgroundMaterial, _super);
  86784. /**
  86785. * Instantiates a Background Material in the given scene
  86786. * @param name The friendly name of the material
  86787. * @param scene The scene to add the material to
  86788. */
  86789. function BackgroundMaterial(name, scene) {
  86790. var _this = _super.call(this, name, scene) || this;
  86791. /**
  86792. * Key light Color (multiply against the R channel of the environement texture)
  86793. */
  86794. _this.primaryColor = BABYLON.Color3.White();
  86795. /**
  86796. * Key light Level (allowing HDR output of the background)
  86797. */
  86798. _this.primaryLevel = 1;
  86799. /**
  86800. * Secondary light Color (multiply against the G channel of the environement texture)
  86801. */
  86802. _this.secondaryColor = BABYLON.Color3.Gray();
  86803. /**
  86804. * Secondary light Level (allowing HDR output of the background)
  86805. */
  86806. _this.secondaryLevel = 1;
  86807. /**
  86808. * Tertiary light Color (multiply against the B channel of the environement texture)
  86809. */
  86810. _this.tertiaryColor = BABYLON.Color3.Black();
  86811. /**
  86812. * Tertiary light Level (allowing HDR output of the background)
  86813. */
  86814. _this.tertiaryLevel = 1;
  86815. /**
  86816. * Reflection Texture used in the material.
  86817. * Should be author in a specific way for the best result (refer to the documentation).
  86818. */
  86819. _this.reflectionTexture = null;
  86820. /**
  86821. * Reflection Texture level of blur.
  86822. *
  86823. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86824. * texture twice.
  86825. */
  86826. _this.reflectionBlur = 0;
  86827. /**
  86828. * Diffuse Texture used in the material.
  86829. * Should be author in a specific way for the best result (refer to the documentation).
  86830. */
  86831. _this.diffuseTexture = null;
  86832. _this._shadowLights = null;
  86833. /**
  86834. * Specify the list of lights casting shadow on the material.
  86835. * All scene shadow lights will be included if null.
  86836. */
  86837. _this.shadowLights = null;
  86838. /**
  86839. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86840. * soft lighting on the background.
  86841. */
  86842. _this.shadowBlurScale = 1;
  86843. /**
  86844. * Helps adjusting the shadow to a softer level if required.
  86845. * 0 means black shadows and 1 means no shadows.
  86846. */
  86847. _this.shadowLevel = 0;
  86848. /**
  86849. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86850. * It is usually zero but might be interesting to modify according to your setup.
  86851. */
  86852. _this.sceneCenter = BABYLON.Vector3.Zero();
  86853. /**
  86854. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86855. * This helps ensuring a nice transition when the camera goes under the ground.
  86856. */
  86857. _this.opacityFresnel = true;
  86858. /**
  86859. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86860. * This helps adding a mirror texture on the ground.
  86861. */
  86862. _this.reflectionFresnel = false;
  86863. /**
  86864. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86865. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86866. */
  86867. _this.reflectionFalloffDistance = 0.0;
  86868. /**
  86869. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86870. */
  86871. _this.reflectionAmount = 1.0;
  86872. /**
  86873. * This specifies the weight of the reflection at grazing angle.
  86874. */
  86875. _this.reflectionReflectance0 = 0.05;
  86876. /**
  86877. * This specifies the weight of the reflection at a perpendicular point of view.
  86878. */
  86879. _this.reflectionReflectance90 = 0.5;
  86880. /**
  86881. * Helps to directly use the maps channels instead of their level.
  86882. */
  86883. _this.useRGBColor = true;
  86884. /**
  86885. * This helps reducing the banding effect that could occur on the background.
  86886. */
  86887. _this.enableNoise = false;
  86888. _this._fovMultiplier = 1.0;
  86889. /**
  86890. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86891. * @type {boolean}
  86892. */
  86893. _this.useEquirectangularFOV = false;
  86894. _this._maxSimultaneousLights = 4;
  86895. /**
  86896. * Number of Simultaneous lights allowed on the material.
  86897. */
  86898. _this.maxSimultaneousLights = 4;
  86899. /**
  86900. * Keep track of the image processing observer to allow dispose and replace.
  86901. */
  86902. _this._imageProcessingObserver = null;
  86903. // Temp values kept as cache in the material.
  86904. _this._renderTargets = new BABYLON.SmartArray(16);
  86905. _this._reflectionControls = BABYLON.Vector4.Zero();
  86906. // Setup the default processing configuration to the scene.
  86907. _this._attachImageProcessingConfiguration(null);
  86908. _this.getRenderTargetTextures = function () {
  86909. _this._renderTargets.reset();
  86910. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86911. _this._renderTargets.push(_this._diffuseTexture);
  86912. }
  86913. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86914. _this._renderTargets.push(_this._reflectionTexture);
  86915. }
  86916. return _this._renderTargets;
  86917. };
  86918. return _this;
  86919. }
  86920. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86921. /**
  86922. * Sets the reflection reflectance fresnel values according to the default standard
  86923. * empirically know to work well :-)
  86924. */
  86925. set: function (value) {
  86926. var reflectionWeight = value;
  86927. if (reflectionWeight < 0.5) {
  86928. reflectionWeight = reflectionWeight * 2.0;
  86929. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86930. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86931. }
  86932. else {
  86933. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86934. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86935. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86936. }
  86937. },
  86938. enumerable: true,
  86939. configurable: true
  86940. });
  86941. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86942. /**
  86943. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86944. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86945. * Recommended to be keep at 1.0 except for special cases.
  86946. */
  86947. get: function () {
  86948. return this._fovMultiplier;
  86949. },
  86950. set: function (value) {
  86951. if (isNaN(value)) {
  86952. value = 1.0;
  86953. }
  86954. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86955. },
  86956. enumerable: true,
  86957. configurable: true
  86958. });
  86959. /**
  86960. * Attaches a new image processing configuration to the PBR Material.
  86961. * @param configuration (if null the scene configuration will be use)
  86962. */
  86963. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86964. var _this = this;
  86965. if (configuration === this._imageProcessingConfiguration) {
  86966. return;
  86967. }
  86968. // Detaches observer.
  86969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86971. }
  86972. // Pick the scene configuration if needed.
  86973. if (!configuration) {
  86974. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86975. }
  86976. else {
  86977. this._imageProcessingConfiguration = configuration;
  86978. }
  86979. // Attaches observer.
  86980. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86981. _this._markAllSubMeshesAsImageProcessingDirty();
  86982. });
  86983. };
  86984. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86985. /**
  86986. * Gets the image processing configuration used either in this material.
  86987. */
  86988. get: function () {
  86989. return this._imageProcessingConfiguration;
  86990. },
  86991. /**
  86992. * Sets the Default image processing configuration used either in the this material.
  86993. *
  86994. * If sets to null, the scene one is in use.
  86995. */
  86996. set: function (value) {
  86997. this._attachImageProcessingConfiguration(value);
  86998. // Ensure the effect will be rebuilt.
  86999. this._markAllSubMeshesAsTexturesDirty();
  87000. },
  87001. enumerable: true,
  87002. configurable: true
  87003. });
  87004. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  87005. /**
  87006. * Gets wether the color curves effect is enabled.
  87007. */
  87008. get: function () {
  87009. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87010. },
  87011. /**
  87012. * Sets wether the color curves effect is enabled.
  87013. */
  87014. set: function (value) {
  87015. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87016. },
  87017. enumerable: true,
  87018. configurable: true
  87019. });
  87020. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87021. /**
  87022. * Gets wether the color grading effect is enabled.
  87023. */
  87024. get: function () {
  87025. return this.imageProcessingConfiguration.colorGradingEnabled;
  87026. },
  87027. /**
  87028. * Gets wether the color grading effect is enabled.
  87029. */
  87030. set: function (value) {
  87031. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87032. },
  87033. enumerable: true,
  87034. configurable: true
  87035. });
  87036. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87037. /**
  87038. * Gets wether tonemapping is enabled or not.
  87039. */
  87040. get: function () {
  87041. return this._imageProcessingConfiguration.toneMappingEnabled;
  87042. },
  87043. /**
  87044. * Sets wether tonemapping is enabled or not
  87045. */
  87046. set: function (value) {
  87047. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87048. },
  87049. enumerable: true,
  87050. configurable: true
  87051. });
  87052. ;
  87053. ;
  87054. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87055. /**
  87056. * The camera exposure used on this material.
  87057. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87058. * This corresponds to a photographic exposure.
  87059. */
  87060. get: function () {
  87061. return this._imageProcessingConfiguration.exposure;
  87062. },
  87063. /**
  87064. * The camera exposure used on this material.
  87065. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87066. * This corresponds to a photographic exposure.
  87067. */
  87068. set: function (value) {
  87069. this._imageProcessingConfiguration.exposure = value;
  87070. },
  87071. enumerable: true,
  87072. configurable: true
  87073. });
  87074. ;
  87075. ;
  87076. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87077. /**
  87078. * Gets The camera contrast used on this material.
  87079. */
  87080. get: function () {
  87081. return this._imageProcessingConfiguration.contrast;
  87082. },
  87083. /**
  87084. * Sets The camera contrast used on this material.
  87085. */
  87086. set: function (value) {
  87087. this._imageProcessingConfiguration.contrast = value;
  87088. },
  87089. enumerable: true,
  87090. configurable: true
  87091. });
  87092. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87093. /**
  87094. * Gets the Color Grading 2D Lookup Texture.
  87095. */
  87096. get: function () {
  87097. return this._imageProcessingConfiguration.colorGradingTexture;
  87098. },
  87099. /**
  87100. * Sets the Color Grading 2D Lookup Texture.
  87101. */
  87102. set: function (value) {
  87103. this.imageProcessingConfiguration.colorGradingTexture = value;
  87104. },
  87105. enumerable: true,
  87106. configurable: true
  87107. });
  87108. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87109. /**
  87110. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87111. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87112. * 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;
  87113. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87114. */
  87115. get: function () {
  87116. return this.imageProcessingConfiguration.colorCurves;
  87117. },
  87118. /**
  87119. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87120. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87121. * 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;
  87122. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87123. */
  87124. set: function (value) {
  87125. this.imageProcessingConfiguration.colorCurves = value;
  87126. },
  87127. enumerable: true,
  87128. configurable: true
  87129. });
  87130. /**
  87131. * The entire material has been created in order to prevent overdraw.
  87132. * @returns false
  87133. */
  87134. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87135. return true;
  87136. };
  87137. /**
  87138. * The entire material has been created in order to prevent overdraw.
  87139. * @returns true if blending is enable
  87140. */
  87141. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87142. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87143. };
  87144. /**
  87145. * Checks wether the material is ready to be rendered for a given mesh.
  87146. * @param mesh The mesh to render
  87147. * @param subMesh The submesh to check against
  87148. * @param useInstances Specify wether or not the material is used with instances
  87149. * @returns true if all the dependencies are ready (Textures, Effects...)
  87150. */
  87151. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87152. var _this = this;
  87153. if (useInstances === void 0) { useInstances = false; }
  87154. if (subMesh.effect && this.isFrozen) {
  87155. if (this._wasPreviouslyReady) {
  87156. return true;
  87157. }
  87158. }
  87159. if (!subMesh._materialDefines) {
  87160. subMesh._materialDefines = new BackgroundMaterialDefines();
  87161. }
  87162. var scene = this.getScene();
  87163. var defines = subMesh._materialDefines;
  87164. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87165. if (defines._renderId === scene.getRenderId()) {
  87166. return true;
  87167. }
  87168. }
  87169. var engine = scene.getEngine();
  87170. // Lights
  87171. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87172. defines._needNormals = true;
  87173. // Textures
  87174. if (defines._areTexturesDirty) {
  87175. defines._needUVs = false;
  87176. if (scene.texturesEnabled) {
  87177. if (scene.getEngine().getCaps().textureLOD) {
  87178. defines.TEXTURELODSUPPORT = true;
  87179. }
  87180. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87181. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87182. return false;
  87183. }
  87184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87185. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87186. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87187. defines.OPACITYFRESNEL = this._opacityFresnel;
  87188. }
  87189. else {
  87190. defines.DIFFUSE = false;
  87191. defines.DIFFUSEHASALPHA = false;
  87192. defines.GAMMADIFFUSE = false;
  87193. defines.OPACITYFRESNEL = false;
  87194. }
  87195. var reflectionTexture = this._reflectionTexture;
  87196. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87197. if (!reflectionTexture.isReadyOrNotBlocking()) {
  87198. return false;
  87199. }
  87200. defines.REFLECTION = true;
  87201. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  87202. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  87203. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  87204. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  87205. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  87206. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  87207. defines.INVERTCUBICMAP = true;
  87208. }
  87209. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  87210. switch (reflectionTexture.coordinatesMode) {
  87211. case BABYLON.Texture.CUBIC_MODE:
  87212. case BABYLON.Texture.INVCUBIC_MODE:
  87213. defines.REFLECTIONMAP_CUBIC = true;
  87214. break;
  87215. case BABYLON.Texture.EXPLICIT_MODE:
  87216. defines.REFLECTIONMAP_EXPLICIT = true;
  87217. break;
  87218. case BABYLON.Texture.PLANAR_MODE:
  87219. defines.REFLECTIONMAP_PLANAR = true;
  87220. break;
  87221. case BABYLON.Texture.PROJECTION_MODE:
  87222. defines.REFLECTIONMAP_PROJECTION = true;
  87223. break;
  87224. case BABYLON.Texture.SKYBOX_MODE:
  87225. defines.REFLECTIONMAP_SKYBOX = true;
  87226. break;
  87227. case BABYLON.Texture.SPHERICAL_MODE:
  87228. defines.REFLECTIONMAP_SPHERICAL = true;
  87229. break;
  87230. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87231. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87232. break;
  87233. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87234. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87235. break;
  87236. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87237. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87238. break;
  87239. }
  87240. if (this.reflectionFresnel) {
  87241. defines.REFLECTIONFRESNEL = true;
  87242. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87243. this._reflectionControls.x = this.reflectionAmount;
  87244. this._reflectionControls.y = this.reflectionReflectance0;
  87245. this._reflectionControls.z = this.reflectionReflectance90;
  87246. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87247. }
  87248. else {
  87249. defines.REFLECTIONFRESNEL = false;
  87250. defines.REFLECTIONFALLOFF = false;
  87251. }
  87252. }
  87253. else {
  87254. defines.REFLECTION = false;
  87255. defines.REFLECTIONFALLOFF = false;
  87256. defines.REFLECTIONBLUR = false;
  87257. defines.REFLECTIONMAP_3D = false;
  87258. defines.REFLECTIONMAP_SPHERICAL = false;
  87259. defines.REFLECTIONMAP_PLANAR = false;
  87260. defines.REFLECTIONMAP_CUBIC = false;
  87261. defines.REFLECTIONMAP_PROJECTION = false;
  87262. defines.REFLECTIONMAP_SKYBOX = false;
  87263. defines.REFLECTIONMAP_EXPLICIT = false;
  87264. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87265. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87266. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87267. defines.INVERTCUBICMAP = false;
  87268. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87269. defines.LODINREFLECTIONALPHA = false;
  87270. defines.GAMMAREFLECTION = false;
  87271. }
  87272. }
  87273. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87274. defines.USERGBCOLOR = this._useRGBColor;
  87275. defines.NOISE = this._enableNoise;
  87276. }
  87277. if (defines._areImageProcessingDirty) {
  87278. if (!this._imageProcessingConfiguration.isReady()) {
  87279. return false;
  87280. }
  87281. this._imageProcessingConfiguration.prepareDefines(defines);
  87282. }
  87283. // Misc.
  87284. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87285. // Values that need to be evaluated on every frame
  87286. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87287. // Attribs
  87288. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87289. if (mesh) {
  87290. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87291. mesh.createNormals(true);
  87292. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87293. }
  87294. }
  87295. }
  87296. // Get correct effect
  87297. if (defines.isDirty) {
  87298. defines.markAsProcessed();
  87299. scene.resetCachedMaterial();
  87300. // Fallbacks
  87301. var fallbacks = new BABYLON.EffectFallbacks();
  87302. if (defines.FOG) {
  87303. fallbacks.addFallback(0, "FOG");
  87304. }
  87305. if (defines.POINTSIZE) {
  87306. fallbacks.addFallback(1, "POINTSIZE");
  87307. }
  87308. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87309. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87310. fallbacks.addCPUSkinningFallback(0, mesh);
  87311. }
  87312. //Attributes
  87313. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87314. if (defines.NORMAL) {
  87315. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87316. }
  87317. if (defines.UV1) {
  87318. attribs.push(BABYLON.VertexBuffer.UVKind);
  87319. }
  87320. if (defines.UV2) {
  87321. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87322. }
  87323. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87324. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87325. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87326. "vFogInfos", "vFogColor", "pointSize",
  87327. "vClipPlane", "mBones",
  87328. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87329. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87330. "shadowLevel", "alpha",
  87331. "vBackgroundCenter", "vReflectionControl",
  87332. "vDiffuseInfos", "diffuseMatrix",
  87333. ];
  87334. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87335. var uniformBuffers = ["Material", "Scene"];
  87336. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87337. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87338. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87339. uniformsNames: uniforms,
  87340. uniformBuffersNames: uniformBuffers,
  87341. samplers: samplers,
  87342. defines: defines,
  87343. maxSimultaneousLights: this._maxSimultaneousLights
  87344. });
  87345. var onCompiled = function (effect) {
  87346. if (_this.onCompiled) {
  87347. _this.onCompiled(effect);
  87348. }
  87349. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87350. };
  87351. var join = defines.toString();
  87352. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87353. attributes: attribs,
  87354. uniformsNames: uniforms,
  87355. uniformBuffersNames: uniformBuffers,
  87356. samplers: samplers,
  87357. defines: join,
  87358. fallbacks: fallbacks,
  87359. onCompiled: onCompiled,
  87360. onError: this.onError,
  87361. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87362. }, engine), defines);
  87363. this.buildUniformLayout();
  87364. }
  87365. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87366. return false;
  87367. }
  87368. defines._renderId = scene.getRenderId();
  87369. this._wasPreviouslyReady = true;
  87370. return true;
  87371. };
  87372. /**
  87373. * Build the uniform buffer used in the material.
  87374. */
  87375. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87376. // Order is important !
  87377. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87378. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87379. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87380. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87381. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87382. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87383. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87384. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87385. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87386. this._uniformBuffer.addUniform("pointSize", 1);
  87387. this._uniformBuffer.addUniform("shadowLevel", 1);
  87388. this._uniformBuffer.addUniform("alpha", 1);
  87389. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87390. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87391. this._uniformBuffer.create();
  87392. };
  87393. /**
  87394. * Unbind the material.
  87395. */
  87396. BackgroundMaterial.prototype.unbind = function () {
  87397. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87398. this._uniformBuffer.setTexture("diffuseSampler", null);
  87399. }
  87400. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87401. this._uniformBuffer.setTexture("reflectionSampler", null);
  87402. }
  87403. _super.prototype.unbind.call(this);
  87404. };
  87405. /**
  87406. * Bind only the world matrix to the material.
  87407. * @param world The world matrix to bind.
  87408. */
  87409. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87410. this._activeEffect.setMatrix("world", world);
  87411. };
  87412. /**
  87413. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87414. * @param world The world matrix to bind.
  87415. * @param subMesh The submesh to bind for.
  87416. */
  87417. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87418. var scene = this.getScene();
  87419. var defines = subMesh._materialDefines;
  87420. if (!defines) {
  87421. return;
  87422. }
  87423. var effect = subMesh.effect;
  87424. if (!effect) {
  87425. return;
  87426. }
  87427. this._activeEffect = effect;
  87428. // Matrices
  87429. this.bindOnlyWorldMatrix(world);
  87430. // Bones
  87431. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87432. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87433. if (mustRebind) {
  87434. this._uniformBuffer.bindToEffect(effect, "Material");
  87435. this.bindViewProjection(effect);
  87436. var reflectionTexture = this._reflectionTexture;
  87437. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87438. // Texture uniforms
  87439. if (scene.texturesEnabled) {
  87440. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87441. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87442. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87443. }
  87444. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87445. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87446. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87447. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87448. }
  87449. }
  87450. if (this.shadowLevel > 0) {
  87451. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87452. }
  87453. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87454. // Point size
  87455. if (this.pointsCloud) {
  87456. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87457. }
  87458. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87459. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87460. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87461. }
  87462. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87463. // Textures
  87464. if (scene.texturesEnabled) {
  87465. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87466. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87467. }
  87468. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87469. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87470. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87471. }
  87472. else if (!defines.REFLECTIONBLUR) {
  87473. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87474. }
  87475. else {
  87476. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87477. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87478. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87479. }
  87480. if (defines.REFLECTIONFRESNEL) {
  87481. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87482. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87483. }
  87484. }
  87485. }
  87486. // Clip plane
  87487. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87488. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87489. }
  87490. if (mustRebind || !this.isFrozen) {
  87491. if (scene.lightsEnabled) {
  87492. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87493. }
  87494. // View
  87495. this.bindView(effect);
  87496. // Fog
  87497. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87498. // image processing
  87499. this._imageProcessingConfiguration.bind(this._activeEffect);
  87500. }
  87501. this._uniformBuffer.update();
  87502. this._afterBind(mesh);
  87503. };
  87504. /**
  87505. * Dispose the material.
  87506. * @param forceDisposeEffect Force disposal of the associated effect.
  87507. * @param forceDisposeTextures Force disposal of the associated textures.
  87508. */
  87509. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87510. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87511. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87512. if (forceDisposeTextures) {
  87513. if (this.diffuseTexture) {
  87514. this.diffuseTexture.dispose();
  87515. }
  87516. if (this.reflectionTexture) {
  87517. this.reflectionTexture.dispose();
  87518. }
  87519. }
  87520. this._renderTargets.dispose();
  87521. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87522. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87523. }
  87524. _super.prototype.dispose.call(this, forceDisposeEffect);
  87525. };
  87526. /**
  87527. * Clones the material.
  87528. * @param name The cloned name.
  87529. * @returns The cloned material.
  87530. */
  87531. BackgroundMaterial.prototype.clone = function (name) {
  87532. var _this = this;
  87533. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87534. };
  87535. /**
  87536. * Serializes the current material to its JSON representation.
  87537. * @returns The JSON representation.
  87538. */
  87539. BackgroundMaterial.prototype.serialize = function () {
  87540. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87541. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87542. return serializationObject;
  87543. };
  87544. /**
  87545. * Gets the class name of the material
  87546. * @returns "BackgroundMaterial"
  87547. */
  87548. BackgroundMaterial.prototype.getClassName = function () {
  87549. return "BackgroundMaterial";
  87550. };
  87551. /**
  87552. * Parse a JSON input to create back a background material.
  87553. * @param source The JSON data to parse
  87554. * @param scene The scene to create the parsed material in
  87555. * @param rootUrl The root url of the assets the material depends upon
  87556. * @returns the instantiated BackgroundMaterial.
  87557. */
  87558. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87559. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87560. };
  87561. /**
  87562. * Standard reflectance value at parallel view angle.
  87563. */
  87564. BackgroundMaterial.StandardReflectance0 = 0.05;
  87565. /**
  87566. * Standard reflectance value at grazing angle.
  87567. */
  87568. BackgroundMaterial.StandardReflectance90 = 0.5;
  87569. __decorate([
  87570. BABYLON.serializeAsColor3()
  87571. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87572. __decorate([
  87573. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87574. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87575. __decorate([
  87576. BABYLON.serialize()
  87577. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87578. __decorate([
  87579. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87580. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87581. __decorate([
  87582. BABYLON.serializeAsColor3()
  87583. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87584. __decorate([
  87585. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87586. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87587. __decorate([
  87588. BABYLON.serialize()
  87589. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87590. __decorate([
  87591. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87592. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87593. __decorate([
  87594. BABYLON.serializeAsColor3()
  87595. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87596. __decorate([
  87597. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87598. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87599. __decorate([
  87600. BABYLON.serialize()
  87601. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87602. __decorate([
  87603. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87604. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87605. __decorate([
  87606. BABYLON.serializeAsTexture()
  87607. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87608. __decorate([
  87609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87610. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87611. __decorate([
  87612. BABYLON.serialize()
  87613. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87614. __decorate([
  87615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87616. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87617. __decorate([
  87618. BABYLON.serializeAsTexture()
  87619. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87620. __decorate([
  87621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87622. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87623. __decorate([
  87624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87625. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87626. __decorate([
  87627. BABYLON.serialize()
  87628. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87629. __decorate([
  87630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87631. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87632. __decorate([
  87633. BABYLON.serialize()
  87634. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87635. __decorate([
  87636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87637. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87638. __decorate([
  87639. BABYLON.serializeAsVector3()
  87640. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87641. __decorate([
  87642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87643. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87644. __decorate([
  87645. BABYLON.serialize()
  87646. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87647. __decorate([
  87648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87649. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87650. __decorate([
  87651. BABYLON.serialize()
  87652. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87653. __decorate([
  87654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87655. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87656. __decorate([
  87657. BABYLON.serialize()
  87658. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87659. __decorate([
  87660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87661. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87662. __decorate([
  87663. BABYLON.serialize()
  87664. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87665. __decorate([
  87666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87667. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87668. __decorate([
  87669. BABYLON.serialize()
  87670. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87671. __decorate([
  87672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87673. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87674. __decorate([
  87675. BABYLON.serialize()
  87676. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87677. __decorate([
  87678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87679. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87680. __decorate([
  87681. BABYLON.serialize()
  87682. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87683. __decorate([
  87684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87685. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87686. __decorate([
  87687. BABYLON.serialize()
  87688. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87689. __decorate([
  87690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87691. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87692. __decorate([
  87693. BABYLON.serialize()
  87694. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87695. __decorate([
  87696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87697. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87698. __decorate([
  87699. BABYLON.serializeAsImageProcessingConfiguration()
  87700. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87701. return BackgroundMaterial;
  87702. }(BABYLON.PushMaterial));
  87703. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87704. })(BABYLON || (BABYLON = {}));
  87705. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87706. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87707. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87708. s = arguments[i];
  87709. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87710. t[p] = s[p];
  87711. }
  87712. return t;
  87713. };
  87714. var BABYLON;
  87715. (function (BABYLON) {
  87716. /**
  87717. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87718. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87719. * It also helps with the default setup of your imageProcessing configuration.
  87720. */
  87721. var EnvironmentHelper = /** @class */ (function () {
  87722. /**
  87723. * constructor
  87724. * @param options
  87725. * @param scene The scene to add the material to
  87726. */
  87727. function EnvironmentHelper(options, scene) {
  87728. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87729. this._scene = scene;
  87730. this._setupBackground();
  87731. this._setupImageProcessing();
  87732. }
  87733. /**
  87734. * Creates the default options for the helper.
  87735. */
  87736. EnvironmentHelper._getDefaultOptions = function () {
  87737. return {
  87738. createGround: true,
  87739. groundSize: 15,
  87740. groundTexture: this._groundTextureCDNUrl,
  87741. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87742. groundOpacity: 0.9,
  87743. enableGroundShadow: true,
  87744. groundShadowLevel: 0.5,
  87745. enableGroundMirror: false,
  87746. groundMirrorSizeRatio: 0.3,
  87747. groundMirrorBlurKernel: 64,
  87748. groundMirrorAmount: 1,
  87749. groundMirrorFresnelWeight: 1,
  87750. groundMirrorFallOffDistance: 0,
  87751. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87752. groundYBias: 0.00001,
  87753. createSkybox: true,
  87754. skyboxSize: 20,
  87755. skyboxTexture: this._skyboxTextureCDNUrl,
  87756. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87757. backgroundYRotation: 0,
  87758. sizeAuto: true,
  87759. rootPosition: BABYLON.Vector3.Zero(),
  87760. setupImageProcessing: true,
  87761. environmentTexture: this._environmentTextureCDNUrl,
  87762. cameraExposure: 0.8,
  87763. cameraContrast: 1.2,
  87764. toneMappingEnabled: true,
  87765. };
  87766. };
  87767. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87768. /**
  87769. * Gets the root mesh created by the helper.
  87770. */
  87771. get: function () {
  87772. return this._rootMesh;
  87773. },
  87774. enumerable: true,
  87775. configurable: true
  87776. });
  87777. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87778. /**
  87779. * Gets the skybox created by the helper.
  87780. */
  87781. get: function () {
  87782. return this._skybox;
  87783. },
  87784. enumerable: true,
  87785. configurable: true
  87786. });
  87787. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87788. /**
  87789. * Gets the skybox texture created by the helper.
  87790. */
  87791. get: function () {
  87792. return this._skyboxTexture;
  87793. },
  87794. enumerable: true,
  87795. configurable: true
  87796. });
  87797. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87798. /**
  87799. * Gets the skybox material created by the helper.
  87800. */
  87801. get: function () {
  87802. return this._skyboxMaterial;
  87803. },
  87804. enumerable: true,
  87805. configurable: true
  87806. });
  87807. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87808. /**
  87809. * Gets the ground mesh created by the helper.
  87810. */
  87811. get: function () {
  87812. return this._ground;
  87813. },
  87814. enumerable: true,
  87815. configurable: true
  87816. });
  87817. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87818. /**
  87819. * Gets the ground texture created by the helper.
  87820. */
  87821. get: function () {
  87822. return this._groundTexture;
  87823. },
  87824. enumerable: true,
  87825. configurable: true
  87826. });
  87827. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87828. /**
  87829. * Gets the ground mirror created by the helper.
  87830. */
  87831. get: function () {
  87832. return this._groundMirror;
  87833. },
  87834. enumerable: true,
  87835. configurable: true
  87836. });
  87837. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87838. /**
  87839. * Gets the ground mirror render list to helps pushing the meshes
  87840. * you wish in the ground reflection.
  87841. */
  87842. get: function () {
  87843. if (this._groundMirror) {
  87844. return this._groundMirror.renderList;
  87845. }
  87846. return null;
  87847. },
  87848. enumerable: true,
  87849. configurable: true
  87850. });
  87851. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87852. /**
  87853. * Gets the ground material created by the helper.
  87854. */
  87855. get: function () {
  87856. return this._groundMaterial;
  87857. },
  87858. enumerable: true,
  87859. configurable: true
  87860. });
  87861. /**
  87862. * Updates the background according to the new options
  87863. * @param options
  87864. */
  87865. EnvironmentHelper.prototype.updateOptions = function (options) {
  87866. var newOptions = __assign({}, this._options, options);
  87867. if (this._ground && !newOptions.createGround) {
  87868. this._ground.dispose();
  87869. this._ground = null;
  87870. }
  87871. if (this._groundMaterial && !newOptions.createGround) {
  87872. this._groundMaterial.dispose();
  87873. this._groundMaterial = null;
  87874. }
  87875. if (this._groundTexture) {
  87876. if (this._options.groundTexture != newOptions.groundTexture) {
  87877. this._groundTexture.dispose();
  87878. this._groundTexture = null;
  87879. }
  87880. }
  87881. if (this._skybox && !newOptions.createSkybox) {
  87882. this._skybox.dispose();
  87883. this._skybox = null;
  87884. }
  87885. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87886. this._skyboxMaterial.dispose();
  87887. this._skyboxMaterial = null;
  87888. }
  87889. if (this._skyboxTexture) {
  87890. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87891. this._skyboxTexture.dispose();
  87892. this._skyboxTexture = null;
  87893. }
  87894. }
  87895. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87896. this._groundMirror.dispose();
  87897. this._groundMirror = null;
  87898. }
  87899. if (this._scene.environmentTexture) {
  87900. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87901. this._scene.environmentTexture.dispose();
  87902. }
  87903. }
  87904. this._options = newOptions;
  87905. this._setupBackground();
  87906. this._setupImageProcessing();
  87907. };
  87908. /**
  87909. * Sets the primary color of all the available elements.
  87910. * @param color
  87911. */
  87912. EnvironmentHelper.prototype.setMainColor = function (color) {
  87913. if (this.groundMaterial) {
  87914. this.groundMaterial.primaryColor = color;
  87915. }
  87916. if (this.skyboxMaterial) {
  87917. this.skyboxMaterial.primaryColor = color;
  87918. }
  87919. if (this.groundMirror) {
  87920. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87921. }
  87922. };
  87923. /**
  87924. * Setup the image processing according to the specified options.
  87925. */
  87926. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87927. if (this._options.setupImageProcessing) {
  87928. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87929. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87930. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87931. this._setupEnvironmentTexture();
  87932. }
  87933. };
  87934. /**
  87935. * Setup the environment texture according to the specified options.
  87936. */
  87937. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87938. if (this._scene.environmentTexture) {
  87939. return;
  87940. }
  87941. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87942. this._scene.environmentTexture = this._options.environmentTexture;
  87943. return;
  87944. }
  87945. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87946. this._scene.environmentTexture = environmentTexture;
  87947. };
  87948. /**
  87949. * Setup the background according to the specified options.
  87950. */
  87951. EnvironmentHelper.prototype._setupBackground = function () {
  87952. if (!this._rootMesh) {
  87953. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87954. }
  87955. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87956. var sceneSize = this._getSceneSize();
  87957. if (this._options.createGround) {
  87958. this._setupGround(sceneSize);
  87959. this._setupGroundMaterial();
  87960. this._setupGroundDiffuseTexture();
  87961. if (this._options.enableGroundMirror) {
  87962. this._setupGroundMirrorTexture(sceneSize);
  87963. }
  87964. this._setupMirrorInGroundMaterial();
  87965. }
  87966. if (this._options.createSkybox) {
  87967. this._setupSkybox(sceneSize);
  87968. this._setupSkyboxMaterial();
  87969. this._setupSkyboxReflectionTexture();
  87970. }
  87971. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87972. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87973. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87974. };
  87975. /**
  87976. * Get the scene sizes according to the setup.
  87977. */
  87978. EnvironmentHelper.prototype._getSceneSize = function () {
  87979. var groundSize = this._options.groundSize;
  87980. var skyboxSize = this._options.skyboxSize;
  87981. var rootPosition = this._options.rootPosition;
  87982. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87983. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87984. }
  87985. var sceneExtends = this._scene.getWorldExtends();
  87986. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87987. if (this._options.sizeAuto) {
  87988. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87989. this._scene.activeCamera.upperRadiusLimit) {
  87990. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87991. skyboxSize = groundSize;
  87992. }
  87993. var sceneDiagonalLenght = sceneDiagonal.length();
  87994. if (sceneDiagonalLenght > groundSize) {
  87995. groundSize = sceneDiagonalLenght * 2;
  87996. skyboxSize = groundSize;
  87997. }
  87998. // 10 % bigger.
  87999. groundSize *= 1.1;
  88000. skyboxSize *= 1.5;
  88001. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  88002. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  88003. }
  88004. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88005. };
  88006. /**
  88007. * Setup the ground according to the specified options.
  88008. */
  88009. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  88010. var _this = this;
  88011. if (!this._ground) {
  88012. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  88013. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88014. this._ground.parent = this._rootMesh;
  88015. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88016. }
  88017. this._ground.receiveShadows = this._options.enableGroundShadow;
  88018. };
  88019. /**
  88020. * Setup the ground material according to the specified options.
  88021. */
  88022. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88023. if (!this._groundMaterial) {
  88024. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88025. }
  88026. this._groundMaterial.alpha = this._options.groundOpacity;
  88027. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88028. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88029. this._groundMaterial.primaryLevel = 1;
  88030. this._groundMaterial.primaryColor = this._options.groundColor;
  88031. this._groundMaterial.secondaryLevel = 0;
  88032. this._groundMaterial.tertiaryLevel = 0;
  88033. this._groundMaterial.useRGBColor = false;
  88034. this._groundMaterial.enableNoise = true;
  88035. if (this._ground) {
  88036. this._ground.material = this._groundMaterial;
  88037. }
  88038. };
  88039. /**
  88040. * Setup the ground diffuse texture according to the specified options.
  88041. */
  88042. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88043. if (!this._groundMaterial) {
  88044. return;
  88045. }
  88046. if (this._groundTexture) {
  88047. return;
  88048. }
  88049. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88050. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88051. return;
  88052. }
  88053. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88054. diffuseTexture.gammaSpace = false;
  88055. diffuseTexture.hasAlpha = true;
  88056. this._groundMaterial.diffuseTexture = diffuseTexture;
  88057. };
  88058. /**
  88059. * Setup the ground mirror texture according to the specified options.
  88060. */
  88061. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88062. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88063. if (!this._groundMirror) {
  88064. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88065. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88066. this._groundMirror.anisotropicFilteringLevel = 1;
  88067. this._groundMirror.wrapU = wrapping;
  88068. this._groundMirror.wrapV = wrapping;
  88069. this._groundMirror.gammaSpace = false;
  88070. if (this._groundMirror.renderList) {
  88071. for (var i = 0; i < this._scene.meshes.length; i++) {
  88072. var mesh = this._scene.meshes[i];
  88073. if (mesh !== this._ground &&
  88074. mesh !== this._skybox &&
  88075. mesh !== this._rootMesh) {
  88076. this._groundMirror.renderList.push(mesh);
  88077. }
  88078. }
  88079. }
  88080. }
  88081. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88082. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88083. };
  88084. /**
  88085. * Setup the ground to receive the mirror texture.
  88086. */
  88087. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88088. if (this._groundMaterial) {
  88089. this._groundMaterial.reflectionTexture = this._groundMirror;
  88090. this._groundMaterial.reflectionFresnel = true;
  88091. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88092. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88093. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88094. }
  88095. };
  88096. /**
  88097. * Setup the skybox according to the specified options.
  88098. */
  88099. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88100. var _this = this;
  88101. if (!this._skybox) {
  88102. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88103. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88104. }
  88105. this._skybox.parent = this._rootMesh;
  88106. };
  88107. /**
  88108. * Setup the skybox material according to the specified options.
  88109. */
  88110. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88111. if (!this._skybox) {
  88112. return;
  88113. }
  88114. if (!this._skyboxMaterial) {
  88115. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88116. }
  88117. this._skyboxMaterial.useRGBColor = false;
  88118. this._skyboxMaterial.primaryLevel = 1;
  88119. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88120. this._skyboxMaterial.secondaryLevel = 0;
  88121. this._skyboxMaterial.tertiaryLevel = 0;
  88122. this._skyboxMaterial.enableNoise = true;
  88123. this._skybox.material = this._skyboxMaterial;
  88124. };
  88125. /**
  88126. * Setup the skybox reflection texture according to the specified options.
  88127. */
  88128. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88129. if (!this._skyboxMaterial) {
  88130. return;
  88131. }
  88132. if (this._skyboxTexture) {
  88133. return;
  88134. }
  88135. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88136. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88137. return;
  88138. }
  88139. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88140. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88141. this._skyboxTexture.gammaSpace = false;
  88142. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88143. };
  88144. /**
  88145. * Dispose all the elements created by the Helper.
  88146. */
  88147. EnvironmentHelper.prototype.dispose = function () {
  88148. if (this._groundMaterial) {
  88149. this._groundMaterial.dispose(true, true);
  88150. }
  88151. if (this._skyboxMaterial) {
  88152. this._skyboxMaterial.dispose(true, true);
  88153. }
  88154. this._rootMesh.dispose(false);
  88155. };
  88156. /**
  88157. * Default ground texture URL.
  88158. */
  88159. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88160. /**
  88161. * Default skybox texture URL.
  88162. */
  88163. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88164. /**
  88165. * Default environment texture URL.
  88166. */
  88167. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88168. return EnvironmentHelper;
  88169. }());
  88170. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88171. })(BABYLON || (BABYLON = {}));
  88172. //# sourceMappingURL=babylon.environmentHelper.js.map
  88173. 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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88174. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\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#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  88175. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88176. var BABYLON;
  88177. (function (BABYLON) {
  88178. var GridMaterialDefines = /** @class */ (function (_super) {
  88179. __extends(GridMaterialDefines, _super);
  88180. function GridMaterialDefines() {
  88181. var _this = _super.call(this) || this;
  88182. _this.TRANSPARENT = false;
  88183. _this.FOG = false;
  88184. _this.PREMULTIPLYALPHA = false;
  88185. _this.rebuild();
  88186. return _this;
  88187. }
  88188. return GridMaterialDefines;
  88189. }(BABYLON.MaterialDefines));
  88190. /**
  88191. * The grid materials allows you to wrap any shape with a grid.
  88192. * Colors are customizable.
  88193. */
  88194. var GridMaterial = /** @class */ (function (_super) {
  88195. __extends(GridMaterial, _super);
  88196. /**
  88197. * constructor
  88198. * @param name The name given to the material in order to identify it afterwards.
  88199. * @param scene The scene the material is used in.
  88200. */
  88201. function GridMaterial(name, scene) {
  88202. var _this = _super.call(this, name, scene) || this;
  88203. /**
  88204. * Main color of the grid (e.g. between lines)
  88205. */
  88206. _this.mainColor = BABYLON.Color3.Black();
  88207. /**
  88208. * Color of the grid lines.
  88209. */
  88210. _this.lineColor = BABYLON.Color3.Teal();
  88211. /**
  88212. * The scale of the grid compared to unit.
  88213. */
  88214. _this.gridRatio = 1.0;
  88215. /**
  88216. * Allows setting an offset for the grid lines.
  88217. */
  88218. _this.gridOffset = BABYLON.Vector3.Zero();
  88219. /**
  88220. * The frequency of thicker lines.
  88221. */
  88222. _this.majorUnitFrequency = 10;
  88223. /**
  88224. * The visibility of minor units in the grid.
  88225. */
  88226. _this.minorUnitVisibility = 0.33;
  88227. /**
  88228. * The grid opacity outside of the lines.
  88229. */
  88230. _this.opacity = 1.0;
  88231. /**
  88232. * Determine RBG output is premultiplied by alpha value.
  88233. */
  88234. _this.preMultiplyAlpha = false;
  88235. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  88236. return _this;
  88237. }
  88238. /**
  88239. * Returns wehter or not the grid requires alpha blending.
  88240. */
  88241. GridMaterial.prototype.needAlphaBlending = function () {
  88242. return this.opacity < 1.0;
  88243. };
  88244. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  88245. return this.needAlphaBlending();
  88246. };
  88247. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88248. if (this.isFrozen) {
  88249. if (this._wasPreviouslyReady && subMesh.effect) {
  88250. return true;
  88251. }
  88252. }
  88253. if (!subMesh._materialDefines) {
  88254. subMesh._materialDefines = new GridMaterialDefines();
  88255. }
  88256. var defines = subMesh._materialDefines;
  88257. var scene = this.getScene();
  88258. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88259. if (this._renderId === scene.getRenderId()) {
  88260. return true;
  88261. }
  88262. }
  88263. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  88264. defines.TRANSPARENT = !defines.TRANSPARENT;
  88265. defines.markAsUnprocessed();
  88266. }
  88267. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  88268. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  88269. defines.markAsUnprocessed();
  88270. }
  88271. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  88272. // Get correct effect
  88273. if (defines.isDirty) {
  88274. defines.markAsProcessed();
  88275. scene.resetCachedMaterial();
  88276. // Attributes
  88277. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88278. // Defines
  88279. var join = defines.toString();
  88280. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  88281. }
  88282. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88283. return false;
  88284. }
  88285. this._renderId = scene.getRenderId();
  88286. this._wasPreviouslyReady = true;
  88287. return true;
  88288. };
  88289. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88290. var scene = this.getScene();
  88291. var defines = subMesh._materialDefines;
  88292. if (!defines) {
  88293. return;
  88294. }
  88295. var effect = subMesh.effect;
  88296. if (!effect) {
  88297. return;
  88298. }
  88299. this._activeEffect = effect;
  88300. // Matrices
  88301. this.bindOnlyWorldMatrix(world);
  88302. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  88303. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  88304. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  88305. // Uniforms
  88306. if (this._mustRebind(scene, effect)) {
  88307. this._activeEffect.setColor3("mainColor", this.mainColor);
  88308. this._activeEffect.setColor3("lineColor", this.lineColor);
  88309. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  88310. this._gridControl.x = this.gridRatio;
  88311. this._gridControl.y = Math.round(this.majorUnitFrequency);
  88312. this._gridControl.z = this.minorUnitVisibility;
  88313. this._gridControl.w = this.opacity;
  88314. this._activeEffect.setVector4("gridControl", this._gridControl);
  88315. }
  88316. // Fog
  88317. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88318. this._afterBind(mesh, this._activeEffect);
  88319. };
  88320. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  88321. _super.prototype.dispose.call(this, forceDisposeEffect);
  88322. };
  88323. GridMaterial.prototype.clone = function (name) {
  88324. var _this = this;
  88325. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  88326. };
  88327. GridMaterial.prototype.serialize = function () {
  88328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88329. serializationObject.customType = "BABYLON.GridMaterial";
  88330. return serializationObject;
  88331. };
  88332. GridMaterial.prototype.getClassName = function () {
  88333. return "GridMaterial";
  88334. };
  88335. GridMaterial.Parse = function (source, scene, rootUrl) {
  88336. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  88337. };
  88338. __decorate([
  88339. BABYLON.serializeAsColor3()
  88340. ], GridMaterial.prototype, "mainColor", void 0);
  88341. __decorate([
  88342. BABYLON.serializeAsColor3()
  88343. ], GridMaterial.prototype, "lineColor", void 0);
  88344. __decorate([
  88345. BABYLON.serialize()
  88346. ], GridMaterial.prototype, "gridRatio", void 0);
  88347. __decorate([
  88348. BABYLON.serializeAsColor3()
  88349. ], GridMaterial.prototype, "gridOffset", void 0);
  88350. __decorate([
  88351. BABYLON.serialize()
  88352. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  88353. __decorate([
  88354. BABYLON.serialize()
  88355. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  88356. __decorate([
  88357. BABYLON.serialize()
  88358. ], GridMaterial.prototype, "opacity", void 0);
  88359. __decorate([
  88360. BABYLON.serialize()
  88361. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88362. return GridMaterial;
  88363. }(BABYLON.PushMaterial));
  88364. BABYLON.GridMaterial = GridMaterial;
  88365. })(BABYLON || (BABYLON = {}));
  88366. //# sourceMappingURL=babylon.gridmaterial.js.map
  88367. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  88368. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  88369. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88370. var BABYLON;
  88371. (function (BABYLON) {
  88372. var GLTFLoaderCoordinateSystemMode;
  88373. (function (GLTFLoaderCoordinateSystemMode) {
  88374. /**
  88375. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88376. */
  88377. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88378. /**
  88379. * Sets the useRightHandedSystem flag on the scene.
  88380. */
  88381. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88382. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88383. var GLTFLoaderAnimationStartMode;
  88384. (function (GLTFLoaderAnimationStartMode) {
  88385. /**
  88386. * No animation will start.
  88387. */
  88388. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88389. /**
  88390. * The first animation will start.
  88391. */
  88392. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88393. /**
  88394. * All animations will start.
  88395. */
  88396. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88397. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88398. var GLTFLoaderState;
  88399. (function (GLTFLoaderState) {
  88400. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88401. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88402. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88403. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88404. var GLTFFileLoader = /** @class */ (function () {
  88405. function GLTFFileLoader() {
  88406. // #region Common options
  88407. /**
  88408. * Raised when the asset has been parsed.
  88409. * The data.json property stores the glTF JSON.
  88410. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88411. */
  88412. this.onParsedObservable = new BABYLON.Observable();
  88413. // #endregion
  88414. // #region V2 options
  88415. /**
  88416. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88417. */
  88418. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88419. /**
  88420. * The animation start mode (NONE, FIRST, ALL).
  88421. */
  88422. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88423. /**
  88424. * Set to true to compile materials before raising the success callback.
  88425. */
  88426. this.compileMaterials = false;
  88427. /**
  88428. * Set to true to also compile materials with clip planes.
  88429. */
  88430. this.useClipPlane = false;
  88431. /**
  88432. * Set to true to compile shadow generators before raising the success callback.
  88433. */
  88434. this.compileShadowGenerators = false;
  88435. /**
  88436. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88437. */
  88438. this.onMeshLoadedObservable = new BABYLON.Observable();
  88439. /**
  88440. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88441. */
  88442. this.onTextureLoadedObservable = new BABYLON.Observable();
  88443. /**
  88444. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88445. */
  88446. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88447. /**
  88448. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88449. * For assets with LODs, raised when all of the LODs are complete.
  88450. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88451. */
  88452. this.onCompleteObservable = new BABYLON.Observable();
  88453. /**
  88454. * Raised when the loader is disposed.
  88455. */
  88456. this.onDisposeObservable = new BABYLON.Observable();
  88457. /**
  88458. * Raised after a loader extension is created.
  88459. * Set additional options for a loader extension in this event.
  88460. */
  88461. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88462. // #endregion
  88463. this._loader = null;
  88464. this.name = "gltf";
  88465. this.extensions = {
  88466. ".gltf": { isBinary: false },
  88467. ".glb": { isBinary: true }
  88468. };
  88469. }
  88470. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88471. set: function (callback) {
  88472. if (this._onParsedObserver) {
  88473. this.onParsedObservable.remove(this._onParsedObserver);
  88474. }
  88475. this._onParsedObserver = this.onParsedObservable.add(callback);
  88476. },
  88477. enumerable: true,
  88478. configurable: true
  88479. });
  88480. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88481. set: function (callback) {
  88482. if (this._onMeshLoadedObserver) {
  88483. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88484. }
  88485. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88486. },
  88487. enumerable: true,
  88488. configurable: true
  88489. });
  88490. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88491. set: function (callback) {
  88492. if (this._onTextureLoadedObserver) {
  88493. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88494. }
  88495. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88496. },
  88497. enumerable: true,
  88498. configurable: true
  88499. });
  88500. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88501. set: function (callback) {
  88502. if (this._onMaterialLoadedObserver) {
  88503. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88504. }
  88505. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88506. },
  88507. enumerable: true,
  88508. configurable: true
  88509. });
  88510. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88511. set: function (callback) {
  88512. if (this._onCompleteObserver) {
  88513. this.onCompleteObservable.remove(this._onCompleteObserver);
  88514. }
  88515. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88516. },
  88517. enumerable: true,
  88518. configurable: true
  88519. });
  88520. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88521. set: function (callback) {
  88522. if (this._onDisposeObserver) {
  88523. this.onDisposeObservable.remove(this._onDisposeObserver);
  88524. }
  88525. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88526. },
  88527. enumerable: true,
  88528. configurable: true
  88529. });
  88530. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88531. set: function (callback) {
  88532. if (this._onExtensionLoadedObserver) {
  88533. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88534. }
  88535. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88536. },
  88537. enumerable: true,
  88538. configurable: true
  88539. });
  88540. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88541. /**
  88542. * The loader state or null if not active.
  88543. */
  88544. get: function () {
  88545. return this._loader ? this._loader.state : null;
  88546. },
  88547. enumerable: true,
  88548. configurable: true
  88549. });
  88550. /**
  88551. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88552. */
  88553. GLTFFileLoader.prototype.dispose = function () {
  88554. if (this._loader) {
  88555. this._loader.dispose();
  88556. this._loader = null;
  88557. }
  88558. this.onMeshLoadedObservable.clear();
  88559. this.onTextureLoadedObservable.clear();
  88560. this.onMaterialLoadedObservable.clear();
  88561. this.onDisposeObservable.notifyObservers(this);
  88562. this.onDisposeObservable.clear();
  88563. };
  88564. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88565. var _this = this;
  88566. return Promise.resolve().then(function () {
  88567. var loaderData = _this._parse(data);
  88568. _this._loader = _this._getLoader(loaderData);
  88569. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88570. });
  88571. };
  88572. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88573. var _this = this;
  88574. return Promise.resolve().then(function () {
  88575. var loaderData = _this._parse(data);
  88576. _this._loader = _this._getLoader(loaderData);
  88577. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88578. });
  88579. };
  88580. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88581. var _this = this;
  88582. return Promise.resolve().then(function () {
  88583. var loaderData = _this._parse(data);
  88584. _this._loader = _this._getLoader(loaderData);
  88585. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88586. var container = new BABYLON.AssetContainer(scene);
  88587. Array.prototype.push.apply(container.meshes, result.meshes);
  88588. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88589. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88590. container.removeAllFromScene();
  88591. return container;
  88592. });
  88593. });
  88594. };
  88595. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88596. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88597. };
  88598. GLTFFileLoader.prototype.createPlugin = function () {
  88599. return new GLTFFileLoader();
  88600. };
  88601. GLTFFileLoader.prototype._parse = function (data) {
  88602. var parsedData;
  88603. if (data instanceof ArrayBuffer) {
  88604. parsedData = GLTFFileLoader._parseBinary(data);
  88605. }
  88606. else {
  88607. parsedData = {
  88608. json: JSON.parse(data),
  88609. bin: null
  88610. };
  88611. }
  88612. this.onParsedObservable.notifyObservers(parsedData);
  88613. this.onParsedObservable.clear();
  88614. return parsedData;
  88615. };
  88616. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88617. var _this = this;
  88618. var loaderVersion = { major: 2, minor: 0 };
  88619. var asset = loaderData.json.asset || {};
  88620. var version = GLTFFileLoader._parseVersion(asset.version);
  88621. if (!version) {
  88622. throw new Error("Invalid version: " + asset.version);
  88623. }
  88624. if (asset.minVersion !== undefined) {
  88625. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88626. if (!minVersion) {
  88627. throw new Error("Invalid minimum version: " + asset.minVersion);
  88628. }
  88629. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88630. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88631. }
  88632. }
  88633. var createLoaders = {
  88634. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88635. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88636. };
  88637. var createLoader = createLoaders[version.major];
  88638. if (!createLoader) {
  88639. throw new Error("Unsupported version: " + asset.version);
  88640. }
  88641. var loader = createLoader();
  88642. loader.coordinateSystemMode = this.coordinateSystemMode;
  88643. loader.animationStartMode = this.animationStartMode;
  88644. loader.compileMaterials = this.compileMaterials;
  88645. loader.useClipPlane = this.useClipPlane;
  88646. loader.compileShadowGenerators = this.compileShadowGenerators;
  88647. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88648. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88649. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88650. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88651. loader.onCompleteObservable.add(function () {
  88652. _this.onMeshLoadedObservable.clear();
  88653. _this.onTextureLoadedObservable.clear();
  88654. _this.onMaterialLoadedObservable.clear();
  88655. _this.onCompleteObservable.notifyObservers(_this);
  88656. _this.onCompleteObservable.clear();
  88657. });
  88658. return loader;
  88659. };
  88660. GLTFFileLoader._parseBinary = function (data) {
  88661. var Binary = {
  88662. Magic: 0x46546C67
  88663. };
  88664. var binaryReader = new BinaryReader(data);
  88665. var magic = binaryReader.readUint32();
  88666. if (magic !== Binary.Magic) {
  88667. throw new Error("Unexpected magic: " + magic);
  88668. }
  88669. var version = binaryReader.readUint32();
  88670. switch (version) {
  88671. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88672. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88673. }
  88674. throw new Error("Unsupported version: " + version);
  88675. };
  88676. GLTFFileLoader._parseV1 = function (binaryReader) {
  88677. var ContentFormat = {
  88678. JSON: 0
  88679. };
  88680. var length = binaryReader.readUint32();
  88681. if (length != binaryReader.getLength()) {
  88682. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88683. }
  88684. var contentLength = binaryReader.readUint32();
  88685. var contentFormat = binaryReader.readUint32();
  88686. var content;
  88687. switch (contentFormat) {
  88688. case ContentFormat.JSON: {
  88689. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88690. break;
  88691. }
  88692. default: {
  88693. throw new Error("Unexpected content format: " + contentFormat);
  88694. }
  88695. }
  88696. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88697. var body = binaryReader.readUint8Array(bytesRemaining);
  88698. return {
  88699. json: content,
  88700. bin: body
  88701. };
  88702. };
  88703. GLTFFileLoader._parseV2 = function (binaryReader) {
  88704. var ChunkFormat = {
  88705. JSON: 0x4E4F534A,
  88706. BIN: 0x004E4942
  88707. };
  88708. var length = binaryReader.readUint32();
  88709. if (length !== binaryReader.getLength()) {
  88710. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88711. }
  88712. // JSON chunk
  88713. var chunkLength = binaryReader.readUint32();
  88714. var chunkFormat = binaryReader.readUint32();
  88715. if (chunkFormat !== ChunkFormat.JSON) {
  88716. throw new Error("First chunk format is not JSON");
  88717. }
  88718. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88719. // Look for BIN chunk
  88720. var bin = null;
  88721. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88722. var chunkLength_1 = binaryReader.readUint32();
  88723. var chunkFormat_1 = binaryReader.readUint32();
  88724. switch (chunkFormat_1) {
  88725. case ChunkFormat.JSON: {
  88726. throw new Error("Unexpected JSON chunk");
  88727. }
  88728. case ChunkFormat.BIN: {
  88729. bin = binaryReader.readUint8Array(chunkLength_1);
  88730. break;
  88731. }
  88732. default: {
  88733. // ignore unrecognized chunkFormat
  88734. binaryReader.skipBytes(chunkLength_1);
  88735. break;
  88736. }
  88737. }
  88738. }
  88739. return {
  88740. json: json,
  88741. bin: bin
  88742. };
  88743. };
  88744. GLTFFileLoader._parseVersion = function (version) {
  88745. if (version === "1.0" || version === "1.0.1") {
  88746. return {
  88747. major: 1,
  88748. minor: 0
  88749. };
  88750. }
  88751. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88752. if (!match) {
  88753. return null;
  88754. }
  88755. return {
  88756. major: parseInt(match[1]),
  88757. minor: parseInt(match[2])
  88758. };
  88759. };
  88760. GLTFFileLoader._compareVersion = function (a, b) {
  88761. if (a.major > b.major)
  88762. return 1;
  88763. if (a.major < b.major)
  88764. return -1;
  88765. if (a.minor > b.minor)
  88766. return 1;
  88767. if (a.minor < b.minor)
  88768. return -1;
  88769. return 0;
  88770. };
  88771. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88772. var result = "";
  88773. var length = buffer.byteLength;
  88774. for (var i = 0; i < length; i++) {
  88775. result += String.fromCharCode(buffer[i]);
  88776. }
  88777. return result;
  88778. };
  88779. // #endregion
  88780. // #region V1 options
  88781. GLTFFileLoader.IncrementalLoading = true;
  88782. GLTFFileLoader.HomogeneousCoordinates = false;
  88783. return GLTFFileLoader;
  88784. }());
  88785. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88786. var BinaryReader = /** @class */ (function () {
  88787. function BinaryReader(arrayBuffer) {
  88788. this._arrayBuffer = arrayBuffer;
  88789. this._dataView = new DataView(arrayBuffer);
  88790. this._byteOffset = 0;
  88791. }
  88792. BinaryReader.prototype.getPosition = function () {
  88793. return this._byteOffset;
  88794. };
  88795. BinaryReader.prototype.getLength = function () {
  88796. return this._arrayBuffer.byteLength;
  88797. };
  88798. BinaryReader.prototype.readUint32 = function () {
  88799. var value = this._dataView.getUint32(this._byteOffset, true);
  88800. this._byteOffset += 4;
  88801. return value;
  88802. };
  88803. BinaryReader.prototype.readUint8Array = function (length) {
  88804. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88805. this._byteOffset += length;
  88806. return value;
  88807. };
  88808. BinaryReader.prototype.skipBytes = function (length) {
  88809. this._byteOffset += length;
  88810. };
  88811. return BinaryReader;
  88812. }());
  88813. if (BABYLON.SceneLoader) {
  88814. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88815. }
  88816. })(BABYLON || (BABYLON = {}));
  88817. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88818. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88819. var BABYLON;
  88820. (function (BABYLON) {
  88821. var GLTF1;
  88822. (function (GLTF1) {
  88823. /**
  88824. * Enums
  88825. */
  88826. var EComponentType;
  88827. (function (EComponentType) {
  88828. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88829. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88830. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88831. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88832. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88833. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88834. var EShaderType;
  88835. (function (EShaderType) {
  88836. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88837. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88838. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88839. var EParameterType;
  88840. (function (EParameterType) {
  88841. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88842. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88843. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88844. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88845. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88846. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88847. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88848. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88849. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88850. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88851. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88852. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88853. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88854. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88855. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88856. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88857. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88858. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88859. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88860. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88861. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88862. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88863. var ETextureWrapMode;
  88864. (function (ETextureWrapMode) {
  88865. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88866. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88867. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88868. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88869. var ETextureFilterType;
  88870. (function (ETextureFilterType) {
  88871. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88872. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88873. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88874. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88875. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88876. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88877. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88878. var ETextureFormat;
  88879. (function (ETextureFormat) {
  88880. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88881. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88882. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88883. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88884. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88885. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88886. var ECullingType;
  88887. (function (ECullingType) {
  88888. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88889. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88890. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88891. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88892. var EBlendingFunction;
  88893. (function (EBlendingFunction) {
  88894. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88895. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88896. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88897. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88898. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88899. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88900. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88901. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88902. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88903. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88904. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88905. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88906. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88907. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88908. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88909. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88910. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88911. })(BABYLON || (BABYLON = {}));
  88912. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88913. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88914. var BABYLON;
  88915. (function (BABYLON) {
  88916. var GLTF1;
  88917. (function (GLTF1) {
  88918. /**
  88919. * Tokenizer. Used for shaders compatibility
  88920. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88921. */
  88922. var ETokenType;
  88923. (function (ETokenType) {
  88924. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88925. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88926. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88927. })(ETokenType || (ETokenType = {}));
  88928. var Tokenizer = /** @class */ (function () {
  88929. function Tokenizer(toParse) {
  88930. this._pos = 0;
  88931. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88932. this._toParse = toParse;
  88933. this._maxPos = toParse.length;
  88934. }
  88935. Tokenizer.prototype.getNextToken = function () {
  88936. if (this.isEnd())
  88937. return ETokenType.END_OF_INPUT;
  88938. this.currentString = this.read();
  88939. this.currentToken = ETokenType.UNKNOWN;
  88940. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88941. this.currentToken = ETokenType.IDENTIFIER;
  88942. this.currentIdentifier = this.currentString;
  88943. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88944. this.currentIdentifier += this.currentString;
  88945. this.forward();
  88946. }
  88947. }
  88948. return this.currentToken;
  88949. };
  88950. Tokenizer.prototype.peek = function () {
  88951. return this._toParse[this._pos];
  88952. };
  88953. Tokenizer.prototype.read = function () {
  88954. return this._toParse[this._pos++];
  88955. };
  88956. Tokenizer.prototype.forward = function () {
  88957. this._pos++;
  88958. };
  88959. Tokenizer.prototype.isEnd = function () {
  88960. return this._pos >= this._maxPos;
  88961. };
  88962. return Tokenizer;
  88963. }());
  88964. /**
  88965. * Values
  88966. */
  88967. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88968. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88969. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88970. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88971. /**
  88972. * Parse
  88973. */
  88974. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88975. for (var buf in parsedBuffers) {
  88976. var parsedBuffer = parsedBuffers[buf];
  88977. gltfRuntime.buffers[buf] = parsedBuffer;
  88978. gltfRuntime.buffersCount++;
  88979. }
  88980. };
  88981. var parseShaders = function (parsedShaders, gltfRuntime) {
  88982. for (var sha in parsedShaders) {
  88983. var parsedShader = parsedShaders[sha];
  88984. gltfRuntime.shaders[sha] = parsedShader;
  88985. gltfRuntime.shaderscount++;
  88986. }
  88987. };
  88988. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88989. for (var object in parsedObjects) {
  88990. var parsedObject = parsedObjects[object];
  88991. gltfRuntime[runtimeProperty][object] = parsedObject;
  88992. }
  88993. };
  88994. /**
  88995. * Utils
  88996. */
  88997. var normalizeUVs = function (buffer) {
  88998. if (!buffer) {
  88999. return;
  89000. }
  89001. for (var i = 0; i < buffer.length / 2; i++) {
  89002. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  89003. }
  89004. };
  89005. var getAttribute = function (attributeParameter) {
  89006. if (attributeParameter.semantic === "NORMAL") {
  89007. return "normal";
  89008. }
  89009. else if (attributeParameter.semantic === "POSITION") {
  89010. return "position";
  89011. }
  89012. else if (attributeParameter.semantic === "JOINT") {
  89013. return "matricesIndices";
  89014. }
  89015. else if (attributeParameter.semantic === "WEIGHT") {
  89016. return "matricesWeights";
  89017. }
  89018. else if (attributeParameter.semantic === "COLOR") {
  89019. return "color";
  89020. }
  89021. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  89022. var channel = Number(attributeParameter.semantic.split("_")[1]);
  89023. return "uv" + (channel === 0 ? "" : channel + 1);
  89024. }
  89025. return null;
  89026. };
  89027. /**
  89028. * Loads and creates animations
  89029. */
  89030. var loadAnimations = function (gltfRuntime) {
  89031. for (var anim in gltfRuntime.animations) {
  89032. var animation = gltfRuntime.animations[anim];
  89033. if (!animation.channels || !animation.samplers) {
  89034. continue;
  89035. }
  89036. var lastAnimation = null;
  89037. for (var i = 0; i < animation.channels.length; i++) {
  89038. // Get parameters and load buffers
  89039. var channel = animation.channels[i];
  89040. var sampler = animation.samplers[channel.sampler];
  89041. if (!sampler) {
  89042. continue;
  89043. }
  89044. var inputData = null;
  89045. var outputData = null;
  89046. if (animation.parameters) {
  89047. inputData = animation.parameters[sampler.input];
  89048. outputData = animation.parameters[sampler.output];
  89049. }
  89050. else {
  89051. inputData = sampler.input;
  89052. outputData = sampler.output;
  89053. }
  89054. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  89055. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  89056. var targetID = channel.target.id;
  89057. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  89058. if (targetNode === null) {
  89059. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  89060. }
  89061. if (targetNode === null) {
  89062. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  89063. continue;
  89064. }
  89065. var isBone = targetNode instanceof BABYLON.Bone;
  89066. // Get target path (position, rotation or scaling)
  89067. var targetPath = channel.target.path;
  89068. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  89069. if (targetPathIndex !== -1) {
  89070. targetPath = babylonAnimationPaths[targetPathIndex];
  89071. }
  89072. // Determine animation type
  89073. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  89074. if (!isBone) {
  89075. if (targetPath === "rotationQuaternion") {
  89076. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89077. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  89078. }
  89079. else {
  89080. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89081. }
  89082. }
  89083. // Create animation and key frames
  89084. var babylonAnimation = null;
  89085. var keys = [];
  89086. var arrayOffset = 0;
  89087. var modifyKey = false;
  89088. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  89089. babylonAnimation = lastAnimation;
  89090. modifyKey = true;
  89091. }
  89092. if (!modifyKey) {
  89093. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89094. }
  89095. // For each frame
  89096. for (var j = 0; j < bufferInput.length; j++) {
  89097. var value = null;
  89098. if (targetPath === "rotationQuaternion") {
  89099. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  89100. arrayOffset += 4;
  89101. }
  89102. else {
  89103. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  89104. arrayOffset += 3;
  89105. }
  89106. if (isBone) {
  89107. var bone = targetNode;
  89108. var translation = BABYLON.Vector3.Zero();
  89109. var rotationQuaternion = new BABYLON.Quaternion();
  89110. var scaling = BABYLON.Vector3.Zero();
  89111. // Warning on decompose
  89112. var mat = bone.getBaseMatrix();
  89113. if (modifyKey && lastAnimation) {
  89114. mat = lastAnimation.getKeys()[j].value;
  89115. }
  89116. mat.decompose(scaling, rotationQuaternion, translation);
  89117. if (targetPath === "position") {
  89118. translation = value;
  89119. }
  89120. else if (targetPath === "rotationQuaternion") {
  89121. rotationQuaternion = value;
  89122. }
  89123. else {
  89124. scaling = value;
  89125. }
  89126. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  89127. }
  89128. if (!modifyKey) {
  89129. keys.push({
  89130. frame: bufferInput[j],
  89131. value: value
  89132. });
  89133. }
  89134. else if (lastAnimation) {
  89135. lastAnimation.getKeys()[j].value = value;
  89136. }
  89137. }
  89138. // Finish
  89139. if (!modifyKey && babylonAnimation) {
  89140. babylonAnimation.setKeys(keys);
  89141. targetNode.animations.push(babylonAnimation);
  89142. }
  89143. lastAnimation = babylonAnimation;
  89144. gltfRuntime.scene.stopAnimation(targetNode);
  89145. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  89146. }
  89147. }
  89148. };
  89149. /**
  89150. * Returns the bones transformation matrix
  89151. */
  89152. var configureBoneTransformation = function (node) {
  89153. var mat = null;
  89154. if (node.translation || node.rotation || node.scale) {
  89155. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  89156. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  89157. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  89158. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  89159. }
  89160. else {
  89161. mat = BABYLON.Matrix.FromArray(node.matrix);
  89162. }
  89163. return mat;
  89164. };
  89165. /**
  89166. * Returns the parent bone
  89167. */
  89168. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  89169. // Try to find
  89170. for (var i = 0; i < newSkeleton.bones.length; i++) {
  89171. if (newSkeleton.bones[i].name === jointName) {
  89172. return newSkeleton.bones[i];
  89173. }
  89174. }
  89175. // Not found, search in gltf nodes
  89176. var nodes = gltfRuntime.nodes;
  89177. for (var nde in nodes) {
  89178. var node = nodes[nde];
  89179. if (!node.jointName) {
  89180. continue;
  89181. }
  89182. var children = node.children;
  89183. for (var i = 0; i < children.length; i++) {
  89184. var child = gltfRuntime.nodes[children[i]];
  89185. if (!child.jointName) {
  89186. continue;
  89187. }
  89188. if (child.jointName === jointName) {
  89189. var mat = configureBoneTransformation(node);
  89190. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  89191. bone.id = nde;
  89192. return bone;
  89193. }
  89194. }
  89195. }
  89196. return null;
  89197. };
  89198. /**
  89199. * Returns the appropriate root node
  89200. */
  89201. var getNodeToRoot = function (nodesToRoot, id) {
  89202. for (var i = 0; i < nodesToRoot.length; i++) {
  89203. var nodeToRoot = nodesToRoot[i];
  89204. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  89205. var child = nodeToRoot.node.children[j];
  89206. if (child === id) {
  89207. return nodeToRoot.bone;
  89208. }
  89209. }
  89210. }
  89211. return null;
  89212. };
  89213. /**
  89214. * Returns the node with the joint name
  89215. */
  89216. var getJointNode = function (gltfRuntime, jointName) {
  89217. var nodes = gltfRuntime.nodes;
  89218. var node = nodes[jointName];
  89219. if (node) {
  89220. return {
  89221. node: node,
  89222. id: jointName
  89223. };
  89224. }
  89225. for (var nde in nodes) {
  89226. node = nodes[nde];
  89227. if (node.jointName === jointName) {
  89228. return {
  89229. node: node,
  89230. id: nde
  89231. };
  89232. }
  89233. }
  89234. return null;
  89235. };
  89236. /**
  89237. * Checks if a nodes is in joints
  89238. */
  89239. var nodeIsInJoints = function (skins, id) {
  89240. for (var i = 0; i < skins.jointNames.length; i++) {
  89241. if (skins.jointNames[i] === id) {
  89242. return true;
  89243. }
  89244. }
  89245. return false;
  89246. };
  89247. /**
  89248. * Fills the nodes to root for bones and builds hierarchy
  89249. */
  89250. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  89251. // Creates nodes for root
  89252. for (var nde in gltfRuntime.nodes) {
  89253. var node = gltfRuntime.nodes[nde];
  89254. var id = nde;
  89255. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  89256. continue;
  89257. }
  89258. // Create node to root bone
  89259. var mat = configureBoneTransformation(node);
  89260. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  89261. bone.id = id;
  89262. nodesToRoot.push({ bone: bone, node: node, id: id });
  89263. }
  89264. // Parenting
  89265. for (var i = 0; i < nodesToRoot.length; i++) {
  89266. var nodeToRoot = nodesToRoot[i];
  89267. var children = nodeToRoot.node.children;
  89268. for (var j = 0; j < children.length; j++) {
  89269. var child = null;
  89270. for (var k = 0; k < nodesToRoot.length; k++) {
  89271. if (nodesToRoot[k].id === children[j]) {
  89272. child = nodesToRoot[k];
  89273. break;
  89274. }
  89275. }
  89276. if (child) {
  89277. child.bone._parent = nodeToRoot.bone;
  89278. nodeToRoot.bone.children.push(child.bone);
  89279. }
  89280. }
  89281. }
  89282. };
  89283. /**
  89284. * Imports a skeleton
  89285. */
  89286. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  89287. if (!newSkeleton) {
  89288. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  89289. }
  89290. if (!skins.babylonSkeleton) {
  89291. return newSkeleton;
  89292. }
  89293. // Find the root bones
  89294. var nodesToRoot = [];
  89295. var nodesToRootToAdd = [];
  89296. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  89297. newSkeleton.bones = [];
  89298. // Joints
  89299. for (var i = 0; i < skins.jointNames.length; i++) {
  89300. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89301. if (!jointNode) {
  89302. continue;
  89303. }
  89304. var node = jointNode.node;
  89305. if (!node) {
  89306. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  89307. continue;
  89308. }
  89309. var id = jointNode.id;
  89310. // Optimize, if the bone already exists...
  89311. var existingBone = gltfRuntime.scene.getBoneByID(id);
  89312. if (existingBone) {
  89313. newSkeleton.bones.push(existingBone);
  89314. continue;
  89315. }
  89316. // Search for parent bone
  89317. var foundBone = false;
  89318. var parentBone = null;
  89319. for (var j = 0; j < i; j++) {
  89320. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  89321. if (!jointNode_1) {
  89322. continue;
  89323. }
  89324. var joint = jointNode_1.node;
  89325. if (!joint) {
  89326. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  89327. continue;
  89328. }
  89329. var children = joint.children;
  89330. if (!children) {
  89331. continue;
  89332. }
  89333. foundBone = false;
  89334. for (var k = 0; k < children.length; k++) {
  89335. if (children[k] === id) {
  89336. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  89337. foundBone = true;
  89338. break;
  89339. }
  89340. }
  89341. if (foundBone) {
  89342. break;
  89343. }
  89344. }
  89345. // Create bone
  89346. var mat = configureBoneTransformation(node);
  89347. if (!parentBone && nodesToRoot.length > 0) {
  89348. parentBone = getNodeToRoot(nodesToRoot, id);
  89349. if (parentBone) {
  89350. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  89351. nodesToRootToAdd.push(parentBone);
  89352. }
  89353. }
  89354. }
  89355. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  89356. bone.id = id;
  89357. }
  89358. // Polish
  89359. var bones = newSkeleton.bones;
  89360. newSkeleton.bones = [];
  89361. for (var i = 0; i < skins.jointNames.length; i++) {
  89362. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89363. if (!jointNode) {
  89364. continue;
  89365. }
  89366. for (var j = 0; j < bones.length; j++) {
  89367. if (bones[j].id === jointNode.id) {
  89368. newSkeleton.bones.push(bones[j]);
  89369. break;
  89370. }
  89371. }
  89372. }
  89373. newSkeleton.prepare();
  89374. // Finish
  89375. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89376. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89377. }
  89378. return newSkeleton;
  89379. };
  89380. /**
  89381. * Imports a mesh and its geometries
  89382. */
  89383. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89384. if (!newMesh) {
  89385. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89386. newMesh.id = id;
  89387. }
  89388. if (!node.babylonNode) {
  89389. return newMesh;
  89390. }
  89391. var subMaterials = [];
  89392. var vertexData = null;
  89393. var verticesStarts = new Array();
  89394. var verticesCounts = new Array();
  89395. var indexStarts = new Array();
  89396. var indexCounts = new Array();
  89397. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89398. var meshID = meshes[meshIndex];
  89399. var mesh = gltfRuntime.meshes[meshID];
  89400. if (!mesh) {
  89401. continue;
  89402. }
  89403. // Positions, normals and UVs
  89404. for (var i = 0; i < mesh.primitives.length; i++) {
  89405. // Temporary vertex data
  89406. var tempVertexData = new BABYLON.VertexData();
  89407. var primitive = mesh.primitives[i];
  89408. if (primitive.mode !== 4) {
  89409. // continue;
  89410. }
  89411. var attributes = primitive.attributes;
  89412. var accessor = null;
  89413. var buffer = null;
  89414. // Set positions, normal and uvs
  89415. for (var semantic in attributes) {
  89416. // Link accessor and buffer view
  89417. accessor = gltfRuntime.accessors[attributes[semantic]];
  89418. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89419. if (semantic === "NORMAL") {
  89420. tempVertexData.normals = new Float32Array(buffer.length);
  89421. tempVertexData.normals.set(buffer);
  89422. }
  89423. else if (semantic === "POSITION") {
  89424. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89425. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89426. for (var j = 0; j < buffer.length; j += 4) {
  89427. tempVertexData.positions[j] = buffer[j];
  89428. tempVertexData.positions[j + 1] = buffer[j + 1];
  89429. tempVertexData.positions[j + 2] = buffer[j + 2];
  89430. }
  89431. }
  89432. else {
  89433. tempVertexData.positions = new Float32Array(buffer.length);
  89434. tempVertexData.positions.set(buffer);
  89435. }
  89436. verticesCounts.push(tempVertexData.positions.length);
  89437. }
  89438. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89439. var channel = Number(semantic.split("_")[1]);
  89440. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89441. var uvs = new Float32Array(buffer.length);
  89442. uvs.set(buffer);
  89443. normalizeUVs(uvs);
  89444. tempVertexData.set(uvs, uvKind);
  89445. }
  89446. else if (semantic === "JOINT") {
  89447. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89448. tempVertexData.matricesIndices.set(buffer);
  89449. }
  89450. else if (semantic === "WEIGHT") {
  89451. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89452. tempVertexData.matricesWeights.set(buffer);
  89453. }
  89454. else if (semantic === "COLOR") {
  89455. tempVertexData.colors = new Float32Array(buffer.length);
  89456. tempVertexData.colors.set(buffer);
  89457. }
  89458. }
  89459. // Indices
  89460. accessor = gltfRuntime.accessors[primitive.indices];
  89461. if (accessor) {
  89462. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89463. tempVertexData.indices = new Int32Array(buffer.length);
  89464. tempVertexData.indices.set(buffer);
  89465. indexCounts.push(tempVertexData.indices.length);
  89466. }
  89467. else {
  89468. // Set indices on the fly
  89469. var indices = [];
  89470. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89471. indices.push(j);
  89472. }
  89473. tempVertexData.indices = new Int32Array(indices);
  89474. indexCounts.push(tempVertexData.indices.length);
  89475. }
  89476. if (!vertexData) {
  89477. vertexData = tempVertexData;
  89478. }
  89479. else {
  89480. vertexData.merge(tempVertexData);
  89481. }
  89482. // Sub material
  89483. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89484. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89485. // Update vertices start and index start
  89486. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89487. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89488. }
  89489. }
  89490. var material;
  89491. if (subMaterials.length > 1) {
  89492. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89493. material.subMaterials = subMaterials;
  89494. }
  89495. else {
  89496. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89497. }
  89498. if (subMaterials.length === 1) {
  89499. material = subMaterials[0];
  89500. }
  89501. if (!newMesh.material) {
  89502. newMesh.material = material;
  89503. }
  89504. // Apply geometry
  89505. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89506. newMesh.computeWorldMatrix(true);
  89507. // Apply submeshes
  89508. newMesh.subMeshes = [];
  89509. var index = 0;
  89510. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89511. var meshID = meshes[meshIndex];
  89512. var mesh = gltfRuntime.meshes[meshID];
  89513. if (!mesh) {
  89514. continue;
  89515. }
  89516. for (var i = 0; i < mesh.primitives.length; i++) {
  89517. if (mesh.primitives[i].mode !== 4) {
  89518. //continue;
  89519. }
  89520. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89521. index++;
  89522. }
  89523. }
  89524. // Finish
  89525. return newMesh;
  89526. };
  89527. /**
  89528. * Configure node transformation from position, rotation and scaling
  89529. */
  89530. var configureNode = function (newNode, position, rotation, scaling) {
  89531. if (newNode.position) {
  89532. newNode.position = position;
  89533. }
  89534. if (newNode.rotationQuaternion || newNode.rotation) {
  89535. newNode.rotationQuaternion = rotation;
  89536. }
  89537. if (newNode.scaling) {
  89538. newNode.scaling = scaling;
  89539. }
  89540. };
  89541. /**
  89542. * Configures node from transformation matrix
  89543. */
  89544. var configureNodeFromMatrix = function (newNode, node, parent) {
  89545. if (node.matrix) {
  89546. var position = new BABYLON.Vector3(0, 0, 0);
  89547. var rotation = new BABYLON.Quaternion();
  89548. var scaling = new BABYLON.Vector3(0, 0, 0);
  89549. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89550. mat.decompose(scaling, rotation, position);
  89551. configureNode(newNode, position, rotation, scaling);
  89552. }
  89553. else if (node.translation && node.rotation && node.scale) {
  89554. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89555. }
  89556. newNode.computeWorldMatrix(true);
  89557. };
  89558. /**
  89559. * Imports a node
  89560. */
  89561. var importNode = function (gltfRuntime, node, id, parent) {
  89562. var lastNode = null;
  89563. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89564. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89565. return null;
  89566. }
  89567. }
  89568. // Meshes
  89569. if (node.skin) {
  89570. if (node.meshes) {
  89571. var skin = gltfRuntime.skins[node.skin];
  89572. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89573. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89574. if (newMesh.skeleton === null) {
  89575. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89576. if (!skin.babylonSkeleton) {
  89577. skin.babylonSkeleton = newMesh.skeleton;
  89578. }
  89579. }
  89580. lastNode = newMesh;
  89581. }
  89582. }
  89583. else if (node.meshes) {
  89584. /**
  89585. * Improve meshes property
  89586. */
  89587. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89588. lastNode = newMesh;
  89589. }
  89590. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89591. var light = gltfRuntime.lights[node.light];
  89592. if (light) {
  89593. if (light.type === "ambient") {
  89594. var ambienLight = light[light.type];
  89595. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89596. hemiLight.name = node.name || "";
  89597. if (ambienLight.color) {
  89598. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89599. }
  89600. lastNode = hemiLight;
  89601. }
  89602. else if (light.type === "directional") {
  89603. var directionalLight = light[light.type];
  89604. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89605. dirLight.name = node.name || "";
  89606. if (directionalLight.color) {
  89607. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89608. }
  89609. lastNode = dirLight;
  89610. }
  89611. else if (light.type === "point") {
  89612. var pointLight = light[light.type];
  89613. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89614. ptLight.name = node.name || "";
  89615. if (pointLight.color) {
  89616. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89617. }
  89618. lastNode = ptLight;
  89619. }
  89620. else if (light.type === "spot") {
  89621. var spotLight = light[light.type];
  89622. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89623. spLight.name = node.name || "";
  89624. if (spotLight.color) {
  89625. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89626. }
  89627. if (spotLight.fallOfAngle) {
  89628. spLight.angle = spotLight.fallOfAngle;
  89629. }
  89630. if (spotLight.fallOffExponent) {
  89631. spLight.exponent = spotLight.fallOffExponent;
  89632. }
  89633. lastNode = spLight;
  89634. }
  89635. }
  89636. }
  89637. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89638. var camera = gltfRuntime.cameras[node.camera];
  89639. if (camera) {
  89640. if (camera.type === "orthographic") {
  89641. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89642. orthoCamera.name = node.name || "";
  89643. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89644. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89645. lastNode = orthoCamera;
  89646. }
  89647. else if (camera.type === "perspective") {
  89648. var perspectiveCamera = camera[camera.type];
  89649. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89650. persCamera.name = node.name || "";
  89651. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89652. if (!perspectiveCamera.aspectRatio) {
  89653. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89654. }
  89655. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89656. persCamera.maxZ = perspectiveCamera.zfar;
  89657. persCamera.minZ = perspectiveCamera.znear;
  89658. }
  89659. lastNode = persCamera;
  89660. }
  89661. }
  89662. }
  89663. // Empty node
  89664. if (!node.jointName) {
  89665. if (node.babylonNode) {
  89666. return node.babylonNode;
  89667. }
  89668. else if (lastNode === null) {
  89669. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89670. node.babylonNode = dummy;
  89671. lastNode = dummy;
  89672. }
  89673. }
  89674. if (lastNode !== null) {
  89675. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89676. configureNodeFromMatrix(lastNode, node, parent);
  89677. }
  89678. else {
  89679. var translation = node.translation || [0, 0, 0];
  89680. var rotation = node.rotation || [0, 0, 0, 1];
  89681. var scale = node.scale || [1, 1, 1];
  89682. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89683. }
  89684. lastNode.updateCache(true);
  89685. node.babylonNode = lastNode;
  89686. }
  89687. return lastNode;
  89688. };
  89689. /**
  89690. * Traverses nodes and creates them
  89691. */
  89692. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89693. if (meshIncluded === void 0) { meshIncluded = false; }
  89694. var node = gltfRuntime.nodes[id];
  89695. var newNode = null;
  89696. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89697. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89698. meshIncluded = true;
  89699. }
  89700. else {
  89701. meshIncluded = false;
  89702. }
  89703. }
  89704. else {
  89705. meshIncluded = true;
  89706. }
  89707. if (!node.jointName && meshIncluded) {
  89708. newNode = importNode(gltfRuntime, node, id, parent);
  89709. if (newNode !== null) {
  89710. newNode.id = id;
  89711. newNode.parent = parent;
  89712. }
  89713. }
  89714. if (node.children) {
  89715. for (var i = 0; i < node.children.length; i++) {
  89716. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89717. }
  89718. }
  89719. };
  89720. /**
  89721. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89722. */
  89723. var postLoad = function (gltfRuntime) {
  89724. // Nodes
  89725. var currentScene = gltfRuntime.currentScene;
  89726. if (currentScene) {
  89727. for (var i = 0; i < currentScene.nodes.length; i++) {
  89728. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89729. }
  89730. }
  89731. else {
  89732. for (var thing in gltfRuntime.scenes) {
  89733. currentScene = gltfRuntime.scenes[thing];
  89734. for (var i = 0; i < currentScene.nodes.length; i++) {
  89735. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89736. }
  89737. }
  89738. }
  89739. // Set animations
  89740. loadAnimations(gltfRuntime);
  89741. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89742. var skeleton = gltfRuntime.scene.skeletons[i];
  89743. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89744. }
  89745. };
  89746. /**
  89747. * onBind shaderrs callback to set uniforms and matrices
  89748. */
  89749. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89750. var materialValues = material.values || technique.parameters;
  89751. for (var unif in unTreatedUniforms) {
  89752. var uniform = unTreatedUniforms[unif];
  89753. var type = uniform.type;
  89754. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89755. if (uniform.semantic && !uniform.source && !uniform.node) {
  89756. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89757. }
  89758. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89759. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89760. if (source === null) {
  89761. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89762. }
  89763. if (source === null) {
  89764. continue;
  89765. }
  89766. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89767. }
  89768. }
  89769. else {
  89770. var value = materialValues[technique.uniforms[unif]];
  89771. if (!value) {
  89772. continue;
  89773. }
  89774. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89775. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89776. if (texture === null || texture === undefined) {
  89777. continue;
  89778. }
  89779. shaderMaterial.getEffect().setTexture(unif, texture);
  89780. }
  89781. else {
  89782. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89783. }
  89784. }
  89785. }
  89786. onSuccess(shaderMaterial);
  89787. };
  89788. /**
  89789. * Prepare uniforms to send the only one time
  89790. * Loads the appropriate textures
  89791. */
  89792. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89793. var materialValues = material.values || technique.parameters;
  89794. var techniqueUniforms = technique.uniforms;
  89795. /**
  89796. * Prepare values here (not matrices)
  89797. */
  89798. for (var unif in unTreatedUniforms) {
  89799. var uniform = unTreatedUniforms[unif];
  89800. var type = uniform.type;
  89801. var value = materialValues[techniqueUniforms[unif]];
  89802. if (value === undefined) {
  89803. // In case the value is the same for all materials
  89804. value = uniform.value;
  89805. }
  89806. if (!value) {
  89807. continue;
  89808. }
  89809. var onLoadTexture = function (uniformName) {
  89810. return function (texture) {
  89811. if (uniform.value && uniformName) {
  89812. // Static uniform
  89813. shaderMaterial.setTexture(uniformName, texture);
  89814. delete unTreatedUniforms[uniformName];
  89815. }
  89816. };
  89817. };
  89818. // Texture (sampler2D)
  89819. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89820. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89821. }
  89822. else {
  89823. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89824. // Static uniform
  89825. delete unTreatedUniforms[unif];
  89826. }
  89827. }
  89828. }
  89829. };
  89830. /**
  89831. * Shader compilation failed
  89832. */
  89833. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89834. return function (effect, error) {
  89835. shaderMaterial.dispose(true);
  89836. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89837. };
  89838. };
  89839. /**
  89840. * Shader compilation success
  89841. */
  89842. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89843. return function (_) {
  89844. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89845. shaderMaterial.onBind = function (mesh) {
  89846. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89847. };
  89848. };
  89849. };
  89850. /**
  89851. * Returns the appropriate uniform if already handled by babylon
  89852. */
  89853. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89854. for (var unif in technique.uniforms) {
  89855. var uniform = technique.uniforms[unif];
  89856. var uniformParameter = technique.parameters[uniform];
  89857. if (tokenizer.currentIdentifier === unif) {
  89858. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89859. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89860. if (transformIndex !== -1) {
  89861. delete unTreatedUniforms[unif];
  89862. return babylonTransforms[transformIndex];
  89863. }
  89864. }
  89865. }
  89866. }
  89867. return tokenizer.currentIdentifier;
  89868. };
  89869. /**
  89870. * All shaders loaded. Create materials one by one
  89871. */
  89872. var importMaterials = function (gltfRuntime) {
  89873. // Create materials
  89874. for (var mat in gltfRuntime.materials) {
  89875. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89876. }
  89877. };
  89878. /**
  89879. * Implementation of the base glTF spec
  89880. */
  89881. var GLTFLoaderBase = /** @class */ (function () {
  89882. function GLTFLoaderBase() {
  89883. }
  89884. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89885. var gltfRuntime = {
  89886. extensions: {},
  89887. accessors: {},
  89888. buffers: {},
  89889. bufferViews: {},
  89890. meshes: {},
  89891. lights: {},
  89892. cameras: {},
  89893. nodes: {},
  89894. images: {},
  89895. textures: {},
  89896. shaders: {},
  89897. programs: {},
  89898. samplers: {},
  89899. techniques: {},
  89900. materials: {},
  89901. animations: {},
  89902. skins: {},
  89903. extensionsUsed: [],
  89904. scenes: {},
  89905. buffersCount: 0,
  89906. shaderscount: 0,
  89907. scene: scene,
  89908. rootUrl: rootUrl,
  89909. loadedBufferCount: 0,
  89910. loadedBufferViews: {},
  89911. loadedShaderCount: 0,
  89912. importOnlyMeshes: false,
  89913. dummyNodes: []
  89914. };
  89915. // Parse
  89916. if (parsedData.extensions) {
  89917. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89918. }
  89919. if (parsedData.extensionsUsed) {
  89920. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89921. }
  89922. if (parsedData.buffers) {
  89923. parseBuffers(parsedData.buffers, gltfRuntime);
  89924. }
  89925. if (parsedData.bufferViews) {
  89926. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89927. }
  89928. if (parsedData.accessors) {
  89929. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89930. }
  89931. if (parsedData.meshes) {
  89932. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89933. }
  89934. if (parsedData.lights) {
  89935. parseObject(parsedData.lights, "lights", gltfRuntime);
  89936. }
  89937. if (parsedData.cameras) {
  89938. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89939. }
  89940. if (parsedData.nodes) {
  89941. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89942. }
  89943. if (parsedData.images) {
  89944. parseObject(parsedData.images, "images", gltfRuntime);
  89945. }
  89946. if (parsedData.textures) {
  89947. parseObject(parsedData.textures, "textures", gltfRuntime);
  89948. }
  89949. if (parsedData.shaders) {
  89950. parseShaders(parsedData.shaders, gltfRuntime);
  89951. }
  89952. if (parsedData.programs) {
  89953. parseObject(parsedData.programs, "programs", gltfRuntime);
  89954. }
  89955. if (parsedData.samplers) {
  89956. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89957. }
  89958. if (parsedData.techniques) {
  89959. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89960. }
  89961. if (parsedData.materials) {
  89962. parseObject(parsedData.materials, "materials", gltfRuntime);
  89963. }
  89964. if (parsedData.animations) {
  89965. parseObject(parsedData.animations, "animations", gltfRuntime);
  89966. }
  89967. if (parsedData.skins) {
  89968. parseObject(parsedData.skins, "skins", gltfRuntime);
  89969. }
  89970. if (parsedData.scenes) {
  89971. gltfRuntime.scenes = parsedData.scenes;
  89972. }
  89973. if (parsedData.scene && parsedData.scenes) {
  89974. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89975. }
  89976. return gltfRuntime;
  89977. };
  89978. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89979. var buffer = gltfRuntime.buffers[id];
  89980. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89981. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89982. }
  89983. else {
  89984. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89985. if (request) {
  89986. onError(request.status + " " + request.statusText);
  89987. }
  89988. });
  89989. }
  89990. };
  89991. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89992. var texture = gltfRuntime.textures[id];
  89993. if (!texture || !texture.source) {
  89994. onError("");
  89995. return;
  89996. }
  89997. if (texture.babylonTexture) {
  89998. onSuccess(null);
  89999. return;
  90000. }
  90001. var source = gltfRuntime.images[texture.source];
  90002. if (BABYLON.Tools.IsBase64(source.uri)) {
  90003. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  90004. }
  90005. else {
  90006. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  90007. if (request) {
  90008. onError(request.status + " " + request.statusText);
  90009. }
  90010. });
  90011. }
  90012. };
  90013. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90014. var texture = gltfRuntime.textures[id];
  90015. if (texture.babylonTexture) {
  90016. onSuccess(texture.babylonTexture);
  90017. return;
  90018. }
  90019. var sampler = gltfRuntime.samplers[texture.sampler];
  90020. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  90021. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  90022. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  90023. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  90024. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90025. var blob = new Blob([buffer]);
  90026. var blobURL = URL.createObjectURL(blob);
  90027. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  90028. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  90029. if (sampler.wrapS !== undefined) {
  90030. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  90031. }
  90032. if (sampler.wrapT !== undefined) {
  90033. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  90034. }
  90035. newTexture.name = id;
  90036. texture.babylonTexture = newTexture;
  90037. onSuccess(newTexture);
  90038. };
  90039. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90040. var shader = gltfRuntime.shaders[id];
  90041. if (BABYLON.Tools.IsBase64(shader.uri)) {
  90042. var shaderString = atob(shader.uri.split(",")[1]);
  90043. onSuccess(shaderString);
  90044. }
  90045. else {
  90046. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  90047. if (request) {
  90048. onError(request.status + " " + request.statusText);
  90049. }
  90050. });
  90051. }
  90052. };
  90053. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90054. var material = gltfRuntime.materials[id];
  90055. if (!material.technique) {
  90056. if (onError) {
  90057. onError("No technique found.");
  90058. }
  90059. return;
  90060. }
  90061. var technique = gltfRuntime.techniques[material.technique];
  90062. if (!technique) {
  90063. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90064. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  90065. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90066. onSuccess(defaultMaterial);
  90067. return;
  90068. }
  90069. var program = gltfRuntime.programs[technique.program];
  90070. var states = technique.states;
  90071. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  90072. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  90073. var newVertexShader = "";
  90074. var newPixelShader = "";
  90075. var vertexTokenizer = new Tokenizer(vertexShader);
  90076. var pixelTokenizer = new Tokenizer(pixelShader);
  90077. var unTreatedUniforms = {};
  90078. var uniforms = [];
  90079. var attributes = [];
  90080. var samplers = [];
  90081. // Fill uniform, sampler2D and attributes
  90082. for (var unif in technique.uniforms) {
  90083. var uniform = technique.uniforms[unif];
  90084. var uniformParameter = technique.parameters[uniform];
  90085. unTreatedUniforms[unif] = uniformParameter;
  90086. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  90087. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90088. if (transformIndex !== -1) {
  90089. uniforms.push(babylonTransforms[transformIndex]);
  90090. delete unTreatedUniforms[unif];
  90091. }
  90092. else {
  90093. uniforms.push(unif);
  90094. }
  90095. }
  90096. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  90097. samplers.push(unif);
  90098. }
  90099. else {
  90100. uniforms.push(unif);
  90101. }
  90102. }
  90103. for (var attr in technique.attributes) {
  90104. var attribute = technique.attributes[attr];
  90105. var attributeParameter = technique.parameters[attribute];
  90106. if (attributeParameter.semantic) {
  90107. attributes.push(getAttribute(attributeParameter));
  90108. }
  90109. }
  90110. // Configure vertex shader
  90111. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  90112. var tokenType = vertexTokenizer.currentToken;
  90113. if (tokenType !== ETokenType.IDENTIFIER) {
  90114. newVertexShader += vertexTokenizer.currentString;
  90115. continue;
  90116. }
  90117. var foundAttribute = false;
  90118. for (var attr in technique.attributes) {
  90119. var attribute = technique.attributes[attr];
  90120. var attributeParameter = technique.parameters[attribute];
  90121. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  90122. newVertexShader += getAttribute(attributeParameter);
  90123. foundAttribute = true;
  90124. break;
  90125. }
  90126. }
  90127. if (foundAttribute) {
  90128. continue;
  90129. }
  90130. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  90131. }
  90132. // Configure pixel shader
  90133. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  90134. var tokenType = pixelTokenizer.currentToken;
  90135. if (tokenType !== ETokenType.IDENTIFIER) {
  90136. newPixelShader += pixelTokenizer.currentString;
  90137. continue;
  90138. }
  90139. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  90140. }
  90141. // Create shader material
  90142. var shaderPath = {
  90143. vertex: program.vertexShader + id,
  90144. fragment: program.fragmentShader + id
  90145. };
  90146. var options = {
  90147. attributes: attributes,
  90148. uniforms: uniforms,
  90149. samplers: samplers,
  90150. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  90151. };
  90152. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  90153. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  90154. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  90155. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  90156. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  90157. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90158. if (states && states.functions) {
  90159. var functions = states.functions;
  90160. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  90161. shaderMaterial.backFaceCulling = false;
  90162. }
  90163. var blendFunc = functions.blendFuncSeparate;
  90164. if (blendFunc) {
  90165. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90166. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  90167. }
  90168. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90169. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90170. }
  90171. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90172. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  90173. }
  90174. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90175. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  90176. }
  90177. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90178. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  90179. }
  90180. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90181. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  90182. }
  90183. }
  90184. }
  90185. };
  90186. return GLTFLoaderBase;
  90187. }());
  90188. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  90189. /**
  90190. * glTF V1 Loader
  90191. */
  90192. var GLTFLoader = /** @class */ (function () {
  90193. function GLTFLoader() {
  90194. // #region Stubs for IGLTFLoader interface
  90195. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90196. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90197. this.compileMaterials = false;
  90198. this.useClipPlane = false;
  90199. this.compileShadowGenerators = false;
  90200. this.onDisposeObservable = new BABYLON.Observable();
  90201. this.onMeshLoadedObservable = new BABYLON.Observable();
  90202. this.onTextureLoadedObservable = new BABYLON.Observable();
  90203. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90204. this.onCompleteObservable = new BABYLON.Observable();
  90205. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90206. this.state = null;
  90207. }
  90208. GLTFLoader.RegisterExtension = function (extension) {
  90209. if (GLTFLoader.Extensions[extension.name]) {
  90210. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  90211. return;
  90212. }
  90213. GLTFLoader.Extensions[extension.name] = extension;
  90214. };
  90215. GLTFLoader.prototype.dispose = function () { };
  90216. // #endregion
  90217. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  90218. var _this = this;
  90219. scene.useRightHandedSystem = true;
  90220. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90221. gltfRuntime.importOnlyMeshes = true;
  90222. if (meshesNames === "") {
  90223. gltfRuntime.importMeshesNames = [];
  90224. }
  90225. else if (typeof meshesNames === "string") {
  90226. gltfRuntime.importMeshesNames = [meshesNames];
  90227. }
  90228. else if (meshesNames && !(meshesNames instanceof Array)) {
  90229. gltfRuntime.importMeshesNames = [meshesNames];
  90230. }
  90231. else {
  90232. gltfRuntime.importMeshesNames = [];
  90233. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  90234. }
  90235. // Create nodes
  90236. _this._createNodes(gltfRuntime);
  90237. var meshes = new Array();
  90238. var skeletons = new Array();
  90239. // Fill arrays of meshes and skeletons
  90240. for (var nde in gltfRuntime.nodes) {
  90241. var node = gltfRuntime.nodes[nde];
  90242. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  90243. meshes.push(node.babylonNode);
  90244. }
  90245. }
  90246. for (var skl in gltfRuntime.skins) {
  90247. var skin = gltfRuntime.skins[skl];
  90248. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  90249. skeletons.push(skin.babylonSkeleton);
  90250. }
  90251. }
  90252. // Load buffers, shaders, materials, etc.
  90253. _this._loadBuffersAsync(gltfRuntime, function () {
  90254. _this._loadShadersAsync(gltfRuntime, function () {
  90255. importMaterials(gltfRuntime);
  90256. postLoad(gltfRuntime);
  90257. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90258. onSuccess(meshes, [], skeletons);
  90259. }
  90260. });
  90261. }, onProgress);
  90262. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90263. onSuccess(meshes, [], skeletons);
  90264. }
  90265. }, onError);
  90266. return true;
  90267. };
  90268. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90269. var _this = this;
  90270. return new Promise(function (resolve, reject) {
  90271. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  90272. resolve({
  90273. meshes: meshes,
  90274. particleSystems: particleSystems,
  90275. skeletons: skeletons
  90276. });
  90277. }, onProgress, function (message) {
  90278. reject(new Error(message));
  90279. });
  90280. });
  90281. };
  90282. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  90283. var _this = this;
  90284. scene.useRightHandedSystem = true;
  90285. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90286. // Load runtime extensios
  90287. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  90288. // Create nodes
  90289. _this._createNodes(gltfRuntime);
  90290. // Load buffers, shaders, materials, etc.
  90291. _this._loadBuffersAsync(gltfRuntime, function () {
  90292. _this._loadShadersAsync(gltfRuntime, function () {
  90293. importMaterials(gltfRuntime);
  90294. postLoad(gltfRuntime);
  90295. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  90296. onSuccess();
  90297. }
  90298. });
  90299. });
  90300. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  90301. onSuccess();
  90302. }
  90303. }, onError);
  90304. }, onError);
  90305. };
  90306. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90307. var _this = this;
  90308. return new Promise(function (resolve, reject) {
  90309. _this._loadAsync(scene, data, rootUrl, function () {
  90310. resolve();
  90311. }, onProgress, function (message) {
  90312. reject(new Error(message));
  90313. });
  90314. });
  90315. };
  90316. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  90317. var hasShaders = false;
  90318. var processShader = function (sha, shader) {
  90319. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  90320. gltfRuntime.loadedShaderCount++;
  90321. if (shaderString) {
  90322. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  90323. }
  90324. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  90325. onload();
  90326. }
  90327. }, function () {
  90328. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  90329. });
  90330. };
  90331. for (var sha in gltfRuntime.shaders) {
  90332. hasShaders = true;
  90333. var shader = gltfRuntime.shaders[sha];
  90334. if (shader) {
  90335. processShader.bind(this, sha, shader)();
  90336. }
  90337. else {
  90338. BABYLON.Tools.Error("No shader named: " + sha);
  90339. }
  90340. }
  90341. if (!hasShaders) {
  90342. onload();
  90343. }
  90344. };
  90345. ;
  90346. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  90347. var hasBuffers = false;
  90348. var processBuffer = function (buf, buffer) {
  90349. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  90350. gltfRuntime.loadedBufferCount++;
  90351. if (bufferView) {
  90352. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  90353. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  90354. }
  90355. gltfRuntime.loadedBufferViews[buf] = bufferView;
  90356. }
  90357. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  90358. onLoad();
  90359. }
  90360. }, function () {
  90361. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90362. });
  90363. };
  90364. for (var buf in gltfRuntime.buffers) {
  90365. hasBuffers = true;
  90366. var buffer = gltfRuntime.buffers[buf];
  90367. if (buffer) {
  90368. processBuffer.bind(this, buf, buffer)();
  90369. }
  90370. else {
  90371. BABYLON.Tools.Error("No buffer named: " + buf);
  90372. }
  90373. }
  90374. if (!hasBuffers) {
  90375. onLoad();
  90376. }
  90377. };
  90378. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90379. var currentScene = gltfRuntime.currentScene;
  90380. if (currentScene) {
  90381. // Only one scene even if multiple scenes are defined
  90382. for (var i = 0; i < currentScene.nodes.length; i++) {
  90383. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90384. }
  90385. }
  90386. else {
  90387. // Load all scenes
  90388. for (var thing in gltfRuntime.scenes) {
  90389. currentScene = gltfRuntime.scenes[thing];
  90390. for (var i = 0; i < currentScene.nodes.length; i++) {
  90391. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90392. }
  90393. }
  90394. }
  90395. };
  90396. GLTFLoader.Extensions = {};
  90397. return GLTFLoader;
  90398. }());
  90399. GLTF1.GLTFLoader = GLTFLoader;
  90400. ;
  90401. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90402. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90403. })(BABYLON || (BABYLON = {}));
  90404. //# sourceMappingURL=babylon.glTFLoader.js.map
  90405. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90406. var BABYLON;
  90407. (function (BABYLON) {
  90408. var GLTF1;
  90409. (function (GLTF1) {
  90410. /**
  90411. * Utils functions for GLTF
  90412. */
  90413. var GLTFUtils = /** @class */ (function () {
  90414. function GLTFUtils() {
  90415. }
  90416. /**
  90417. * Sets the given "parameter" matrix
  90418. * @param scene: the {BABYLON.Scene} object
  90419. * @param source: the source node where to pick the matrix
  90420. * @param parameter: the GLTF technique parameter
  90421. * @param uniformName: the name of the shader's uniform
  90422. * @param shaderMaterial: the shader material
  90423. */
  90424. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90425. var mat = null;
  90426. if (parameter.semantic === "MODEL") {
  90427. mat = source.getWorldMatrix();
  90428. }
  90429. else if (parameter.semantic === "PROJECTION") {
  90430. mat = scene.getProjectionMatrix();
  90431. }
  90432. else if (parameter.semantic === "VIEW") {
  90433. mat = scene.getViewMatrix();
  90434. }
  90435. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90436. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90437. }
  90438. else if (parameter.semantic === "MODELVIEW") {
  90439. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90440. }
  90441. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90442. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90443. }
  90444. else if (parameter.semantic === "MODELINVERSE") {
  90445. mat = source.getWorldMatrix().invert();
  90446. }
  90447. else if (parameter.semantic === "VIEWINVERSE") {
  90448. mat = scene.getViewMatrix().invert();
  90449. }
  90450. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90451. mat = scene.getProjectionMatrix().invert();
  90452. }
  90453. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90454. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90455. }
  90456. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90457. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90458. }
  90459. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90460. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90461. }
  90462. else {
  90463. debugger;
  90464. }
  90465. if (mat) {
  90466. switch (parameter.type) {
  90467. case GLTF1.EParameterType.FLOAT_MAT2:
  90468. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90469. break;
  90470. case GLTF1.EParameterType.FLOAT_MAT3:
  90471. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90472. break;
  90473. case GLTF1.EParameterType.FLOAT_MAT4:
  90474. shaderMaterial.setMatrix(uniformName, mat);
  90475. break;
  90476. default: break;
  90477. }
  90478. }
  90479. };
  90480. /**
  90481. * Sets the given "parameter" matrix
  90482. * @param shaderMaterial: the shader material
  90483. * @param uniform: the name of the shader's uniform
  90484. * @param value: the value of the uniform
  90485. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90486. */
  90487. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90488. switch (type) {
  90489. case GLTF1.EParameterType.FLOAT:
  90490. shaderMaterial.setFloat(uniform, value);
  90491. return true;
  90492. case GLTF1.EParameterType.FLOAT_VEC2:
  90493. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90494. return true;
  90495. case GLTF1.EParameterType.FLOAT_VEC3:
  90496. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90497. return true;
  90498. case GLTF1.EParameterType.FLOAT_VEC4:
  90499. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90500. return true;
  90501. default: return false;
  90502. }
  90503. };
  90504. /**
  90505. * Returns the wrap mode of the texture
  90506. * @param mode: the mode value
  90507. */
  90508. GLTFUtils.GetWrapMode = function (mode) {
  90509. switch (mode) {
  90510. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90511. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90512. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90513. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90514. }
  90515. };
  90516. /**
  90517. * Returns the byte stride giving an accessor
  90518. * @param accessor: the GLTF accessor objet
  90519. */
  90520. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90521. // Needs this function since "byteStride" isn't requiered in glTF format
  90522. var type = accessor.type;
  90523. switch (type) {
  90524. case "VEC2": return 2;
  90525. case "VEC3": return 3;
  90526. case "VEC4": return 4;
  90527. case "MAT2": return 4;
  90528. case "MAT3": return 9;
  90529. case "MAT4": return 16;
  90530. default: return 1;
  90531. }
  90532. };
  90533. /**
  90534. * Returns the texture filter mode giving a mode value
  90535. * @param mode: the filter mode value
  90536. */
  90537. GLTFUtils.GetTextureFilterMode = function (mode) {
  90538. switch (mode) {
  90539. case GLTF1.ETextureFilterType.LINEAR:
  90540. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90541. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90542. case GLTF1.ETextureFilterType.NEAREST:
  90543. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90544. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90545. }
  90546. };
  90547. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90548. var byteOffset = bufferView.byteOffset + byteOffset;
  90549. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90550. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90551. throw new Error("Buffer access is out of range");
  90552. }
  90553. var buffer = loadedBufferView.buffer;
  90554. byteOffset += loadedBufferView.byteOffset;
  90555. switch (componentType) {
  90556. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90557. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90558. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90559. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90560. default: return new Float32Array(buffer, byteOffset, byteLength);
  90561. }
  90562. };
  90563. /**
  90564. * Returns a buffer from its accessor
  90565. * @param gltfRuntime: the GLTF runtime
  90566. * @param accessor: the GLTF accessor
  90567. */
  90568. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90569. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90570. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90571. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90572. };
  90573. /**
  90574. * Decodes a buffer view into a string
  90575. * @param view: the buffer view
  90576. */
  90577. GLTFUtils.DecodeBufferToText = function (view) {
  90578. var result = "";
  90579. var length = view.byteLength;
  90580. for (var i = 0; i < length; ++i) {
  90581. result += String.fromCharCode(view[i]);
  90582. }
  90583. return result;
  90584. };
  90585. /**
  90586. * Returns the default material of gltf. Related to
  90587. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90588. * @param scene: the Babylon.js scene
  90589. */
  90590. GLTFUtils.GetDefaultMaterial = function (scene) {
  90591. if (!GLTFUtils._DefaultMaterial) {
  90592. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90593. "precision highp float;",
  90594. "",
  90595. "uniform mat4 worldView;",
  90596. "uniform mat4 projection;",
  90597. "",
  90598. "attribute vec3 position;",
  90599. "",
  90600. "void main(void)",
  90601. "{",
  90602. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90603. "}"
  90604. ].join("\n");
  90605. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90606. "precision highp float;",
  90607. "",
  90608. "uniform vec4 u_emission;",
  90609. "",
  90610. "void main(void)",
  90611. "{",
  90612. " gl_FragColor = u_emission;",
  90613. "}"
  90614. ].join("\n");
  90615. var shaderPath = {
  90616. vertex: "GLTFDefaultMaterial",
  90617. fragment: "GLTFDefaultMaterial"
  90618. };
  90619. var options = {
  90620. attributes: ["position"],
  90621. uniforms: ["worldView", "projection", "u_emission"],
  90622. samplers: new Array(),
  90623. needAlphaBlending: false
  90624. };
  90625. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90626. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90627. }
  90628. return GLTFUtils._DefaultMaterial;
  90629. };
  90630. // The GLTF default material
  90631. GLTFUtils._DefaultMaterial = null;
  90632. return GLTFUtils;
  90633. }());
  90634. GLTF1.GLTFUtils = GLTFUtils;
  90635. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90636. })(BABYLON || (BABYLON = {}));
  90637. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90638. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90639. var BABYLON;
  90640. (function (BABYLON) {
  90641. var GLTF1;
  90642. (function (GLTF1) {
  90643. var GLTFLoaderExtension = /** @class */ (function () {
  90644. function GLTFLoaderExtension(name) {
  90645. this._name = name;
  90646. }
  90647. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90648. get: function () {
  90649. return this._name;
  90650. },
  90651. enumerable: true,
  90652. configurable: true
  90653. });
  90654. /**
  90655. * Defines an override for loading the runtime
  90656. * Return true to stop further extensions from loading the runtime
  90657. */
  90658. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90659. return false;
  90660. };
  90661. /**
  90662. * Defines an onverride for creating gltf runtime
  90663. * Return true to stop further extensions from creating the runtime
  90664. */
  90665. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90666. return false;
  90667. };
  90668. /**
  90669. * Defines an override for loading buffers
  90670. * Return true to stop further extensions from loading this buffer
  90671. */
  90672. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90673. return false;
  90674. };
  90675. /**
  90676. * Defines an override for loading texture buffers
  90677. * Return true to stop further extensions from loading this texture data
  90678. */
  90679. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90680. return false;
  90681. };
  90682. /**
  90683. * Defines an override for creating textures
  90684. * Return true to stop further extensions from loading this texture
  90685. */
  90686. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90687. return false;
  90688. };
  90689. /**
  90690. * Defines an override for loading shader strings
  90691. * Return true to stop further extensions from loading this shader data
  90692. */
  90693. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90694. return false;
  90695. };
  90696. /**
  90697. * Defines an override for loading materials
  90698. * Return true to stop further extensions from loading this material
  90699. */
  90700. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90701. return false;
  90702. };
  90703. // ---------
  90704. // Utilities
  90705. // ---------
  90706. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90707. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90708. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90709. }, function () {
  90710. setTimeout(function () {
  90711. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90712. });
  90713. });
  90714. };
  90715. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90716. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90717. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90718. }, function () {
  90719. setTimeout(function () {
  90720. onSuccess();
  90721. });
  90722. });
  90723. };
  90724. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90725. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90726. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90727. }, function () {
  90728. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90729. });
  90730. };
  90731. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90732. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90733. };
  90734. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90735. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90736. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90737. }, function () {
  90738. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90739. });
  90740. };
  90741. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90742. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90743. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90744. }, function () {
  90745. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90746. });
  90747. };
  90748. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90749. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90750. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90751. }, function () {
  90752. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90753. });
  90754. };
  90755. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90756. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90757. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90758. }, function () {
  90759. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90760. });
  90761. };
  90762. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90763. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90764. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90765. if (func(loaderExtension)) {
  90766. return;
  90767. }
  90768. }
  90769. defaultFunc();
  90770. };
  90771. return GLTFLoaderExtension;
  90772. }());
  90773. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90774. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90775. })(BABYLON || (BABYLON = {}));
  90776. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90777. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90778. var BABYLON;
  90779. (function (BABYLON) {
  90780. var GLTF1;
  90781. (function (GLTF1) {
  90782. var BinaryExtensionBufferName = "binary_glTF";
  90783. ;
  90784. ;
  90785. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90786. __extends(GLTFBinaryExtension, _super);
  90787. function GLTFBinaryExtension() {
  90788. return _super.call(this, "KHR_binary_glTF") || this;
  90789. }
  90790. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90791. var extensionsUsed = data.json.extensionsUsed;
  90792. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90793. return false;
  90794. }
  90795. this._bin = data.bin;
  90796. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90797. return true;
  90798. };
  90799. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90800. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90801. return false;
  90802. }
  90803. if (id !== BinaryExtensionBufferName) {
  90804. return false;
  90805. }
  90806. onSuccess(this._bin);
  90807. return true;
  90808. };
  90809. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90810. var texture = gltfRuntime.textures[id];
  90811. var source = gltfRuntime.images[texture.source];
  90812. if (!source.extensions || !(this.name in source.extensions)) {
  90813. return false;
  90814. }
  90815. var sourceExt = source.extensions[this.name];
  90816. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90817. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90818. onSuccess(buffer);
  90819. return true;
  90820. };
  90821. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90822. var shader = gltfRuntime.shaders[id];
  90823. if (!shader.extensions || !(this.name in shader.extensions)) {
  90824. return false;
  90825. }
  90826. var binaryExtensionShader = shader.extensions[this.name];
  90827. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90828. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90829. setTimeout(function () {
  90830. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90831. onSuccess(shaderString);
  90832. });
  90833. return true;
  90834. };
  90835. return GLTFBinaryExtension;
  90836. }(GLTF1.GLTFLoaderExtension));
  90837. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90838. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90839. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90840. })(BABYLON || (BABYLON = {}));
  90841. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90842. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90843. var BABYLON;
  90844. (function (BABYLON) {
  90845. var GLTF1;
  90846. (function (GLTF1) {
  90847. ;
  90848. ;
  90849. ;
  90850. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90851. __extends(GLTFMaterialsCommonExtension, _super);
  90852. function GLTFMaterialsCommonExtension() {
  90853. return _super.call(this, "KHR_materials_common") || this;
  90854. }
  90855. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90856. if (!gltfRuntime.extensions)
  90857. return false;
  90858. var extension = gltfRuntime.extensions[this.name];
  90859. if (!extension)
  90860. return false;
  90861. // Create lights
  90862. var lights = extension.lights;
  90863. if (lights) {
  90864. for (var thing in lights) {
  90865. var light = lights[thing];
  90866. switch (light.type) {
  90867. case "ambient":
  90868. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90869. var ambient = light.ambient;
  90870. if (ambient) {
  90871. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90872. }
  90873. break;
  90874. case "point":
  90875. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90876. var point = light.point;
  90877. if (point) {
  90878. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90879. }
  90880. break;
  90881. case "directional":
  90882. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90883. var directional = light.directional;
  90884. if (directional) {
  90885. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90886. }
  90887. break;
  90888. case "spot":
  90889. var spot = light.spot;
  90890. if (spot) {
  90891. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  90892. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90893. }
  90894. break;
  90895. default:
  90896. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90897. break;
  90898. }
  90899. }
  90900. }
  90901. return false;
  90902. };
  90903. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90904. var material = gltfRuntime.materials[id];
  90905. if (!material || !material.extensions)
  90906. return false;
  90907. var extension = material.extensions[this.name];
  90908. if (!extension)
  90909. return false;
  90910. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90911. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90912. if (extension.technique === "CONSTANT") {
  90913. standardMaterial.disableLighting = true;
  90914. }
  90915. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90916. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90917. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90918. // Ambient
  90919. if (typeof extension.values.ambient === "string") {
  90920. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90921. }
  90922. else {
  90923. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90924. }
  90925. // Diffuse
  90926. if (typeof extension.values.diffuse === "string") {
  90927. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90928. }
  90929. else {
  90930. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90931. }
  90932. // Emission
  90933. if (typeof extension.values.emission === "string") {
  90934. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90935. }
  90936. else {
  90937. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90938. }
  90939. // Specular
  90940. if (typeof extension.values.specular === "string") {
  90941. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90942. }
  90943. else {
  90944. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90945. }
  90946. return true;
  90947. };
  90948. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90949. // Create buffer from texture url
  90950. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90951. // Create texture from buffer
  90952. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90953. }, onError);
  90954. };
  90955. return GLTFMaterialsCommonExtension;
  90956. }(GLTF1.GLTFLoaderExtension));
  90957. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90958. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90959. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90960. })(BABYLON || (BABYLON = {}));
  90961. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90962. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90963. var BABYLON;
  90964. (function (BABYLON) {
  90965. var GLTF2;
  90966. (function (GLTF2) {
  90967. var ArrayItem = /** @class */ (function () {
  90968. function ArrayItem() {
  90969. }
  90970. ArrayItem.Assign = function (values) {
  90971. if (values) {
  90972. for (var index = 0; index < values.length; index++) {
  90973. values[index]._index = index;
  90974. }
  90975. }
  90976. };
  90977. return ArrayItem;
  90978. }());
  90979. GLTF2.ArrayItem = ArrayItem;
  90980. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90981. })(BABYLON || (BABYLON = {}));
  90982. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90983. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90984. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90985. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90986. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90987. var BABYLON;
  90988. (function (BABYLON) {
  90989. var GLTF2;
  90990. (function (GLTF2) {
  90991. var GLTFLoader = /** @class */ (function () {
  90992. function GLTFLoader() {
  90993. this._completePromises = new Array();
  90994. this._disposed = false;
  90995. this._state = null;
  90996. this._extensions = {};
  90997. this._defaultSampler = {};
  90998. this._requests = new Array();
  90999. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91000. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91001. this.compileMaterials = false;
  91002. this.useClipPlane = false;
  91003. this.compileShadowGenerators = false;
  91004. this.onDisposeObservable = new BABYLON.Observable();
  91005. this.onMeshLoadedObservable = new BABYLON.Observable();
  91006. this.onTextureLoadedObservable = new BABYLON.Observable();
  91007. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91008. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91009. this.onCompleteObservable = new BABYLON.Observable();
  91010. }
  91011. GLTFLoader._Register = function (name, factory) {
  91012. if (GLTFLoader._Factories[name]) {
  91013. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  91014. return;
  91015. }
  91016. GLTFLoader._Factories[name] = factory;
  91017. // Keep the order of registration so that extensions registered first are called first.
  91018. GLTFLoader._Names.push(name);
  91019. };
  91020. Object.defineProperty(GLTFLoader.prototype, "state", {
  91021. get: function () {
  91022. return this._state;
  91023. },
  91024. enumerable: true,
  91025. configurable: true
  91026. });
  91027. GLTFLoader.prototype.dispose = function () {
  91028. if (this._disposed) {
  91029. return;
  91030. }
  91031. this._disposed = true;
  91032. this.onDisposeObservable.notifyObservers(this);
  91033. this.onDisposeObservable.clear();
  91034. this._clear();
  91035. };
  91036. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91037. var _this = this;
  91038. return Promise.resolve().then(function () {
  91039. var nodes = null;
  91040. if (meshesNames) {
  91041. var nodeMap_1 = {};
  91042. if (_this._gltf.nodes) {
  91043. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  91044. var node = _a[_i];
  91045. if (node.name) {
  91046. nodeMap_1[node.name] = node;
  91047. }
  91048. }
  91049. }
  91050. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  91051. nodes = names.map(function (name) {
  91052. var node = nodeMap_1[name];
  91053. if (!node) {
  91054. throw new Error("Failed to find node " + name);
  91055. }
  91056. return node;
  91057. });
  91058. }
  91059. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  91060. return {
  91061. meshes: _this._getMeshes(),
  91062. particleSystems: [],
  91063. skeletons: _this._getSkeletons(),
  91064. };
  91065. });
  91066. });
  91067. };
  91068. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91069. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  91070. };
  91071. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  91072. var _this = this;
  91073. return Promise.resolve().then(function () {
  91074. _this._loadExtensions();
  91075. _this._babylonScene = scene;
  91076. _this._rootUrl = rootUrl;
  91077. _this._progressCallback = onProgress;
  91078. _this._state = BABYLON.GLTFLoaderState.Loading;
  91079. _this._loadData(data);
  91080. var promises = new Array();
  91081. if (nodes) {
  91082. promises.push(_this._loadNodesAsync(nodes));
  91083. }
  91084. else {
  91085. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  91086. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  91087. }
  91088. if (_this.compileMaterials) {
  91089. promises.push(_this._compileMaterialsAsync());
  91090. }
  91091. if (_this.compileShadowGenerators) {
  91092. promises.push(_this._compileShadowGeneratorsAsync());
  91093. }
  91094. return Promise.all(promises).then(function () {
  91095. _this._state = BABYLON.GLTFLoaderState.Ready;
  91096. _this._startAnimations();
  91097. BABYLON.Tools.SetImmediate(function () {
  91098. if (!_this._disposed) {
  91099. Promise.all(_this._completePromises).then(function () {
  91100. _this._state = BABYLON.GLTFLoaderState.Complete;
  91101. _this.onCompleteObservable.notifyObservers(_this);
  91102. _this.onCompleteObservable.clear();
  91103. _this._clear();
  91104. }).catch(function (error) {
  91105. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91106. _this._clear();
  91107. });
  91108. }
  91109. });
  91110. });
  91111. }).catch(function (error) {
  91112. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91113. _this._clear();
  91114. throw error;
  91115. });
  91116. };
  91117. GLTFLoader.prototype._loadExtensions = function () {
  91118. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91119. var name_1 = _a[_i];
  91120. var extension = GLTFLoader._Factories[name_1](this);
  91121. this._extensions[name_1] = extension;
  91122. this.onExtensionLoadedObservable.notifyObservers(extension);
  91123. }
  91124. this.onExtensionLoadedObservable.clear();
  91125. };
  91126. GLTFLoader.prototype._loadData = function (data) {
  91127. this._gltf = data.json;
  91128. this._setupData();
  91129. if (data.bin) {
  91130. var buffers = this._gltf.buffers;
  91131. if (buffers && buffers[0] && !buffers[0].uri) {
  91132. var binaryBuffer = buffers[0];
  91133. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  91134. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  91135. }
  91136. binaryBuffer._data = Promise.resolve(data.bin);
  91137. }
  91138. else {
  91139. BABYLON.Tools.Warn("Unexpected BIN chunk");
  91140. }
  91141. }
  91142. };
  91143. GLTFLoader.prototype._setupData = function () {
  91144. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  91145. GLTF2.ArrayItem.Assign(this._gltf.animations);
  91146. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  91147. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  91148. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  91149. GLTF2.ArrayItem.Assign(this._gltf.images);
  91150. GLTF2.ArrayItem.Assign(this._gltf.materials);
  91151. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  91152. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  91153. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  91154. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  91155. GLTF2.ArrayItem.Assign(this._gltf.skins);
  91156. GLTF2.ArrayItem.Assign(this._gltf.textures);
  91157. if (this._gltf.nodes) {
  91158. var nodeParents = {};
  91159. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  91160. var node = _a[_i];
  91161. if (node.children) {
  91162. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  91163. var index = _c[_b];
  91164. nodeParents[index] = node._index;
  91165. }
  91166. }
  91167. }
  91168. var rootNode = this._createRootNode();
  91169. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  91170. var node = _e[_d];
  91171. var parentIndex = nodeParents[node._index];
  91172. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  91173. }
  91174. }
  91175. };
  91176. GLTFLoader.prototype._createRootNode = function () {
  91177. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  91178. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  91179. switch (this.coordinateSystemMode) {
  91180. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  91181. if (!this._babylonScene.useRightHandedSystem) {
  91182. rootNode.rotation = [0, 1, 0, 0];
  91183. rootNode.scale = [1, 1, -1];
  91184. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  91185. }
  91186. break;
  91187. }
  91188. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  91189. this._babylonScene.useRightHandedSystem = true;
  91190. break;
  91191. }
  91192. default: {
  91193. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  91194. }
  91195. }
  91196. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  91197. return rootNode;
  91198. };
  91199. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  91200. var promises = new Array();
  91201. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  91202. var node = nodes_1[_i];
  91203. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91204. }
  91205. promises.push(this._loadAnimationsAsync());
  91206. return Promise.all(promises).then(function () { });
  91207. };
  91208. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  91209. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  91210. if (promise) {
  91211. return promise;
  91212. }
  91213. var promises = new Array();
  91214. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  91215. var index = _a[_i];
  91216. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  91217. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91218. }
  91219. promises.push(this._loadAnimationsAsync());
  91220. return Promise.all(promises).then(function () { });
  91221. };
  91222. GLTFLoader.prototype._getMeshes = function () {
  91223. var meshes = new Array();
  91224. // Root mesh is always first.
  91225. meshes.push(this._rootBabylonMesh);
  91226. var nodes = this._gltf.nodes;
  91227. if (nodes) {
  91228. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  91229. var node = nodes_2[_i];
  91230. if (node._babylonMesh) {
  91231. meshes.push(node._babylonMesh);
  91232. }
  91233. if (node._primitiveBabylonMeshes) {
  91234. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  91235. var babylonMesh = _b[_a];
  91236. meshes.push(babylonMesh);
  91237. }
  91238. }
  91239. }
  91240. }
  91241. return meshes;
  91242. };
  91243. GLTFLoader.prototype._getSkeletons = function () {
  91244. var skeletons = new Array();
  91245. var skins = this._gltf.skins;
  91246. if (skins) {
  91247. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  91248. var skin = skins_1[_i];
  91249. if (skin._babylonSkeleton) {
  91250. skeletons.push(skin._babylonSkeleton);
  91251. }
  91252. }
  91253. }
  91254. return skeletons;
  91255. };
  91256. GLTFLoader.prototype._startAnimations = function () {
  91257. var animations = this._gltf.animations;
  91258. if (!animations) {
  91259. return;
  91260. }
  91261. switch (this.animationStartMode) {
  91262. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  91263. // do nothing
  91264. break;
  91265. }
  91266. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  91267. var animation = animations[0];
  91268. animation._babylonAnimationGroup.start(true);
  91269. break;
  91270. }
  91271. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  91272. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  91273. var animation = animations_1[_i];
  91274. animation._babylonAnimationGroup.start(true);
  91275. }
  91276. break;
  91277. }
  91278. default: {
  91279. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  91280. return;
  91281. }
  91282. }
  91283. };
  91284. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  91285. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  91286. if (promise) {
  91287. return promise;
  91288. }
  91289. if (node._babylonMesh) {
  91290. throw new Error(context + ": Invalid recursive node hierarchy");
  91291. }
  91292. var promises = new Array();
  91293. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  91294. node._babylonMesh = babylonMesh;
  91295. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91296. node._babylonAnimationTargets.push(babylonMesh);
  91297. GLTFLoader._LoadTransform(node, babylonMesh);
  91298. if (node.mesh != undefined) {
  91299. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  91300. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  91301. }
  91302. if (node.children) {
  91303. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91304. var index = _a[_i];
  91305. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  91306. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  91307. }
  91308. }
  91309. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91310. return Promise.all(promises).then(function () { });
  91311. };
  91312. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  91313. // TODO: instancing
  91314. var promises = new Array();
  91315. var primitives = mesh.primitives;
  91316. if (!primitives || primitives.length === 0) {
  91317. throw new Error(context + ": Primitives are missing");
  91318. }
  91319. GLTF2.ArrayItem.Assign(primitives);
  91320. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  91321. var primitive = primitives_1[_i];
  91322. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  91323. }
  91324. if (node.skin != undefined) {
  91325. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  91326. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  91327. }
  91328. return Promise.all(promises).then(function () {
  91329. if (node._primitiveBabylonMeshes) {
  91330. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91331. var primitiveBabylonMesh = _a[_i];
  91332. primitiveBabylonMesh._refreshBoundingInfo(true);
  91333. }
  91334. }
  91335. });
  91336. };
  91337. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  91338. var _this = this;
  91339. var promises = new Array();
  91340. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  91341. babylonMesh.setEnabled(false);
  91342. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  91343. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  91344. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  91345. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  91346. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  91347. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  91348. }));
  91349. if (primitive.material == undefined) {
  91350. babylonMesh.material = this._getDefaultMaterial();
  91351. }
  91352. else {
  91353. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  91354. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  91355. }
  91356. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91357. return Promise.all(promises).then(function () {
  91358. babylonMesh.setEnabled(true);
  91359. });
  91360. };
  91361. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  91362. var _this = this;
  91363. var attributes = primitive.attributes;
  91364. if (!attributes) {
  91365. throw new Error(context + ": Attributes are missing");
  91366. }
  91367. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91368. // TODO: handle other primitive modes
  91369. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91370. }
  91371. var promises = new Array();
  91372. var babylonVertexData = new BABYLON.VertexData();
  91373. if (primitive.indices == undefined) {
  91374. var positionAccessorIndex = attributes["POSITION"];
  91375. if (positionAccessorIndex != undefined) {
  91376. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91377. babylonVertexData.indices = new Uint32Array(accessor.count);
  91378. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91379. babylonVertexData.indices[i] = i;
  91380. }
  91381. }
  91382. }
  91383. else {
  91384. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91385. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91386. babylonVertexData.indices = data;
  91387. }));
  91388. }
  91389. var loadAttribute = function (attribute, kind) {
  91390. if (attributes[attribute] == undefined) {
  91391. return;
  91392. }
  91393. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91394. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91395. babylonMesh._delayInfo.push(kind);
  91396. }
  91397. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91398. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91399. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91400. if (attribute === "COLOR_0") {
  91401. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91402. babylonMesh.hasVertexAlpha = true;
  91403. if (accessor.type === "VEC3") {
  91404. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91405. }
  91406. }
  91407. babylonVertexData.set(attributeData, kind);
  91408. }));
  91409. };
  91410. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91411. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91412. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91413. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91414. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91415. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91416. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91417. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91418. return Promise.all(promises).then(function () {
  91419. return babylonVertexData;
  91420. });
  91421. };
  91422. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91423. if (!primitive.targets) {
  91424. return;
  91425. }
  91426. if (node._numMorphTargets == undefined) {
  91427. node._numMorphTargets = primitive.targets.length;
  91428. }
  91429. else if (primitive.targets.length !== node._numMorphTargets) {
  91430. throw new Error(context + ": Primitives do not have the same number of targets");
  91431. }
  91432. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91433. for (var index = 0; index < primitive.targets.length; index++) {
  91434. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91435. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91436. // TODO: tell the target whether it has positions, normals, tangents
  91437. }
  91438. };
  91439. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91440. if (!primitive.targets) {
  91441. return Promise.resolve();
  91442. }
  91443. var promises = new Array();
  91444. var morphTargetManager = babylonMesh.morphTargetManager;
  91445. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91446. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91447. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91448. }
  91449. return Promise.all(promises).then(function () { });
  91450. };
  91451. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91452. var _this = this;
  91453. var promises = new Array();
  91454. var loadAttribute = function (attribute, setData) {
  91455. if (attributes[attribute] == undefined) {
  91456. return;
  91457. }
  91458. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91459. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91460. setData(data);
  91461. }));
  91462. };
  91463. loadAttribute("POSITION", function (data) {
  91464. if (babylonVertexData.positions) {
  91465. for (var i = 0; i < data.length; i++) {
  91466. data[i] += babylonVertexData.positions[i];
  91467. }
  91468. babylonMorphTarget.setPositions(data);
  91469. }
  91470. });
  91471. loadAttribute("NORMAL", function (data) {
  91472. if (babylonVertexData.normals) {
  91473. for (var i = 0; i < data.length; i++) {
  91474. data[i] += babylonVertexData.normals[i];
  91475. }
  91476. babylonMorphTarget.setNormals(data);
  91477. }
  91478. });
  91479. loadAttribute("TANGENT", function (data) {
  91480. if (babylonVertexData.tangents) {
  91481. // Tangent data for morph targets is stored as xyz delta.
  91482. // The vertexData.tangent is stored as xyzw.
  91483. // So we need to skip every fourth vertexData.tangent.
  91484. for (var i = 0, j = 0; i < data.length; i++) {
  91485. data[i] += babylonVertexData.tangents[j++];
  91486. if ((i + 1) % 3 == 0) {
  91487. j++;
  91488. }
  91489. }
  91490. babylonMorphTarget.setTangents(data);
  91491. }
  91492. });
  91493. return Promise.all(promises).then(function () { });
  91494. };
  91495. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91496. if (accessor.componentType == 5126 /* FLOAT */) {
  91497. return data;
  91498. }
  91499. var factor = 1;
  91500. if (accessor.normalized) {
  91501. switch (accessor.componentType) {
  91502. case 5121 /* UNSIGNED_BYTE */: {
  91503. factor = 1 / 255;
  91504. break;
  91505. }
  91506. case 5123 /* UNSIGNED_SHORT */: {
  91507. factor = 1 / 65535;
  91508. break;
  91509. }
  91510. default: {
  91511. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91512. }
  91513. }
  91514. }
  91515. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91516. for (var i = 0; i < result.length; i++) {
  91517. result[i] = data[i] * factor;
  91518. }
  91519. return result;
  91520. };
  91521. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91522. var result = new Float32Array(data.length / 3 * 4);
  91523. var offset = 0;
  91524. for (var i = 0; i < result.length; i++) {
  91525. if ((i + 1) % 4 === 0) {
  91526. result[i] = 1;
  91527. }
  91528. else {
  91529. result[i] = data[offset++];
  91530. }
  91531. }
  91532. return result;
  91533. };
  91534. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91535. var position = BABYLON.Vector3.Zero();
  91536. var rotation = BABYLON.Quaternion.Identity();
  91537. var scaling = BABYLON.Vector3.One();
  91538. if (node.matrix) {
  91539. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91540. matrix.decompose(scaling, rotation, position);
  91541. }
  91542. else {
  91543. if (node.translation)
  91544. position = BABYLON.Vector3.FromArray(node.translation);
  91545. if (node.rotation)
  91546. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91547. if (node.scale)
  91548. scaling = BABYLON.Vector3.FromArray(node.scale);
  91549. }
  91550. babylonNode.position = position;
  91551. babylonNode.rotationQuaternion = rotation;
  91552. babylonNode.scaling = scaling;
  91553. };
  91554. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91555. var _this = this;
  91556. var assignSkeleton = function () {
  91557. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91558. var babylonMesh = _a[_i];
  91559. babylonMesh.skeleton = skin._babylonSkeleton;
  91560. }
  91561. node._babylonMesh.parent = _this._rootBabylonMesh;
  91562. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91563. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91564. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91565. };
  91566. if (skin._loaded) {
  91567. assignSkeleton();
  91568. return skin._loaded;
  91569. }
  91570. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91571. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91572. var skeletonId = "skeleton" + skin._index;
  91573. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91574. skin._babylonSkeleton = babylonSkeleton;
  91575. _this._loadBones(context, skin, inverseBindMatricesData);
  91576. assignSkeleton();
  91577. }));
  91578. };
  91579. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91580. if (skin.inverseBindMatrices == undefined) {
  91581. return Promise.resolve(null);
  91582. }
  91583. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91584. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91585. return data;
  91586. });
  91587. };
  91588. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91589. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91590. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91591. node._babylonAnimationTargets.push(babylonBone);
  91592. return babylonBone;
  91593. };
  91594. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91595. var babylonBones = {};
  91596. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91597. var index = _a[_i];
  91598. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91599. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91600. }
  91601. };
  91602. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91603. var babylonBone = babylonBones[node._index];
  91604. if (babylonBone) {
  91605. return babylonBone;
  91606. }
  91607. var boneIndex = skin.joints.indexOf(node._index);
  91608. var baseMatrix = BABYLON.Matrix.Identity();
  91609. if (inverseBindMatricesData && boneIndex !== -1) {
  91610. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91611. baseMatrix.invertToRef(baseMatrix);
  91612. }
  91613. var babylonParentBone = null;
  91614. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91615. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91616. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91617. }
  91618. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91619. babylonBones[node._index] = babylonBone;
  91620. return babylonBone;
  91621. };
  91622. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91623. return node.matrix ?
  91624. BABYLON.Matrix.FromArray(node.matrix) :
  91625. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  91626. };
  91627. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91628. var animations = this._gltf.animations;
  91629. if (!animations) {
  91630. return Promise.resolve();
  91631. }
  91632. var promises = new Array();
  91633. for (var index = 0; index < animations.length; index++) {
  91634. var animation = animations[index];
  91635. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91636. }
  91637. return Promise.all(promises).then(function () { });
  91638. };
  91639. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91640. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91641. animation._babylonAnimationGroup = babylonAnimationGroup;
  91642. var promises = new Array();
  91643. GLTF2.ArrayItem.Assign(animation.channels);
  91644. GLTF2.ArrayItem.Assign(animation.samplers);
  91645. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91646. var channel = _a[_i];
  91647. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91648. }
  91649. return Promise.all(promises).then(function () {
  91650. babylonAnimationGroup.normalize();
  91651. });
  91652. };
  91653. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91654. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91655. if (!targetNode._babylonMesh) {
  91656. return Promise.resolve();
  91657. }
  91658. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91659. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91660. var targetPath;
  91661. var animationType;
  91662. switch (channel.target.path) {
  91663. case "translation" /* TRANSLATION */: {
  91664. targetPath = "position";
  91665. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91666. break;
  91667. }
  91668. case "rotation" /* ROTATION */: {
  91669. targetPath = "rotationQuaternion";
  91670. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91671. break;
  91672. }
  91673. case "scale" /* SCALE */: {
  91674. targetPath = "scaling";
  91675. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91676. break;
  91677. }
  91678. case "weights" /* WEIGHTS */: {
  91679. targetPath = "influence";
  91680. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91681. break;
  91682. }
  91683. default: {
  91684. throw new Error(context + ": Invalid target path " + channel.target.path);
  91685. }
  91686. }
  91687. var outputBufferOffset = 0;
  91688. var getNextOutputValue;
  91689. switch (targetPath) {
  91690. case "position": {
  91691. getNextOutputValue = function () {
  91692. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91693. outputBufferOffset += 3;
  91694. return value;
  91695. };
  91696. break;
  91697. }
  91698. case "rotationQuaternion": {
  91699. getNextOutputValue = function () {
  91700. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91701. outputBufferOffset += 4;
  91702. return value;
  91703. };
  91704. break;
  91705. }
  91706. case "scaling": {
  91707. getNextOutputValue = function () {
  91708. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91709. outputBufferOffset += 3;
  91710. return value;
  91711. };
  91712. break;
  91713. }
  91714. case "influence": {
  91715. getNextOutputValue = function () {
  91716. var value = new Array(targetNode._numMorphTargets);
  91717. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91718. value[i] = data.output[outputBufferOffset++];
  91719. }
  91720. return value;
  91721. };
  91722. break;
  91723. }
  91724. }
  91725. var getNextKey;
  91726. switch (data.interpolation) {
  91727. case "STEP" /* STEP */: {
  91728. getNextKey = function (frameIndex) { return ({
  91729. frame: data.input[frameIndex],
  91730. value: getNextOutputValue(),
  91731. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91732. }); };
  91733. break;
  91734. }
  91735. case "LINEAR" /* LINEAR */: {
  91736. getNextKey = function (frameIndex) { return ({
  91737. frame: data.input[frameIndex],
  91738. value: getNextOutputValue()
  91739. }); };
  91740. break;
  91741. }
  91742. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91743. getNextKey = function (frameIndex) { return ({
  91744. frame: data.input[frameIndex],
  91745. inTangent: getNextOutputValue(),
  91746. value: getNextOutputValue(),
  91747. outTangent: getNextOutputValue()
  91748. }); };
  91749. break;
  91750. }
  91751. }
  91752. var keys;
  91753. if (data.input.length === 1) {
  91754. var key = getNextKey(0);
  91755. keys = [
  91756. { frame: key.frame, value: key.value },
  91757. { frame: key.frame + 1, value: key.value }
  91758. ];
  91759. }
  91760. else {
  91761. keys = new Array(data.input.length);
  91762. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91763. keys[frameIndex] = getNextKey(frameIndex);
  91764. }
  91765. }
  91766. if (targetPath === "influence") {
  91767. var _loop_1 = function (targetIndex) {
  91768. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91769. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91770. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91771. frame: key.frame,
  91772. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91773. value: key.value[targetIndex],
  91774. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91775. }); }));
  91776. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91777. var babylonMesh = _a[_i];
  91778. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91779. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91780. }
  91781. };
  91782. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91783. _loop_1(targetIndex);
  91784. }
  91785. }
  91786. else {
  91787. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91788. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91789. babylonAnimation.setKeys(keys);
  91790. if (targetNode._babylonAnimationTargets) {
  91791. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91792. var target = _a[_i];
  91793. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91794. }
  91795. }
  91796. }
  91797. });
  91798. };
  91799. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91800. if (sampler._data) {
  91801. return sampler._data;
  91802. }
  91803. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91804. switch (interpolation) {
  91805. case "STEP" /* STEP */:
  91806. case "LINEAR" /* LINEAR */:
  91807. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91808. break;
  91809. }
  91810. default: {
  91811. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91812. }
  91813. }
  91814. var inputData;
  91815. var outputData;
  91816. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91817. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91818. sampler._data = Promise.all([
  91819. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91820. inputData = data;
  91821. }),
  91822. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91823. outputData = data;
  91824. })
  91825. ]).then(function () {
  91826. return {
  91827. input: inputData,
  91828. interpolation: interpolation,
  91829. output: outputData,
  91830. };
  91831. });
  91832. return sampler._data;
  91833. };
  91834. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91835. if (buffer._data) {
  91836. return buffer._data;
  91837. }
  91838. if (!buffer.uri) {
  91839. throw new Error(context + ": Uri is missing");
  91840. }
  91841. buffer._data = this._loadUriAsync(context, buffer.uri);
  91842. return buffer._data;
  91843. };
  91844. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91845. if (bufferView._data) {
  91846. return bufferView._data;
  91847. }
  91848. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91849. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91850. try {
  91851. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91852. }
  91853. catch (e) {
  91854. throw new Error(context + ": " + e.message);
  91855. }
  91856. });
  91857. return bufferView._data;
  91858. };
  91859. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91860. var _this = this;
  91861. if (accessor.sparse) {
  91862. throw new Error(context + ": Sparse accessors are not currently supported");
  91863. }
  91864. if (accessor._data) {
  91865. return accessor._data;
  91866. }
  91867. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91868. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91869. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91870. var byteOffset = accessor.byteOffset || 0;
  91871. var byteStride = bufferView.byteStride;
  91872. if (byteStride === 0) {
  91873. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91874. }
  91875. try {
  91876. switch (accessor.componentType) {
  91877. case 5120 /* BYTE */: {
  91878. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91879. }
  91880. case 5121 /* UNSIGNED_BYTE */: {
  91881. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91882. }
  91883. case 5122 /* SHORT */: {
  91884. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91885. }
  91886. case 5123 /* UNSIGNED_SHORT */: {
  91887. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91888. }
  91889. case 5125 /* UNSIGNED_INT */: {
  91890. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91891. }
  91892. case 5126 /* FLOAT */: {
  91893. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91894. }
  91895. default: {
  91896. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91897. }
  91898. }
  91899. }
  91900. catch (e) {
  91901. throw new Error(context + ": " + e);
  91902. }
  91903. });
  91904. return accessor._data;
  91905. };
  91906. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91907. byteOffset += data.byteOffset;
  91908. var targetLength = count * numComponents;
  91909. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91910. return new typedArray(data.buffer, byteOffset, targetLength);
  91911. }
  91912. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91913. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91914. var targetBuffer = new typedArray(targetLength);
  91915. var sourceIndex = 0;
  91916. var targetIndex = 0;
  91917. while (targetIndex < targetLength) {
  91918. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91919. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91920. targetIndex++;
  91921. }
  91922. sourceIndex += elementStride;
  91923. }
  91924. return targetBuffer;
  91925. };
  91926. GLTFLoader.prototype._getDefaultMaterial = function () {
  91927. var id = "__gltf_default";
  91928. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91929. if (!babylonMaterial) {
  91930. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91931. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91932. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91933. babylonMaterial.metallic = 1;
  91934. babylonMaterial.roughness = 1;
  91935. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91936. }
  91937. return babylonMaterial;
  91938. };
  91939. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91940. var promises = new Array();
  91941. var babylonMaterial = material._babylonMaterial;
  91942. // Ensure metallic workflow
  91943. babylonMaterial.metallic = 1;
  91944. babylonMaterial.roughness = 1;
  91945. var properties = material.pbrMetallicRoughness;
  91946. if (properties) {
  91947. if (properties.baseColorFactor) {
  91948. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91949. babylonMaterial.alpha = properties.baseColorFactor[3];
  91950. }
  91951. else {
  91952. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91953. }
  91954. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91955. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91956. if (properties.baseColorTexture) {
  91957. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91958. babylonMaterial.albedoTexture = texture;
  91959. }));
  91960. }
  91961. if (properties.metallicRoughnessTexture) {
  91962. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91963. babylonMaterial.metallicTexture = texture;
  91964. }));
  91965. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91966. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91967. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91968. }
  91969. }
  91970. this._loadMaterialAlphaProperties(context, material);
  91971. return Promise.all(promises).then(function () { });
  91972. };
  91973. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91974. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91975. if (promise) {
  91976. return promise;
  91977. }
  91978. material._babylonMeshes = material._babylonMeshes || [];
  91979. material._babylonMeshes.push(babylonMesh);
  91980. if (material._loaded) {
  91981. babylonMesh.material = material._babylonMaterial;
  91982. return material._loaded;
  91983. }
  91984. var promises = new Array();
  91985. var babylonMaterial = this._createMaterial(material);
  91986. material._babylonMaterial = babylonMaterial;
  91987. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91988. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91989. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91990. babylonMesh.material = babylonMaterial;
  91991. return (material._loaded = Promise.all(promises).then(function () { }));
  91992. };
  91993. GLTFLoader.prototype._createMaterial = function (material) {
  91994. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91995. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91996. return babylonMaterial;
  91997. };
  91998. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91999. var promises = new Array();
  92000. var babylonMaterial = material._babylonMaterial;
  92001. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  92002. if (material.doubleSided) {
  92003. babylonMaterial.backFaceCulling = false;
  92004. babylonMaterial.twoSidedLighting = true;
  92005. }
  92006. if (material.normalTexture) {
  92007. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  92008. babylonMaterial.bumpTexture = texture;
  92009. }));
  92010. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  92011. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  92012. if (material.normalTexture.scale != undefined) {
  92013. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  92014. }
  92015. }
  92016. if (material.occlusionTexture) {
  92017. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  92018. babylonMaterial.ambientTexture = texture;
  92019. }));
  92020. babylonMaterial.useAmbientInGrayScale = true;
  92021. if (material.occlusionTexture.strength != undefined) {
  92022. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  92023. }
  92024. }
  92025. if (material.emissiveTexture) {
  92026. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  92027. babylonMaterial.emissiveTexture = texture;
  92028. }));
  92029. }
  92030. return Promise.all(promises).then(function () { });
  92031. };
  92032. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  92033. var babylonMaterial = material._babylonMaterial;
  92034. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  92035. switch (alphaMode) {
  92036. case "OPAQUE" /* OPAQUE */: {
  92037. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  92038. break;
  92039. }
  92040. case "MASK" /* MASK */: {
  92041. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  92042. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  92043. if (babylonMaterial.alpha) {
  92044. if (babylonMaterial.alpha === 0) {
  92045. babylonMaterial.alphaCutOff = 1;
  92046. }
  92047. else {
  92048. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  92049. }
  92050. babylonMaterial.alpha = 1;
  92051. }
  92052. if (babylonMaterial.albedoTexture) {
  92053. babylonMaterial.albedoTexture.hasAlpha = true;
  92054. }
  92055. break;
  92056. }
  92057. case "BLEND" /* BLEND */: {
  92058. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  92059. if (babylonMaterial.albedoTexture) {
  92060. babylonMaterial.albedoTexture.hasAlpha = true;
  92061. babylonMaterial.useAlphaFromAlbedoTexture = true;
  92062. }
  92063. break;
  92064. }
  92065. default: {
  92066. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  92067. }
  92068. }
  92069. };
  92070. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  92071. var _this = this;
  92072. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  92073. context = "#/textures/" + textureInfo.index;
  92074. var promises = new Array();
  92075. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  92076. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  92077. var deferred = new BABYLON.Deferred();
  92078. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  92079. if (!_this._disposed) {
  92080. deferred.resolve();
  92081. }
  92082. }, function (message, exception) {
  92083. if (!_this._disposed) {
  92084. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  92085. }
  92086. });
  92087. promises.push(deferred.promise);
  92088. babylonTexture.name = texture.name || "texture" + texture._index;
  92089. babylonTexture.wrapU = samplerData.wrapU;
  92090. babylonTexture.wrapV = samplerData.wrapV;
  92091. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  92092. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  92093. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  92094. babylonTexture.updateURL(objectURL);
  92095. }));
  92096. assign(babylonTexture);
  92097. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  92098. return Promise.all(promises).then(function () { });
  92099. };
  92100. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  92101. if (!sampler._data) {
  92102. sampler._data = {
  92103. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  92104. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  92105. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  92106. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  92107. };
  92108. }
  92109. ;
  92110. return sampler._data;
  92111. };
  92112. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  92113. if (image._objectURL) {
  92114. return image._objectURL;
  92115. }
  92116. var promise;
  92117. if (image.uri) {
  92118. promise = this._loadUriAsync(context, image.uri);
  92119. }
  92120. else {
  92121. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  92122. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  92123. }
  92124. image._objectURL = promise.then(function (data) {
  92125. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  92126. });
  92127. return image._objectURL;
  92128. };
  92129. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  92130. var _this = this;
  92131. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  92132. if (promise) {
  92133. return promise;
  92134. }
  92135. if (!GLTFLoader._ValidateUri(uri)) {
  92136. throw new Error(context + ": Uri '" + uri + "' is invalid");
  92137. }
  92138. if (BABYLON.Tools.IsBase64(uri)) {
  92139. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  92140. }
  92141. return new Promise(function (resolve, reject) {
  92142. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  92143. if (!_this._disposed) {
  92144. resolve(new Uint8Array(data));
  92145. }
  92146. }, function (event) {
  92147. if (!_this._disposed) {
  92148. try {
  92149. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  92150. request._lengthComputable = event.lengthComputable;
  92151. request._loaded = event.loaded;
  92152. request._total = event.total;
  92153. _this._onProgress();
  92154. }
  92155. }
  92156. catch (e) {
  92157. reject(e);
  92158. }
  92159. }
  92160. }, _this._babylonScene.database, true, function (request, exception) {
  92161. if (!_this._disposed) {
  92162. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  92163. }
  92164. });
  92165. _this._requests.push(request);
  92166. });
  92167. };
  92168. GLTFLoader.prototype._onProgress = function () {
  92169. if (!this._progressCallback) {
  92170. return;
  92171. }
  92172. var lengthComputable = true;
  92173. var loaded = 0;
  92174. var total = 0;
  92175. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92176. var request = _a[_i];
  92177. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  92178. return;
  92179. }
  92180. lengthComputable = lengthComputable && request._lengthComputable;
  92181. loaded += request._loaded;
  92182. total += request._total;
  92183. }
  92184. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  92185. };
  92186. GLTFLoader._GetProperty = function (context, array, index) {
  92187. if (!array || index == undefined || !array[index]) {
  92188. throw new Error(context + ": Failed to find index " + index);
  92189. }
  92190. return array[index];
  92191. };
  92192. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  92193. // Set defaults if undefined
  92194. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  92195. switch (mode) {
  92196. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92197. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92198. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92199. default:
  92200. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  92201. return BABYLON.Texture.WRAP_ADDRESSMODE;
  92202. }
  92203. };
  92204. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  92205. // Set defaults if undefined
  92206. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  92207. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  92208. if (magFilter === 9729 /* LINEAR */) {
  92209. switch (minFilter) {
  92210. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  92211. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  92212. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  92213. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  92214. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  92215. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92216. default:
  92217. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92218. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92219. }
  92220. }
  92221. else {
  92222. if (magFilter !== 9728 /* NEAREST */) {
  92223. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  92224. }
  92225. switch (minFilter) {
  92226. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  92227. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  92228. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92229. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  92230. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  92231. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  92232. default:
  92233. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92234. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92235. }
  92236. }
  92237. };
  92238. GLTFLoader._GetNumComponents = function (context, type) {
  92239. switch (type) {
  92240. case "SCALAR": return 1;
  92241. case "VEC2": return 2;
  92242. case "VEC3": return 3;
  92243. case "VEC4": return 4;
  92244. case "MAT2": return 4;
  92245. case "MAT3": return 9;
  92246. case "MAT4": return 16;
  92247. }
  92248. throw new Error(context + ": Invalid type " + type);
  92249. };
  92250. GLTFLoader._ValidateUri = function (uri) {
  92251. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  92252. };
  92253. GLTFLoader.prototype._compileMaterialsAsync = function () {
  92254. var promises = new Array();
  92255. if (this._gltf.materials) {
  92256. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  92257. var material = _a[_i];
  92258. var babylonMaterial = material._babylonMaterial;
  92259. var babylonMeshes = material._babylonMeshes;
  92260. if (babylonMaterial && babylonMeshes) {
  92261. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  92262. var babylonMesh = babylonMeshes_1[_b];
  92263. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  92264. if (this.useClipPlane) {
  92265. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  92266. }
  92267. }
  92268. }
  92269. }
  92270. }
  92271. return Promise.all(promises).then(function () { });
  92272. };
  92273. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  92274. var promises = new Array();
  92275. var lights = this._babylonScene.lights;
  92276. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  92277. var light = lights_1[_i];
  92278. var generator = light.getShadowGenerator();
  92279. if (generator) {
  92280. promises.push(generator.forceCompilationAsync());
  92281. }
  92282. }
  92283. return Promise.all(promises).then(function () { });
  92284. };
  92285. GLTFLoader.prototype._clear = function () {
  92286. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92287. var request = _a[_i];
  92288. request.abort();
  92289. }
  92290. this._requests.length = 0;
  92291. if (this._gltf && this._gltf.images) {
  92292. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  92293. var image = _c[_b];
  92294. if (image._objectURL) {
  92295. image._objectURL.then(function (value) {
  92296. URL.revokeObjectURL(value);
  92297. });
  92298. image._objectURL = undefined;
  92299. }
  92300. }
  92301. }
  92302. delete this._gltf;
  92303. delete this._babylonScene;
  92304. this._completePromises.length = 0;
  92305. this._extensions = {};
  92306. delete this._rootBabylonMesh;
  92307. delete this._progressCallback;
  92308. this.onMeshLoadedObservable.clear();
  92309. this.onTextureLoadedObservable.clear();
  92310. this.onMaterialLoadedObservable.clear();
  92311. };
  92312. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  92313. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92314. var name_2 = _a[_i];
  92315. var extension = this._extensions[name_2];
  92316. if (extension.enabled) {
  92317. var promise = actionAsync(extension);
  92318. if (promise) {
  92319. return promise;
  92320. }
  92321. }
  92322. }
  92323. return null;
  92324. };
  92325. GLTFLoader._Names = new Array();
  92326. GLTFLoader._Factories = {};
  92327. return GLTFLoader;
  92328. }());
  92329. GLTF2.GLTFLoader = GLTFLoader;
  92330. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  92331. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92332. })(BABYLON || (BABYLON = {}));
  92333. //# sourceMappingURL=babylon.glTFLoader.js.map
  92334. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92335. var BABYLON;
  92336. (function (BABYLON) {
  92337. var GLTF2;
  92338. (function (GLTF2) {
  92339. var GLTFLoaderExtension = /** @class */ (function () {
  92340. function GLTFLoaderExtension(loader) {
  92341. this.enabled = true;
  92342. this._loader = loader;
  92343. }
  92344. // #region Overridable Methods
  92345. /** Override this method to modify the default behavior for loading scenes. */
  92346. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  92347. /** Override this method to modify the default behavior for loading nodes. */
  92348. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  92349. /** Override this method to modify the default behavior for loading materials. */
  92350. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  92351. /** Override this method to modify the default behavior for loading uris. */
  92352. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  92353. // #endregion
  92354. /** Helper method called by a loader extension to load an glTF extension. */
  92355. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  92356. var _this = this;
  92357. if (!property.extensions) {
  92358. return null;
  92359. }
  92360. var extensions = property.extensions;
  92361. var extension = extensions[this.name];
  92362. if (!extension) {
  92363. return null;
  92364. }
  92365. // Clear out the extension before executing the action to avoid recursing into the same property.
  92366. delete extensions[this.name];
  92367. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92368. // Restore the extension after completing the action.
  92369. extensions[_this.name] = extension;
  92370. });
  92371. };
  92372. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92373. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92374. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92375. };
  92376. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92377. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92378. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92379. };
  92380. /** Helper method called by the loader to allow extensions to override loading materials. */
  92381. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92382. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92383. };
  92384. /** Helper method called by the loader to allow extensions to override loading uris. */
  92385. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92386. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92387. };
  92388. return GLTFLoaderExtension;
  92389. }());
  92390. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92391. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92392. })(BABYLON || (BABYLON = {}));
  92393. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92394. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92395. var BABYLON;
  92396. (function (BABYLON) {
  92397. var GLTF2;
  92398. (function (GLTF2) {
  92399. var Extensions;
  92400. (function (Extensions) {
  92401. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92402. var NAME = "MSFT_lod";
  92403. var MSFT_lod = /** @class */ (function (_super) {
  92404. __extends(MSFT_lod, _super);
  92405. function MSFT_lod() {
  92406. var _this = _super !== null && _super.apply(this, arguments) || this;
  92407. _this.name = NAME;
  92408. /**
  92409. * Maximum number of LODs to load, starting from the lowest LOD.
  92410. */
  92411. _this.maxLODsToLoad = Number.MAX_VALUE;
  92412. _this._loadingNodeLOD = null;
  92413. _this._loadNodeSignals = {};
  92414. _this._loadingMaterialLOD = null;
  92415. _this._loadMaterialSignals = {};
  92416. return _this;
  92417. }
  92418. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92419. var _this = this;
  92420. return this._loadExtensionAsync(context, node, function (context, extension) {
  92421. var firstPromise;
  92422. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92423. var _loop_1 = function (indexLOD) {
  92424. var nodeLOD = nodeLODs[indexLOD];
  92425. if (indexLOD !== 0) {
  92426. _this._loadingNodeLOD = nodeLOD;
  92427. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92428. }
  92429. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92430. if (indexLOD !== 0) {
  92431. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92432. previousNodeLOD._babylonMesh.setEnabled(false);
  92433. }
  92434. if (indexLOD !== nodeLODs.length - 1) {
  92435. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92436. _this._loadNodeSignals[nodeIndex].resolve();
  92437. delete _this._loadNodeSignals[nodeIndex];
  92438. }
  92439. });
  92440. if (indexLOD === 0) {
  92441. firstPromise = promise;
  92442. }
  92443. else {
  92444. _this._loader._completePromises.push(promise);
  92445. _this._loadingNodeLOD = null;
  92446. }
  92447. };
  92448. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92449. _loop_1(indexLOD);
  92450. }
  92451. return firstPromise;
  92452. });
  92453. };
  92454. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92455. var _this = this;
  92456. // Don't load material LODs if already loading a node LOD.
  92457. if (this._loadingNodeLOD) {
  92458. return null;
  92459. }
  92460. return this._loadExtensionAsync(context, material, function (context, extension) {
  92461. var firstPromise;
  92462. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92463. var _loop_2 = function (indexLOD) {
  92464. var materialLOD = materialLODs[indexLOD];
  92465. if (indexLOD !== 0) {
  92466. _this._loadingMaterialLOD = materialLOD;
  92467. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92468. }
  92469. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92470. if (indexLOD !== materialLODs.length - 1) {
  92471. var materialIndex = materialLODs[indexLOD + 1]._index;
  92472. _this._loadMaterialSignals[materialIndex].resolve();
  92473. delete _this._loadMaterialSignals[materialIndex];
  92474. }
  92475. });
  92476. if (indexLOD === 0) {
  92477. firstPromise = promise;
  92478. }
  92479. else {
  92480. _this._loader._completePromises.push(promise);
  92481. _this._loadingMaterialLOD = null;
  92482. }
  92483. };
  92484. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92485. _loop_2(indexLOD);
  92486. }
  92487. return firstPromise;
  92488. });
  92489. };
  92490. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92491. var _this = this;
  92492. // Defer the loading of uris if loading a material or node LOD.
  92493. if (this._loadingMaterialLOD) {
  92494. var index = this._loadingMaterialLOD._index;
  92495. return this._loadMaterialSignals[index].promise.then(function () {
  92496. return _this._loader._loadUriAsync(context, uri);
  92497. });
  92498. }
  92499. else if (this._loadingNodeLOD) {
  92500. var index = this._loadingNodeLOD._index;
  92501. return this._loadNodeSignals[index].promise.then(function () {
  92502. return _this._loader._loadUriAsync(context, uri);
  92503. });
  92504. }
  92505. return null;
  92506. };
  92507. /**
  92508. * Gets an array of LOD properties from lowest to highest.
  92509. */
  92510. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92511. if (this.maxLODsToLoad <= 0) {
  92512. throw new Error("maxLODsToLoad must be greater than zero");
  92513. }
  92514. var properties = new Array();
  92515. for (var i = ids.length - 1; i >= 0; i--) {
  92516. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92517. if (properties.length === this.maxLODsToLoad) {
  92518. return properties;
  92519. }
  92520. }
  92521. properties.push(property);
  92522. return properties;
  92523. };
  92524. return MSFT_lod;
  92525. }(GLTF2.GLTFLoaderExtension));
  92526. Extensions.MSFT_lod = MSFT_lod;
  92527. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92528. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92529. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92530. })(BABYLON || (BABYLON = {}));
  92531. //# sourceMappingURL=MSFT_lod.js.map
  92532. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92533. var BABYLON;
  92534. (function (BABYLON) {
  92535. var GLTF2;
  92536. (function (GLTF2) {
  92537. var Extensions;
  92538. (function (Extensions) {
  92539. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92540. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92541. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92542. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92543. function KHR_materials_pbrSpecularGlossiness() {
  92544. var _this = _super !== null && _super.apply(this, arguments) || this;
  92545. _this.name = NAME;
  92546. return _this;
  92547. }
  92548. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92549. var _this = this;
  92550. return this._loadExtensionAsync(context, material, function (context, extension) {
  92551. material._babylonMeshes = material._babylonMeshes || [];
  92552. material._babylonMeshes.push(babylonMesh);
  92553. if (material._loaded) {
  92554. babylonMesh.material = material._babylonMaterial;
  92555. return material._loaded;
  92556. }
  92557. var promises = new Array();
  92558. var babylonMaterial = _this._loader._createMaterial(material);
  92559. material._babylonMaterial = babylonMaterial;
  92560. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92561. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92562. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92563. babylonMesh.material = babylonMaterial;
  92564. return (material._loaded = Promise.all(promises).then(function () { }));
  92565. });
  92566. };
  92567. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92568. var promises = new Array();
  92569. var babylonMaterial = material._babylonMaterial;
  92570. if (properties.diffuseFactor) {
  92571. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92572. babylonMaterial.alpha = properties.diffuseFactor[3];
  92573. }
  92574. else {
  92575. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92576. }
  92577. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92578. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92579. if (properties.diffuseTexture) {
  92580. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92581. babylonMaterial.albedoTexture = texture;
  92582. }));
  92583. }
  92584. if (properties.specularGlossinessTexture) {
  92585. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92586. babylonMaterial.reflectivityTexture = texture;
  92587. }));
  92588. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92589. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92590. }
  92591. loader._loadMaterialAlphaProperties(context, material);
  92592. return Promise.all(promises).then(function () { });
  92593. };
  92594. return KHR_materials_pbrSpecularGlossiness;
  92595. }(GLTF2.GLTFLoaderExtension));
  92596. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92597. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92598. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92599. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92600. })(BABYLON || (BABYLON = {}));
  92601. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92602. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92603. var BABYLON;
  92604. (function (BABYLON) {
  92605. var GLTF2;
  92606. (function (GLTF2) {
  92607. var Extensions;
  92608. (function (Extensions) {
  92609. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92610. var NAME = "KHR_lights";
  92611. var LightType;
  92612. (function (LightType) {
  92613. LightType["AMBIENT"] = "ambient";
  92614. LightType["DIRECTIONAL"] = "directional";
  92615. LightType["POINT"] = "point";
  92616. LightType["SPOT"] = "spot";
  92617. })(LightType || (LightType = {}));
  92618. var KHR_lights = /** @class */ (function (_super) {
  92619. __extends(KHR_lights, _super);
  92620. function KHR_lights() {
  92621. var _this = _super !== null && _super.apply(this, arguments) || this;
  92622. _this.name = NAME;
  92623. return _this;
  92624. }
  92625. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92626. var _this = this;
  92627. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92628. var promise = _this._loader._loadSceneAsync(context, scene);
  92629. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92630. if (light.type !== LightType.AMBIENT) {
  92631. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92632. }
  92633. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92634. return promise;
  92635. });
  92636. };
  92637. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92638. var _this = this;
  92639. return this._loadExtensionAsync(context, node, function (context, extension) {
  92640. var promise = _this._loader._loadNodeAsync(context, node);
  92641. var babylonLight;
  92642. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92643. var name = node._babylonMesh.name;
  92644. switch (light.type) {
  92645. case LightType.AMBIENT: {
  92646. throw new Error(context + ": Ambient lights are not allowed on a node");
  92647. }
  92648. case LightType.DIRECTIONAL: {
  92649. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92650. break;
  92651. }
  92652. case LightType.POINT: {
  92653. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92654. break;
  92655. }
  92656. case LightType.SPOT: {
  92657. var spotLight = light;
  92658. // TODO: support inner and outer cone angles
  92659. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92660. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92661. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92662. break;
  92663. }
  92664. default: {
  92665. throw new Error(context + ": Invalid light type " + light.type);
  92666. }
  92667. }
  92668. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92669. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92670. babylonLight.parent = node._babylonMesh;
  92671. return promise;
  92672. });
  92673. };
  92674. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92675. get: function () {
  92676. var extensions = this._loader._gltf.extensions;
  92677. if (!extensions || !extensions[this.name]) {
  92678. throw new Error("#/extensions: " + this.name + " not found");
  92679. }
  92680. var extension = extensions[this.name];
  92681. return extension.lights;
  92682. },
  92683. enumerable: true,
  92684. configurable: true
  92685. });
  92686. return KHR_lights;
  92687. }(GLTF2.GLTFLoaderExtension));
  92688. Extensions.KHR_lights = KHR_lights;
  92689. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92690. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92691. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92692. })(BABYLON || (BABYLON = {}));
  92693. //# sourceMappingURL=KHR_lights.js.map
  92694. (function universalModuleDefinition(root, factory) {
  92695. var f = factory();
  92696. if (root && root["BABYLON"]) {
  92697. return;
  92698. }
  92699. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92700. globalObject["BABYLON"] = f;
  92701. if(typeof exports === 'object' && typeof module === 'object')
  92702. module.exports = f;
  92703. else if(typeof define === 'function' && define.amd)
  92704. define(["BABYLON"], factory);
  92705. else if(typeof exports === 'object')
  92706. exports["BABYLON"] = f;
  92707. else {
  92708. root["BABYLON"] = f;
  92709. }
  92710. })(this, function() {
  92711. return BABYLON;
  92712. });